@anfenn/dync 1.0.25 → 1.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,18 +1,3839 @@
1
- import {
2
- Dync,
3
- MemoryAdapter,
4
- MemoryQueryContext,
5
- SQLiteAdapter,
6
- SqliteQueryContext,
7
- SyncAction,
8
- createLocalId
9
- } from "./chunk-QA2TX54K.js";
10
1
  import "./chunk-SQB6E7V2.js";
2
+
3
+ // src/logger.ts
4
+ function newLogger(base, min) {
5
+ const order = {
6
+ debug: 10,
7
+ info: 20,
8
+ warn: 30,
9
+ error: 40,
10
+ none: 100
11
+ };
12
+ const threshold = order[min];
13
+ const enabled = (lvl) => order[lvl] >= threshold;
14
+ return {
15
+ debug: (...a) => enabled("debug") && base.debug?.(...a),
16
+ info: (...a) => enabled("info") && base.info?.(...a),
17
+ warn: (...a) => enabled("warn") && base.warn?.(...a),
18
+ error: (...a) => enabled("error") && base.error?.(...a)
19
+ };
20
+ }
21
+
22
+ // src/types.ts
23
+ var SERVER_PK = "id";
24
+ var LOCAL_PK = "_localId";
25
+ var UPDATED_AT = "updated_at";
26
+ var ApiError = class extends Error {
27
+ isNetworkError;
28
+ cause;
29
+ constructor(message, isNetworkError2, cause) {
30
+ super(message);
31
+ this.name = "ApiError";
32
+ this.isNetworkError = isNetworkError2;
33
+ this.cause = cause;
34
+ }
35
+ };
36
+ var SyncAction = /* @__PURE__ */ ((SyncAction2) => {
37
+ SyncAction2["Create"] = "create";
38
+ SyncAction2["Update"] = "update";
39
+ SyncAction2["Remove"] = "remove";
40
+ return SyncAction2;
41
+ })(SyncAction || {});
42
+
43
+ // src/createLocalId.ts
44
+ function createLocalId() {
45
+ if (typeof globalThis.crypto?.randomUUID === "function") {
46
+ return globalThis.crypto.randomUUID();
47
+ }
48
+ throw new Error("createLocalId(): crypto.randomUUID is not available");
49
+ }
50
+
51
+ // src/helpers.ts
52
+ function parseApiError(error) {
53
+ if (error instanceof ApiError) {
54
+ return error;
55
+ }
56
+ if (typeof error === "string") {
57
+ return new ApiError(error, false);
58
+ }
59
+ return new ApiError(error.message, isNetworkError(error), error);
60
+ }
61
+ function isNetworkError(error) {
62
+ const message = error.message?.toLowerCase() ?? "";
63
+ const name = error.name;
64
+ if (message.includes("failed to fetch") || message.includes("network request failed")) {
65
+ return true;
66
+ }
67
+ const code = error.code;
68
+ if (code === "ERR_NETWORK" || code === "ECONNABORTED" || code === "ENOTFOUND" || code === "ECONNREFUSED") {
69
+ return true;
70
+ }
71
+ if (error.isAxiosError && error.response === void 0) {
72
+ return true;
73
+ }
74
+ if (name === "ApolloError" && error.networkError) {
75
+ return true;
76
+ }
77
+ if (message.includes("network error") || message.includes("networkerror")) {
78
+ return true;
79
+ }
80
+ return false;
81
+ }
82
+ function sleep(ms, signal) {
83
+ return new Promise((resolve) => {
84
+ if (signal?.aborted) {
85
+ resolve();
86
+ return;
87
+ }
88
+ const timer = setTimeout(resolve, ms);
89
+ signal?.addEventListener("abort", () => {
90
+ clearTimeout(timer);
91
+ resolve();
92
+ });
93
+ });
94
+ }
95
+ function orderFor(a) {
96
+ switch (a) {
97
+ case "create" /* Create */:
98
+ return 1;
99
+ case "update" /* Update */:
100
+ return 2;
101
+ case "remove" /* Remove */:
102
+ return 3;
103
+ }
104
+ }
105
+ function omitFields(item, fields) {
106
+ const result = { ...item };
107
+ for (const k of fields) delete result[k];
108
+ return result;
109
+ }
110
+ function deleteKeyIfEmptyObject(obj, key) {
111
+ if (obj[key] && Object.keys(obj[key]).length === 0) {
112
+ delete obj[key];
113
+ }
114
+ }
115
+
116
+ // src/addVisibilityChangeListener.ts
117
+ function addVisibilityChangeListener(add, currentSubscription, onVisibilityChange) {
118
+ if (add && !currentSubscription) {
119
+ const handler = () => {
120
+ onVisibilityChange(document.visibilityState === "visible");
121
+ };
122
+ document.addEventListener("visibilitychange", handler);
123
+ return {
124
+ remove: () => {
125
+ document.removeEventListener("visibilitychange", handler);
126
+ }
127
+ };
128
+ } else if (!add && currentSubscription) {
129
+ currentSubscription.remove();
130
+ return void 0;
131
+ }
132
+ return currentSubscription;
133
+ }
134
+
135
+ // src/core/StateManager.ts
136
+ var LOCAL_ONLY_SYNC_FIELDS = [LOCAL_PK, UPDATED_AT];
137
+ var DYNC_STATE_TABLE = "_dync_state";
138
+ var SYNC_STATE_KEY = "sync_state";
139
+ var DEFAULT_STATE = {
140
+ firstLoadDone: false,
141
+ pendingChanges: [],
142
+ lastPulled: {}
143
+ };
144
+ var StateManager = class {
145
+ persistedState;
146
+ syncStatus;
147
+ apiError;
148
+ listeners = /* @__PURE__ */ new Set();
149
+ storageAdapter;
150
+ hydrated = false;
151
+ constructor(ctx) {
152
+ this.storageAdapter = ctx.storageAdapter;
153
+ this.persistedState = DEFAULT_STATE;
154
+ this.syncStatus = ctx.initialStatus ?? "disabled";
155
+ }
156
+ /**
157
+ * Load state from the database. Called after stores() defines the schema.
158
+ */
159
+ async hydrate() {
160
+ if (this.hydrated) return;
161
+ if (!this.storageAdapter) {
162
+ throw new Error("Cannot hydrate state without a storage adapter");
163
+ }
164
+ const table = this.storageAdapter.table(DYNC_STATE_TABLE);
165
+ const row = await table.get(SYNC_STATE_KEY);
166
+ if (row?.value) {
167
+ this.persistedState = parseStoredState(row.value);
168
+ }
169
+ this.hydrated = true;
170
+ this.emit();
171
+ }
172
+ emit() {
173
+ this.listeners.forEach((fn) => fn(this.getSyncState()));
174
+ }
175
+ async persist() {
176
+ if (!this.hydrated || !this.storageAdapter) return;
177
+ this.emit();
178
+ const table = this.storageAdapter.table(DYNC_STATE_TABLE);
179
+ await table.put({ [LOCAL_PK]: SYNC_STATE_KEY, value: JSON.stringify(this.persistedState) });
180
+ }
181
+ getState() {
182
+ return clonePersistedState(this.persistedState);
183
+ }
184
+ setState(setterOrState) {
185
+ this.persistedState = resolveNextState(this.persistedState, setterOrState);
186
+ return this.persist();
187
+ }
188
+ setApiError(error) {
189
+ this.apiError = error ? parseApiError(error) : void 0;
190
+ this.emit();
191
+ }
192
+ addPendingChange(change) {
193
+ const next = clonePersistedState(this.persistedState);
194
+ const queueItem = next.pendingChanges.find((p) => p.localId === change.localId && p.tableName === change.tableName);
195
+ const omittedChanges = omitFields(change.changes, LOCAL_ONLY_SYNC_FIELDS);
196
+ const omittedBefore = omitFields(change.before, LOCAL_ONLY_SYNC_FIELDS);
197
+ const omittedAfter = omitFields(change.after, LOCAL_ONLY_SYNC_FIELDS);
198
+ const hasChanges = Object.keys(omittedChanges || {}).length > 0;
199
+ const action = change.action;
200
+ if (queueItem) {
201
+ if (queueItem.action === "remove" /* Remove */) {
202
+ return Promise.resolve();
203
+ }
204
+ queueItem.version += 1;
205
+ if (action === "remove" /* Remove */) {
206
+ queueItem.action = "remove" /* Remove */;
207
+ } else if (hasChanges) {
208
+ queueItem.changes = { ...queueItem.changes, ...omittedChanges };
209
+ queueItem.after = { ...queueItem.after, ...omittedAfter };
210
+ }
211
+ } else if (action === "remove" /* Remove */ || hasChanges) {
212
+ next.pendingChanges = [...next.pendingChanges];
213
+ next.pendingChanges.push({
214
+ action,
215
+ tableName: change.tableName,
216
+ localId: change.localId,
217
+ id: change.id,
218
+ version: 1,
219
+ changes: omittedChanges,
220
+ before: omittedBefore,
221
+ after: omittedAfter
222
+ });
223
+ }
224
+ this.persistedState = next;
225
+ return this.persist();
226
+ }
227
+ samePendingVersion(tableName, localId, version) {
228
+ return this.persistedState.pendingChanges.find((p) => p.localId === localId && p.tableName === tableName)?.version === version;
229
+ }
230
+ removePendingChange(localId, tableName) {
231
+ const next = clonePersistedState(this.persistedState);
232
+ next.pendingChanges = next.pendingChanges.filter((p) => !(p.localId === localId && p.tableName === tableName));
233
+ this.persistedState = next;
234
+ return this.persist();
235
+ }
236
+ updatePendingChange(tableName, localId, action, id) {
237
+ const next = clonePersistedState(this.persistedState);
238
+ const changeItem = next.pendingChanges.find((p) => p.tableName === tableName && p.localId === localId);
239
+ if (changeItem) {
240
+ changeItem.action = action;
241
+ if (id) changeItem.id = id;
242
+ this.persistedState = next;
243
+ return this.persist();
244
+ }
245
+ return Promise.resolve();
246
+ }
247
+ setPendingChangeBefore(tableName, localId, before) {
248
+ const next = clonePersistedState(this.persistedState);
249
+ const changeItem = next.pendingChanges.find((p) => p.tableName === tableName && p.localId === localId);
250
+ if (changeItem) {
251
+ changeItem.before = { ...changeItem.before ?? {}, ...before };
252
+ this.persistedState = next;
253
+ return this.persist();
254
+ }
255
+ return Promise.resolve();
256
+ }
257
+ hasConflicts(localId) {
258
+ return Boolean(this.persistedState.conflicts?.[localId]);
259
+ }
260
+ getSyncStatus() {
261
+ return this.syncStatus;
262
+ }
263
+ setSyncStatus(status) {
264
+ if (this.syncStatus === status) return;
265
+ this.syncStatus = status;
266
+ this.emit();
267
+ }
268
+ getSyncState() {
269
+ return buildSyncState(this.persistedState, this.syncStatus, this.hydrated, this.apiError);
270
+ }
271
+ subscribe(listener) {
272
+ this.listeners.add(listener);
273
+ return () => this.listeners.delete(listener);
274
+ }
275
+ };
276
+ function parseStoredState(stored) {
277
+ const parsed = JSON.parse(stored);
278
+ if (parsed.pendingChanges) {
279
+ parsed.pendingChanges = parsed.pendingChanges.map((change) => ({
280
+ ...change,
281
+ timestamp: change.timestamp ? new Date(change.timestamp) : change.timestamp
282
+ }));
283
+ }
284
+ return parsed;
285
+ }
286
+ function resolveNextState(current, setterOrState) {
287
+ if (typeof setterOrState === "function") {
288
+ return { ...current, ...setterOrState(clonePersistedState(current)) };
289
+ }
290
+ return { ...current, ...setterOrState };
291
+ }
292
+ function buildSyncState(state, status, hydrated, apiError) {
293
+ const persisted = clonePersistedState(state);
294
+ const syncState = {
295
+ ...persisted,
296
+ status,
297
+ hydrated,
298
+ apiError
299
+ };
300
+ deleteKeyIfEmptyObject(syncState, "conflicts");
301
+ return syncState;
302
+ }
303
+ function clonePersistedState(state) {
304
+ return {
305
+ ...state,
306
+ pendingChanges: state.pendingChanges.map((change) => ({
307
+ ...change,
308
+ changes: cloneRecord(change.changes),
309
+ before: cloneRecord(change.before),
310
+ after: cloneRecord(change.after)
311
+ })),
312
+ lastPulled: { ...state.lastPulled },
313
+ conflicts: cloneConflicts(state.conflicts)
314
+ };
315
+ }
316
+ function cloneConflicts(conflicts) {
317
+ if (!conflicts) return void 0;
318
+ const next = {};
319
+ for (const [key, value] of Object.entries(conflicts)) {
320
+ next[key] = {
321
+ tableName: value.tableName,
322
+ fields: value.fields.map((field) => ({ ...field }))
323
+ };
324
+ }
325
+ return next;
326
+ }
327
+ function cloneRecord(record) {
328
+ if (!record) return record;
329
+ return { ...record };
330
+ }
331
+
332
+ // src/core/tableEnhancers.ts
333
+ function wrapWithMutationEmitter(table, tableName, emitMutation) {
334
+ const rawAdd = table.raw.add;
335
+ const rawPut = table.raw.put;
336
+ const rawUpdate = table.raw.update;
337
+ const rawDelete = table.raw.delete;
338
+ const rawBulkAdd = table.raw.bulkAdd;
339
+ const rawBulkPut = table.raw.bulkPut;
340
+ const rawBulkUpdate = table.raw.bulkUpdate;
341
+ const rawBulkDelete = table.raw.bulkDelete;
342
+ const rawClear = table.raw.clear;
343
+ table.add = async (item) => {
344
+ const result = await rawAdd(item);
345
+ emitMutation({ type: "add", tableName, keys: [result] });
346
+ return result;
347
+ };
348
+ table.put = async (item) => {
349
+ const result = await rawPut(item);
350
+ emitMutation({ type: "update", tableName, keys: [result] });
351
+ return result;
352
+ };
353
+ table.update = async (key, changes) => {
354
+ const result = await rawUpdate(key, changes);
355
+ if (result > 0) {
356
+ emitMutation({ type: "update", tableName, keys: [key] });
357
+ }
358
+ return result;
359
+ };
360
+ table.delete = async (key) => {
361
+ await rawDelete(key);
362
+ emitMutation({ type: "delete", tableName, keys: [key] });
363
+ };
364
+ table.bulkAdd = async (items) => {
365
+ const result = await rawBulkAdd(items);
366
+ if (items.length > 0) {
367
+ emitMutation({ type: "add", tableName });
368
+ }
369
+ return result;
370
+ };
371
+ table.bulkPut = async (items) => {
372
+ const result = await rawBulkPut(items);
373
+ if (items.length > 0) {
374
+ emitMutation({ type: "update", tableName });
375
+ }
376
+ return result;
377
+ };
378
+ table.bulkUpdate = async (keysAndChanges) => {
379
+ const result = await rawBulkUpdate(keysAndChanges);
380
+ if (result > 0) {
381
+ emitMutation({ type: "update", tableName, keys: keysAndChanges.map((kc) => kc.key) });
382
+ }
383
+ return result;
384
+ };
385
+ table.bulkDelete = async (keys) => {
386
+ await rawBulkDelete(keys);
387
+ if (keys.length > 0) {
388
+ emitMutation({ type: "delete", tableName });
389
+ }
390
+ };
391
+ table.clear = async () => {
392
+ await rawClear();
393
+ emitMutation({ type: "delete", tableName });
394
+ };
395
+ }
396
+ function setupEnhancedTables({ owner, tableCache, enhancedTables, getTable }, tableNames) {
397
+ for (const tableName of tableNames) {
398
+ tableCache.delete(tableName);
399
+ enhancedTables.delete(tableName);
400
+ if (!Object.prototype.hasOwnProperty.call(owner, tableName)) {
401
+ Object.defineProperty(owner, tableName, {
402
+ get: () => getTable(tableName),
403
+ enumerable: true,
404
+ configurable: true
405
+ });
406
+ }
407
+ }
408
+ }
409
+ function enhanceSyncTable({ table, tableName, withTransaction, state, enhancedTables, emitMutation }) {
410
+ const rawAdd = table.raw.add;
411
+ const rawPut = table.raw.put;
412
+ const rawUpdate = table.raw.update;
413
+ const rawDelete = table.raw.delete;
414
+ const rawBulkAdd = table.raw.bulkAdd;
415
+ const rawBulkPut = table.raw.bulkPut;
416
+ const rawBulkUpdate = table.raw.bulkUpdate;
417
+ const rawBulkDelete = table.raw.bulkDelete;
418
+ const rawClear = table.raw.clear;
419
+ const wrappedAdd = async (item) => {
420
+ let localId = item._localId;
421
+ if (!localId) localId = createLocalId();
422
+ const syncedItem = {
423
+ ...item,
424
+ _localId: localId,
425
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
426
+ };
427
+ let result;
428
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async () => {
429
+ result = await rawAdd(syncedItem);
430
+ await state.addPendingChange({
431
+ action: "create" /* Create */,
432
+ tableName,
433
+ localId,
434
+ changes: syncedItem,
435
+ before: null,
436
+ after: syncedItem
437
+ });
438
+ });
439
+ emitMutation({ type: "add", tableName, keys: [localId] });
440
+ return result;
441
+ };
442
+ const wrappedPut = async (item) => {
443
+ let localId = item._localId;
444
+ if (!localId) localId = createLocalId();
445
+ const syncedItem = {
446
+ ...item,
447
+ _localId: localId,
448
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
449
+ };
450
+ let result;
451
+ let isUpdate = false;
452
+ let existingRecord;
453
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
454
+ const txTable = tables[tableName];
455
+ existingRecord = await txTable.get(localId);
456
+ isUpdate = !!existingRecord;
457
+ result = await rawPut(syncedItem);
458
+ await state.addPendingChange({
459
+ action: isUpdate ? "update" /* Update */ : "create" /* Create */,
460
+ tableName,
461
+ localId,
462
+ id: existingRecord?.id,
463
+ changes: syncedItem,
464
+ before: existingRecord ?? null,
465
+ after: syncedItem
466
+ });
467
+ });
468
+ emitMutation({ type: isUpdate ? "update" : "add", tableName, keys: [localId] });
469
+ return result;
470
+ };
471
+ const wrappedUpdate = async (key, changes) => {
472
+ const updatedChanges = {
473
+ ...changes,
474
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
475
+ };
476
+ let result = 0;
477
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
478
+ const txTable = tables[tableName];
479
+ const record = await txTable.get(key);
480
+ if (!record) {
481
+ throw new Error(`Record with key=${key} not found`);
482
+ }
483
+ result = await rawUpdate(key, updatedChanges) ?? 0;
484
+ if (result > 0) {
485
+ await state.addPendingChange({
486
+ action: "update" /* Update */,
487
+ tableName,
488
+ localId: key,
489
+ id: record.id,
490
+ changes: updatedChanges,
491
+ before: record,
492
+ after: { ...record, ...updatedChanges }
493
+ });
494
+ }
495
+ });
496
+ if (result > 0) {
497
+ emitMutation({ type: "update", tableName, keys: [key] });
498
+ }
499
+ return result;
500
+ };
501
+ const wrappedDelete = async (key) => {
502
+ let deletedLocalId;
503
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
504
+ const txTable = tables[tableName];
505
+ const record = await txTable.get(key);
506
+ await rawDelete(key);
507
+ if (record) {
508
+ deletedLocalId = record._localId;
509
+ await state.addPendingChange({
510
+ action: "remove" /* Remove */,
511
+ tableName,
512
+ localId: record._localId,
513
+ id: record.id,
514
+ changes: null,
515
+ before: record
516
+ });
517
+ }
518
+ });
519
+ if (deletedLocalId) {
520
+ emitMutation({ type: "delete", tableName, keys: [deletedLocalId] });
521
+ }
522
+ };
523
+ const wrappedBulkAdd = async (items) => {
524
+ if (items.length === 0) return [];
525
+ const now = (/* @__PURE__ */ new Date()).toISOString();
526
+ const syncedItems = items.map((item) => {
527
+ const localId = item._localId || createLocalId();
528
+ return {
529
+ ...item,
530
+ _localId: localId,
531
+ updated_at: now
532
+ };
533
+ });
534
+ let result;
535
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async () => {
536
+ result = await rawBulkAdd(syncedItems);
537
+ for (const syncedItem of syncedItems) {
538
+ await state.addPendingChange({
539
+ action: "create" /* Create */,
540
+ tableName,
541
+ localId: syncedItem._localId,
542
+ changes: syncedItem,
543
+ before: null,
544
+ after: syncedItem
545
+ });
546
+ }
547
+ });
548
+ emitMutation({ type: "add", tableName, keys: syncedItems.map((i) => i._localId) });
549
+ return result;
550
+ };
551
+ const wrappedBulkPut = async (items) => {
552
+ if (items.length === 0) return [];
553
+ const now = (/* @__PURE__ */ new Date()).toISOString();
554
+ const syncedItems = items.map((item) => {
555
+ const localId = item._localId || createLocalId();
556
+ return {
557
+ ...item,
558
+ _localId: localId,
559
+ updated_at: now
560
+ };
561
+ });
562
+ const localIds = syncedItems.map((i) => i._localId);
563
+ let result;
564
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
565
+ const txTable = tables[tableName];
566
+ const existingRecords = await txTable.bulkGet(localIds);
567
+ const existingMap = /* @__PURE__ */ new Map();
568
+ for (let i = 0; i < localIds.length; i++) {
569
+ if (existingRecords[i]) {
570
+ existingMap.set(localIds[i], existingRecords[i]);
571
+ }
572
+ }
573
+ result = await rawBulkPut(syncedItems);
574
+ for (const syncedItem of syncedItems) {
575
+ const existing = existingMap.get(syncedItem._localId);
576
+ await state.addPendingChange({
577
+ action: existing ? "update" /* Update */ : "create" /* Create */,
578
+ tableName,
579
+ localId: syncedItem._localId,
580
+ id: existing?.id,
581
+ changes: syncedItem,
582
+ before: existing ?? null,
583
+ after: syncedItem
584
+ });
585
+ }
586
+ });
587
+ emitMutation({ type: "update", tableName, keys: localIds });
588
+ return result;
589
+ };
590
+ const wrappedBulkUpdate = async (keysAndChanges) => {
591
+ if (keysAndChanges.length === 0) return 0;
592
+ const now = (/* @__PURE__ */ new Date()).toISOString();
593
+ const updatedKeysAndChanges = keysAndChanges.map(({ key, changes }) => ({
594
+ key,
595
+ changes: {
596
+ ...changes,
597
+ updated_at: now
598
+ }
599
+ }));
600
+ let result = 0;
601
+ const updatedKeys = [];
602
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
603
+ const txTable = tables[tableName];
604
+ const keys = updatedKeysAndChanges.map((kc) => kc.key);
605
+ const records = await txTable.bulkGet(keys);
606
+ const recordMap = /* @__PURE__ */ new Map();
607
+ for (let i = 0; i < keys.length; i++) {
608
+ if (records[i]) {
609
+ recordMap.set(String(keys[i]), records[i]);
610
+ }
611
+ }
612
+ result = await rawBulkUpdate(updatedKeysAndChanges);
613
+ for (const { key, changes } of updatedKeysAndChanges) {
614
+ const record = recordMap.get(String(key));
615
+ if (record) {
616
+ updatedKeys.push(record._localId);
617
+ await state.addPendingChange({
618
+ action: "update" /* Update */,
619
+ tableName,
620
+ localId: record._localId,
621
+ id: record.id,
622
+ changes,
623
+ before: record,
624
+ after: { ...record, ...changes }
625
+ });
626
+ }
627
+ }
628
+ });
629
+ if (updatedKeys.length > 0) {
630
+ emitMutation({ type: "update", tableName, keys: updatedKeys });
631
+ }
632
+ return result;
633
+ };
634
+ const wrappedBulkDelete = async (keys) => {
635
+ if (keys.length === 0) return;
636
+ const deletedLocalIds = [];
637
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
638
+ const txTable = tables[tableName];
639
+ const records = await txTable.bulkGet(keys);
640
+ await rawBulkDelete(keys);
641
+ for (const record of records) {
642
+ if (record) {
643
+ deletedLocalIds.push(record._localId);
644
+ await state.addPendingChange({
645
+ action: "remove" /* Remove */,
646
+ tableName,
647
+ localId: record._localId,
648
+ id: record.id,
649
+ changes: null,
650
+ before: record
651
+ });
652
+ }
653
+ }
654
+ });
655
+ if (deletedLocalIds.length > 0) {
656
+ emitMutation({ type: "delete", tableName, keys: deletedLocalIds });
657
+ }
658
+ };
659
+ const wrappedClear = async () => {
660
+ const deletedLocalIds = [];
661
+ await withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
662
+ const txTable = tables[tableName];
663
+ const allRecords = await txTable.toArray();
664
+ await rawClear();
665
+ for (const record of allRecords) {
666
+ if (record._localId) {
667
+ deletedLocalIds.push(record._localId);
668
+ await state.addPendingChange({
669
+ action: "remove" /* Remove */,
670
+ tableName,
671
+ localId: record._localId,
672
+ id: record.id,
673
+ changes: null,
674
+ before: record
675
+ });
676
+ }
677
+ }
678
+ });
679
+ if (deletedLocalIds.length > 0) {
680
+ emitMutation({ type: "delete", tableName, keys: deletedLocalIds });
681
+ }
682
+ };
683
+ table.add = wrappedAdd;
684
+ table.put = wrappedPut;
685
+ table.update = wrappedUpdate;
686
+ table.delete = wrappedDelete;
687
+ table.bulkAdd = wrappedBulkAdd;
688
+ table.bulkPut = wrappedBulkPut;
689
+ table.bulkUpdate = wrappedBulkUpdate;
690
+ table.bulkDelete = wrappedBulkDelete;
691
+ table.clear = wrappedClear;
692
+ enhancedTables.add(tableName);
693
+ }
694
+
695
+ // src/core/pullOperations.ts
696
+ async function pullAll(ctx) {
697
+ let firstSyncError;
698
+ const changedTables = [];
699
+ for (const [tableName, api] of Object.entries(ctx.syncApis)) {
700
+ try {
701
+ const lastPulled = ctx.state.getState().lastPulled[tableName];
702
+ const since = lastPulled ? new Date(lastPulled) : /* @__PURE__ */ new Date(0);
703
+ ctx.logger.debug(`[dync] pull:start tableName=${tableName} since=${since.toISOString()}`);
704
+ const serverData = await api.list(since);
705
+ const changed = await processPullData(tableName, serverData, since, ctx);
706
+ if (changed) changedTables.push(tableName);
707
+ } catch (err) {
708
+ firstSyncError = firstSyncError ?? err;
709
+ ctx.logger.error(`[dync] pull:error tableName=${tableName}`, err);
710
+ }
711
+ }
712
+ return { error: firstSyncError, changedTables };
713
+ }
714
+ async function handleRemoteItemUpdate(table, tableName, localItem, remote, ctx) {
715
+ const pendingChange = ctx.state.getState().pendingChanges.find((p) => p.tableName === tableName && p.localId === localItem._localId);
716
+ const conflictStrategy = ctx.conflictResolutionStrategy;
717
+ if (pendingChange) {
718
+ ctx.logger.debug(`[dync] pull:conflict-strategy:${conflictStrategy} tableName=${tableName} id=${remote.id}`);
719
+ switch (conflictStrategy) {
720
+ case "local-wins":
721
+ break;
722
+ case "remote-wins": {
723
+ const merged = { ...remote, _localId: localItem._localId };
724
+ await table.raw.update(localItem._localId, merged);
725
+ await ctx.state.removePendingChange(localItem._localId, tableName);
726
+ break;
727
+ }
728
+ case "try-shallow-merge": {
729
+ const changes = pendingChange.changes || {};
730
+ const before = pendingChange.before || {};
731
+ const fields = Object.entries(changes).filter(([k, localValue]) => k in before && k in remote && before[k] !== remote[k] && localValue !== remote[k]).map(([key, localValue]) => ({ key, localValue, remoteValue: remote[key] }));
732
+ if (fields.length > 0) {
733
+ ctx.logger.warn(`[dync] pull:${conflictStrategy}:conflicts-found`, JSON.stringify(fields, null, 4));
734
+ await ctx.state.setState((syncState) => ({
735
+ ...syncState,
736
+ conflicts: {
737
+ ...syncState.conflicts || {},
738
+ [localItem._localId]: { tableName, fields }
739
+ }
740
+ }));
741
+ } else {
742
+ const localChangedKeys = Object.keys(changes);
743
+ const preservedLocal = { _localId: localItem._localId };
744
+ for (const k of localChangedKeys) {
745
+ if (k in localItem) preservedLocal[k] = localItem[k];
746
+ }
747
+ const merged = { ...remote, ...preservedLocal };
748
+ await table.raw.update(localItem._localId, merged);
749
+ await ctx.state.setState((syncState) => {
750
+ const ss = { ...syncState };
751
+ delete ss.conflicts?.[localItem._localId];
752
+ return ss;
753
+ });
754
+ }
755
+ break;
756
+ }
757
+ }
758
+ } else {
759
+ const merged = { ...localItem, ...remote };
760
+ await table.raw.update(localItem._localId, merged);
761
+ ctx.logger.debug(`[dync] pull:merge-remote tableName=${tableName} id=${remote.id}`);
762
+ }
763
+ }
764
+ async function pullAllBatch(ctx) {
765
+ let firstSyncError;
766
+ const changedTables = [];
767
+ try {
768
+ const sinceMap = {};
769
+ for (const tableName of ctx.batchSync.syncTables) {
770
+ const lastPulled = ctx.state.getState().lastPulled[tableName];
771
+ sinceMap[tableName] = lastPulled ? new Date(lastPulled) : /* @__PURE__ */ new Date(0);
772
+ }
773
+ ctx.logger.debug(`[dync] pull:batch:start tables=${[...ctx.batchSync.syncTables].join(",")}`, sinceMap);
774
+ const serverDataByTable = await ctx.batchSync.pull(sinceMap);
775
+ for (const [tableName, serverData] of Object.entries(serverDataByTable)) {
776
+ if (!ctx.batchSync.syncTables.includes(tableName)) {
777
+ ctx.logger.warn(`[dync] pull:batch:unknown-table tableName=${tableName}`);
778
+ continue;
779
+ }
780
+ try {
781
+ const changed = await processPullData(tableName, serverData, sinceMap[tableName], ctx);
782
+ if (changed) changedTables.push(tableName);
783
+ } catch (err) {
784
+ firstSyncError = firstSyncError ?? err;
785
+ ctx.logger.error(`[dync] pull:batch:error tableName=${tableName}`, err);
786
+ }
787
+ }
788
+ } catch (err) {
789
+ firstSyncError = err;
790
+ ctx.logger.error(`[dync] pull:batch:error`, err);
791
+ }
792
+ return { error: firstSyncError, changedTables };
793
+ }
794
+ async function processPullData(tableName, serverData, since, ctx) {
795
+ if (!serverData?.length) return false;
796
+ ctx.logger.debug(`[dync] pull:process tableName=${tableName} count=${serverData.length}`);
797
+ let newest = since;
798
+ let hasChanges = false;
799
+ await ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
800
+ const txTable = tables[tableName];
801
+ const pendingRemovalById = new Set(
802
+ ctx.state.getState().pendingChanges.filter((p) => p.tableName === tableName && p.action === "remove" /* Remove */).map((p) => p.id)
803
+ );
804
+ for (const remote of serverData) {
805
+ const remoteUpdated = new Date(remote.updated_at);
806
+ if (remoteUpdated > newest) newest = remoteUpdated;
807
+ if (pendingRemovalById.has(remote.id)) {
808
+ ctx.logger.debug(`[dync] pull:skip-pending-remove tableName=${tableName} id=${remote.id}`);
809
+ continue;
810
+ }
811
+ const localItem = await txTable.where("id").equals(remote.id).first();
812
+ if (remote.deleted) {
813
+ if (localItem) {
814
+ await txTable.raw.delete(localItem._localId);
815
+ ctx.logger.debug(`[dync] pull:remove tableName=${tableName} id=${remote.id}`);
816
+ hasChanges = true;
817
+ }
818
+ continue;
819
+ }
820
+ delete remote.deleted;
821
+ if (localItem) {
822
+ await handleRemoteItemUpdate(txTable, tableName, localItem, remote, ctx);
823
+ hasChanges = true;
824
+ } else {
825
+ const newLocalItem = { ...remote, _localId: createLocalId() };
826
+ await txTable.raw.add(newLocalItem);
827
+ ctx.logger.debug(`[dync] pull:add tableName=${tableName} id=${remote.id}`);
828
+ hasChanges = true;
829
+ }
830
+ }
831
+ await ctx.state.setState((syncState) => ({
832
+ ...syncState,
833
+ lastPulled: {
834
+ ...syncState.lastPulled,
835
+ [tableName]: newest.toISOString()
836
+ }
837
+ }));
838
+ });
839
+ return hasChanges;
840
+ }
841
+
842
+ // src/core/pushOperations.ts
843
+ async function handleRemoveSuccess(change, ctx) {
844
+ const { tableName, localId, id } = change;
845
+ ctx.logger.debug(`[dync] push:remove:success tableName=${tableName} localId=${localId} id=${id}`);
846
+ await ctx.state.removePendingChange(localId, tableName);
847
+ }
848
+ async function handleUpdateSuccess(change, ctx) {
849
+ const { tableName, localId, version, changes } = change;
850
+ ctx.logger.debug(`[dync] push:update:success tableName=${tableName} localId=${localId} id=${change.id}`);
851
+ if (ctx.state.samePendingVersion(tableName, localId, version)) {
852
+ await ctx.state.removePendingChange(localId, tableName);
853
+ } else {
854
+ await ctx.state.setPendingChangeBefore(tableName, localId, changes);
855
+ }
856
+ }
857
+ async function handleCreateSuccess(change, serverResult, ctx) {
858
+ const { tableName, localId, version, changes, id } = change;
859
+ ctx.logger.debug(`[dync] push:create:success tableName=${tableName} localId=${localId} id=${id ?? serverResult.id}`);
860
+ await ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
861
+ const txTable = tables[tableName];
862
+ const wasChanged = await txTable.raw.update(localId, serverResult) ?? 0;
863
+ if (wasChanged && ctx.state.samePendingVersion(tableName, localId, version)) {
864
+ await ctx.state.removePendingChange(localId, tableName);
865
+ } else {
866
+ const nextAction = wasChanged ? "update" /* Update */ : "remove" /* Remove */;
867
+ await ctx.state.updatePendingChange(tableName, localId, nextAction, serverResult.id);
868
+ if (nextAction === "remove" /* Remove */) return;
869
+ }
870
+ });
871
+ const finalItem = { ...changes, ...serverResult, _localId: localId };
872
+ ctx.syncOptions.onAfterRemoteAdd?.(tableName, finalItem);
873
+ }
874
+ async function pushAll(ctx) {
875
+ let firstSyncError;
876
+ const changesSnapshot = [...ctx.state.getState().pendingChanges].sort((a, b) => orderFor(a.action) - orderFor(b.action));
877
+ for (const change of changesSnapshot) {
878
+ try {
879
+ await pushOne(change, ctx);
880
+ } catch (err) {
881
+ firstSyncError = firstSyncError ?? err;
882
+ ctx.logger.error(`[dync] push:error change=${JSON.stringify(change)}`, err);
883
+ }
884
+ }
885
+ return firstSyncError;
886
+ }
887
+ async function pushOne(change, ctx) {
888
+ const api = ctx.syncApis[change.tableName];
889
+ if (!api) return;
890
+ ctx.logger.debug(`[dync] push:attempt action=${change.action} tableName=${change.tableName} localId=${change.localId}`);
891
+ const { action, tableName, localId, id, changes, after } = change;
892
+ switch (action) {
893
+ case "remove" /* Remove */:
894
+ if (!id) {
895
+ ctx.logger.warn(`[dync] push:remove:no-id tableName=${tableName} localId=${localId}`);
896
+ await ctx.state.removePendingChange(localId, tableName);
897
+ return;
898
+ }
899
+ await api.remove(id);
900
+ await handleRemoveSuccess(change, ctx);
901
+ break;
902
+ case "update" /* Update */: {
903
+ if (ctx.state.hasConflicts(localId)) {
904
+ ctx.logger.warn(`[dync] push:update:skipping-with-conflicts tableName=${tableName} localId=${localId} id=${id}`);
905
+ return;
906
+ }
907
+ const exists = await api.update(id, changes, after);
908
+ if (exists) {
909
+ await handleUpdateSuccess(change, ctx);
910
+ } else {
911
+ await handleMissingRemoteRecord(change, ctx);
912
+ }
913
+ break;
914
+ }
915
+ case "create" /* Create */: {
916
+ const result = await api.add(changes);
917
+ if (result) {
918
+ await handleCreateSuccess(change, result, ctx);
919
+ } else {
920
+ ctx.logger.warn(`[dync] push:create:no-result tableName=${tableName} localId=${localId} id=${id}`);
921
+ if (ctx.state.samePendingVersion(tableName, localId, change.version)) {
922
+ await ctx.state.removePendingChange(localId, tableName);
923
+ }
924
+ }
925
+ break;
926
+ }
927
+ }
928
+ }
929
+ async function handleMissingRemoteRecord(change, ctx) {
930
+ const { tableName, localId } = change;
931
+ const strategy = ctx.syncOptions.missingRemoteRecordDuringUpdateStrategy;
932
+ let localItem;
933
+ await ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
934
+ const txTable = tables[tableName];
935
+ localItem = await txTable.get(localId);
936
+ if (!localItem) {
937
+ ctx.logger.warn(`[dync] push:missing-remote:no-local-item tableName=${tableName} localId=${localId}`);
938
+ await ctx.state.removePendingChange(localId, tableName);
939
+ return;
940
+ }
941
+ switch (strategy) {
942
+ case "delete-local-record":
943
+ await txTable.raw.delete(localId);
944
+ ctx.logger.debug(`[dync] push:missing-remote:${strategy} tableName=${tableName} id=${localItem.id}`);
945
+ break;
946
+ case "insert-remote-record": {
947
+ const newItem = {
948
+ ...localItem,
949
+ _localId: createLocalId(),
950
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
951
+ };
952
+ await txTable.raw.add(newItem);
953
+ await txTable.raw.delete(localId);
954
+ await ctx.state.addPendingChange({
955
+ action: "create" /* Create */,
956
+ tableName,
957
+ localId: newItem._localId,
958
+ changes: newItem,
959
+ before: null
960
+ });
961
+ ctx.logger.debug(`[dync] push:missing-remote:${strategy} tableName=${tableName} id=${newItem.id}`);
962
+ break;
963
+ }
964
+ case "ignore":
965
+ ctx.logger.debug(`[dync] push:missing-remote:${strategy} tableName=${tableName} id=${localItem.id}`);
966
+ break;
967
+ default:
968
+ ctx.logger.error(`[dync] push:missing-remote:unknown-strategy tableName=${tableName} id=${localItem.id} strategy=${strategy}`);
969
+ break;
970
+ }
971
+ await ctx.state.removePendingChange(localId, tableName);
972
+ });
973
+ ctx.syncOptions.onAfterMissingRemoteRecordDuringUpdate?.(strategy, localItem);
974
+ }
975
+ async function pushAllBatch(ctx) {
976
+ let firstSyncError;
977
+ try {
978
+ const changesSnapshot = [...ctx.state.getState().pendingChanges].filter((change) => ctx.batchSync.syncTables.includes(change.tableName)).sort((a, b) => orderFor(a.action) - orderFor(b.action));
979
+ if (changesSnapshot.length === 0) {
980
+ ctx.logger.debug("[dync] push:batch:no-changes");
981
+ return void 0;
982
+ }
983
+ const changesToPush = changesSnapshot.filter((change) => {
984
+ if (change.action === "update" /* Update */ && ctx.state.hasConflicts(change.localId)) {
985
+ ctx.logger.warn(`[dync] push:batch:skipping-with-conflicts tableName=${change.tableName} localId=${change.localId}`);
986
+ return false;
987
+ }
988
+ return true;
989
+ });
990
+ if (changesToPush.length === 0) {
991
+ ctx.logger.debug("[dync] push:batch:all-skipped");
992
+ return void 0;
993
+ }
994
+ const payloads = changesToPush.map((change) => ({
995
+ table: change.tableName,
996
+ action: change.action === "create" /* Create */ ? "add" : change.action === "update" /* Update */ ? "update" : "remove",
997
+ localId: change.localId,
998
+ id: change.id,
999
+ data: change.action === "remove" /* Remove */ ? void 0 : change.changes
1000
+ }));
1001
+ ctx.logger.debug(`[dync] push:batch:start count=${payloads.length}`);
1002
+ const results = await ctx.batchSync.push(payloads);
1003
+ const resultMap = /* @__PURE__ */ new Map();
1004
+ for (const result of results) {
1005
+ resultMap.set(result.localId, result);
1006
+ }
1007
+ for (const change of changesToPush) {
1008
+ const result = resultMap.get(change.localId);
1009
+ if (!result) {
1010
+ ctx.logger.warn(`[dync] push:batch:missing-result localId=${change.localId}`);
1011
+ continue;
1012
+ }
1013
+ try {
1014
+ await processBatchPushResult(change, result, ctx);
1015
+ } catch (err) {
1016
+ firstSyncError = firstSyncError ?? err;
1017
+ ctx.logger.error(`[dync] push:batch:error localId=${change.localId}`, err);
1018
+ }
1019
+ }
1020
+ } catch (err) {
1021
+ firstSyncError = err;
1022
+ ctx.logger.error("[dync] push:batch:error", err);
1023
+ }
1024
+ return firstSyncError;
1025
+ }
1026
+ async function processBatchPushResult(change, result, ctx) {
1027
+ const { action, tableName, localId } = change;
1028
+ if (!result.success) {
1029
+ if (action === "update" /* Update */) {
1030
+ await handleMissingRemoteRecord(change, ctx);
1031
+ } else {
1032
+ ctx.logger.warn(`[dync] push:batch:failed tableName=${tableName} localId=${localId} error=${result.error}`);
1033
+ }
1034
+ return;
1035
+ }
1036
+ switch (action) {
1037
+ case "remove" /* Remove */:
1038
+ handleRemoveSuccess(change, ctx);
1039
+ break;
1040
+ case "update" /* Update */:
1041
+ handleUpdateSuccess(change, ctx);
1042
+ break;
1043
+ case "create" /* Create */: {
1044
+ const serverResult = { id: result.id };
1045
+ if (result.updated_at) {
1046
+ serverResult.updated_at = result.updated_at;
1047
+ }
1048
+ await handleCreateSuccess(change, serverResult, ctx);
1049
+ break;
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ // src/core/firstLoad.ts
1055
+ var yieldToEventLoop = () => sleep(0);
1056
+ var WRITE_BATCH_SIZE = 200;
1057
+ async function startFirstLoad(ctx) {
1058
+ ctx.logger.debug("[dync] Starting first load...");
1059
+ if (ctx.state.getState().firstLoadDone) {
1060
+ ctx.logger.debug("[dync] First load already completed");
1061
+ return;
1062
+ }
1063
+ let error;
1064
+ for (const [tableName, api] of Object.entries(ctx.syncApis)) {
1065
+ if (!api.firstLoad) {
1066
+ ctx.logger.error(`[dync] firstLoad:no-api-function tableName=${tableName}`);
1067
+ continue;
1068
+ }
1069
+ try {
1070
+ ctx.logger.info(`[dync] firstLoad:start tableName=${tableName}`);
1071
+ let lastId;
1072
+ let isEmptyTable = true;
1073
+ let batchCount = 0;
1074
+ let totalInserted = 0;
1075
+ let totalUpdated = 0;
1076
+ while (true) {
1077
+ const batch = await api.firstLoad(lastId);
1078
+ if (!batch?.length) break;
1079
+ batchCount++;
1080
+ const { inserted, updated } = await processBatchInChunks(ctx, tableName, batch, isEmptyTable, lastId === void 0);
1081
+ totalInserted += inserted;
1082
+ totalUpdated += updated;
1083
+ if (ctx.onProgress) {
1084
+ ctx.onProgress({
1085
+ table: tableName,
1086
+ inserted: totalInserted,
1087
+ updated: totalUpdated,
1088
+ total: totalInserted + totalUpdated
1089
+ });
1090
+ }
1091
+ if (lastId === void 0) {
1092
+ isEmptyTable = await ctx.table(tableName).count() === batch.length;
1093
+ }
1094
+ if (lastId !== void 0 && lastId === batch[batch.length - 1].id) {
1095
+ throw new Error(`Duplicate records downloaded, stopping to prevent infinite loop`);
1096
+ }
1097
+ lastId = batch[batch.length - 1].id;
1098
+ if (batchCount % 5 === 0) {
1099
+ await yieldToEventLoop();
1100
+ }
1101
+ }
1102
+ ctx.logger.info(`[dync] firstLoad:done tableName=${tableName} inserted=${totalInserted} updated=${totalUpdated}`);
1103
+ } catch (err) {
1104
+ error = error ?? err;
1105
+ ctx.logger.error(`[dync] firstLoad:error tableName=${tableName}`, err);
1106
+ }
1107
+ }
1108
+ await ctx.state.setState((syncState) => ({
1109
+ ...syncState,
1110
+ firstLoadDone: true,
1111
+ error
1112
+ }));
1113
+ ctx.logger.debug("[dync] First load completed");
1114
+ }
1115
+ async function processBatchInChunks(ctx, tableName, batch, isEmptyTable, isFirstBatch) {
1116
+ let newest = new Date(ctx.state.getState().lastPulled[tableName] || 0);
1117
+ return ctx.withTransaction("rw", [tableName, DYNC_STATE_TABLE], async (tables) => {
1118
+ const txTable = tables[tableName];
1119
+ let tableIsEmpty = isEmptyTable;
1120
+ if (isFirstBatch) {
1121
+ const count = await txTable.count();
1122
+ tableIsEmpty = count === 0;
1123
+ }
1124
+ const activeRecords = [];
1125
+ for (const remote of batch) {
1126
+ const remoteUpdated = new Date(remote.updated_at || 0);
1127
+ if (remoteUpdated > newest) newest = remoteUpdated;
1128
+ if (remote.deleted) continue;
1129
+ delete remote.deleted;
1130
+ remote._localId = createLocalId();
1131
+ activeRecords.push(remote);
1132
+ }
1133
+ let inserted = 0;
1134
+ let updated = 0;
1135
+ if (tableIsEmpty) {
1136
+ for (let i = 0; i < activeRecords.length; i += WRITE_BATCH_SIZE) {
1137
+ const chunk = activeRecords.slice(i, i + WRITE_BATCH_SIZE);
1138
+ await txTable.raw.bulkAdd(chunk);
1139
+ inserted += chunk.length;
1140
+ }
1141
+ } else {
1142
+ for (let i = 0; i < activeRecords.length; i += WRITE_BATCH_SIZE) {
1143
+ const chunk = activeRecords.slice(i, i + WRITE_BATCH_SIZE);
1144
+ const chunkResult = await processChunkWithLookup(txTable, chunk);
1145
+ inserted += chunkResult.inserted;
1146
+ updated += chunkResult.updated;
1147
+ }
1148
+ }
1149
+ await ctx.state.setState((syncState) => ({
1150
+ ...syncState,
1151
+ lastPulled: {
1152
+ ...syncState.lastPulled,
1153
+ [tableName]: newest.toISOString()
1154
+ }
1155
+ }));
1156
+ return { inserted, updated };
1157
+ });
1158
+ }
1159
+ async function processChunkWithLookup(txTable, chunk) {
1160
+ const serverIds = chunk.filter((r) => r.id != null).map((r) => r.id);
1161
+ const existingByServerId = /* @__PURE__ */ new Map();
1162
+ if (serverIds.length > 0) {
1163
+ const existingRecords = await txTable.where("id").anyOf(serverIds).toArray();
1164
+ for (const existing of existingRecords) {
1165
+ existingByServerId.set(existing.id, existing);
1166
+ }
1167
+ }
1168
+ const toAdd = [];
1169
+ let updated = 0;
1170
+ for (const remote of chunk) {
1171
+ const existing = remote.id != null ? existingByServerId.get(remote.id) : void 0;
1172
+ if (existing) {
1173
+ const merged = Object.assign({}, existing, remote, { _localId: existing._localId });
1174
+ await txTable.raw.update(existing._localId, merged);
1175
+ updated++;
1176
+ } else {
1177
+ toAdd.push(remote);
1178
+ }
1179
+ }
1180
+ if (toAdd.length > 0) {
1181
+ await txTable.raw.bulkAdd(toAdd);
1182
+ }
1183
+ existingByServerId.clear();
1184
+ return { inserted: toAdd.length, updated };
1185
+ }
1186
+ async function startFirstLoadBatch(ctx) {
1187
+ ctx.logger.debug("[dync] Starting batch first load...");
1188
+ if (ctx.state.getState().firstLoadDone) {
1189
+ ctx.logger.debug("[dync] First load already completed");
1190
+ return;
1191
+ }
1192
+ if (!ctx.batchSync.firstLoad) {
1193
+ ctx.logger.warn("[dync] firstLoad:batch:no-firstLoad-function");
1194
+ await ctx.state.setState((syncState) => ({
1195
+ ...syncState,
1196
+ firstLoadDone: true
1197
+ }));
1198
+ return;
1199
+ }
1200
+ let error;
1201
+ try {
1202
+ ctx.logger.info(`[dync] firstLoad:batch:start tables=${[...ctx.batchSync.syncTables].join(",")}`);
1203
+ const progress = {};
1204
+ for (const tableName of ctx.batchSync.syncTables) {
1205
+ progress[tableName] = { inserted: 0, updated: 0 };
1206
+ }
1207
+ let cursors = {};
1208
+ for (const tableName of ctx.batchSync.syncTables) {
1209
+ cursors[tableName] = void 0;
1210
+ }
1211
+ let batchCount = 0;
1212
+ while (true) {
1213
+ const result = await ctx.batchSync.firstLoad(cursors);
1214
+ if (!result.hasMore && Object.values(result.data).every((d) => !d?.length)) {
1215
+ break;
1216
+ }
1217
+ batchCount++;
1218
+ for (const [tableName, batch] of Object.entries(result.data)) {
1219
+ if (!ctx.batchSync.syncTables.includes(tableName)) {
1220
+ ctx.logger.warn(`[dync] firstLoad:batch:unknown-table tableName=${tableName}`);
1221
+ continue;
1222
+ }
1223
+ if (!batch?.length) continue;
1224
+ const isFirstBatch = progress[tableName].inserted === 0 && progress[tableName].updated === 0;
1225
+ const isEmptyTable = isFirstBatch && await ctx.table(tableName).count() === 0;
1226
+ const { inserted, updated } = await processBatchInChunks(ctx, tableName, batch, isEmptyTable, isFirstBatch);
1227
+ progress[tableName].inserted += inserted;
1228
+ progress[tableName].updated += updated;
1229
+ if (ctx.onProgress) {
1230
+ ctx.onProgress({
1231
+ table: tableName,
1232
+ inserted: progress[tableName].inserted,
1233
+ updated: progress[tableName].updated,
1234
+ total: progress[tableName].inserted + progress[tableName].updated
1235
+ });
1236
+ }
1237
+ }
1238
+ cursors = result.cursors;
1239
+ if (batchCount % 5 === 0) {
1240
+ await yieldToEventLoop();
1241
+ }
1242
+ if (!result.hasMore) {
1243
+ break;
1244
+ }
1245
+ }
1246
+ for (const [tableName, p] of Object.entries(progress)) {
1247
+ ctx.logger.info(`[dync] firstLoad:batch:done tableName=${tableName} inserted=${p.inserted} updated=${p.updated}`);
1248
+ }
1249
+ } catch (err) {
1250
+ error = err;
1251
+ ctx.logger.error("[dync] firstLoad:batch:error", err);
1252
+ }
1253
+ await ctx.state.setState((syncState) => ({
1254
+ ...syncState,
1255
+ firstLoadDone: true,
1256
+ error
1257
+ }));
1258
+ ctx.logger.debug("[dync] Batch first load completed");
1259
+ }
1260
+
1261
+ // src/index.shared.ts
1262
+ var DEFAULT_SYNC_INTERVAL_MILLIS = 2e3;
1263
+ var DEFAULT_LOGGER = console;
1264
+ var DEFAULT_MIN_LOG_LEVEL = "debug";
1265
+ var DEFAULT_MISSING_REMOTE_RECORD_STRATEGY = "insert-remote-record";
1266
+ var DEFAULT_CONFLICT_RESOLUTION_STRATEGY = "try-shallow-merge";
1267
+ var DyncBase = class {
1268
+ adapter;
1269
+ tableCache = /* @__PURE__ */ new Map();
1270
+ mutationWrappedTables = /* @__PURE__ */ new Set();
1271
+ syncEnhancedTables = /* @__PURE__ */ new Set();
1272
+ mutationListeners = /* @__PURE__ */ new Set();
1273
+ visibilitySubscription;
1274
+ openPromise;
1275
+ disableSyncPromise;
1276
+ disableSyncPromiseResolver;
1277
+ sleepAbortController;
1278
+ closing = false;
1279
+ // Per-table sync mode
1280
+ syncApis = {};
1281
+ // Batch sync mode
1282
+ batchSync;
1283
+ syncedTables = /* @__PURE__ */ new Set();
1284
+ syncOptions;
1285
+ logger;
1286
+ syncTimerStarted = false;
1287
+ mutationsDuringSync = false;
1288
+ state;
1289
+ name;
1290
+ constructor(databaseName, syncApisOrBatchSync, storageAdapter, options) {
1291
+ const isBatchMode = typeof syncApisOrBatchSync.push === "function";
1292
+ if (isBatchMode) {
1293
+ this.batchSync = syncApisOrBatchSync;
1294
+ this.syncedTables = new Set(this.batchSync.syncTables);
1295
+ } else {
1296
+ this.syncApis = syncApisOrBatchSync;
1297
+ this.syncedTables = new Set(Object.keys(this.syncApis));
1298
+ }
1299
+ this.adapter = storageAdapter;
1300
+ this.name = databaseName;
1301
+ this.syncOptions = {
1302
+ syncInterval: DEFAULT_SYNC_INTERVAL_MILLIS,
1303
+ logger: DEFAULT_LOGGER,
1304
+ minLogLevel: DEFAULT_MIN_LOG_LEVEL,
1305
+ missingRemoteRecordDuringUpdateStrategy: DEFAULT_MISSING_REMOTE_RECORD_STRATEGY,
1306
+ conflictResolutionStrategy: DEFAULT_CONFLICT_RESOLUTION_STRATEGY,
1307
+ ...options ?? {}
1308
+ };
1309
+ this.logger = newLogger(this.syncOptions.logger, this.syncOptions.minLogLevel);
1310
+ this.state = new StateManager({
1311
+ storageAdapter: this.adapter
1312
+ });
1313
+ Object.defineProperty(this.sync, "state", {
1314
+ get: () => this.getSyncState(),
1315
+ enumerable: true
1316
+ });
1317
+ const driverInfo = "driverType" in this.adapter ? ` (Driver: ${this.adapter.driverType})` : "";
1318
+ this.logger.debug(`[dync] Initialized with ${this.adapter.type}${driverInfo}`);
1319
+ }
1320
+ version(versionNumber) {
1321
+ const self = this;
1322
+ const schemaOptions = {};
1323
+ let storesDefined = false;
1324
+ const builder = {
1325
+ stores(schema) {
1326
+ const usesStructuredSchema = Object.values(schema).some((def) => typeof def !== "string");
1327
+ const stateTableSchema = usesStructuredSchema ? {
1328
+ columns: {
1329
+ [LOCAL_PK]: { type: "TEXT" },
1330
+ value: { type: "TEXT" }
1331
+ }
1332
+ } : LOCAL_PK;
1333
+ const fullSchema = {
1334
+ ...schema,
1335
+ [DYNC_STATE_TABLE]: stateTableSchema
1336
+ };
1337
+ for (const [tableName, tableSchema] of Object.entries(schema)) {
1338
+ const isSyncTable = self.syncedTables.has(tableName);
1339
+ if (typeof tableSchema === "string") {
1340
+ if (isSyncTable) {
1341
+ fullSchema[tableName] = `${LOCAL_PK}, &${SERVER_PK}, ${tableSchema}, ${UPDATED_AT}`;
1342
+ }
1343
+ self.logger.debug(
1344
+ `[dync] Defining ${isSyncTable ? "" : "non-"}sync table '${tableName}' with primary key & indexes '${fullSchema[tableName]}'`
1345
+ );
1346
+ } else {
1347
+ if (isSyncTable) {
1348
+ fullSchema[tableName] = self.injectSyncColumns(tableSchema);
1349
+ }
1350
+ const schemaColumns = Object.keys(fullSchema[tableName].columns ?? {}).join(", ");
1351
+ const schemaIndexes = (fullSchema[tableName].indexes ?? []).map((idx) => idx.columns.join("+")).join(", ");
1352
+ self.logger.debug(
1353
+ `[dync] Defining ${isSyncTable ? "" : "non-"}sync table '${tableName}' with columns ${schemaColumns} and indexes ${schemaIndexes}`
1354
+ );
1355
+ }
1356
+ }
1357
+ storesDefined = true;
1358
+ self.adapter.defineSchema(versionNumber, fullSchema, schemaOptions);
1359
+ self.setupEnhancedTables(Object.keys(schema));
1360
+ return builder;
1361
+ },
1362
+ sqlite(configure) {
1363
+ if (!storesDefined) {
1364
+ throw new Error("Call stores() before registering sqlite migrations");
1365
+ }
1366
+ const sqliteOptions = schemaOptions.sqlite ??= {};
1367
+ const migrations = sqliteOptions.migrations ??= {};
1368
+ const configurator = {
1369
+ upgrade(handler) {
1370
+ migrations.upgrade = handler;
1371
+ },
1372
+ downgrade(handler) {
1373
+ migrations.downgrade = handler;
1374
+ }
1375
+ };
1376
+ configure(configurator);
1377
+ return builder;
1378
+ }
1379
+ };
1380
+ return builder;
1381
+ }
1382
+ async open() {
1383
+ if (this.closing) {
1384
+ return;
1385
+ }
1386
+ if (this.openPromise) {
1387
+ return this.openPromise;
1388
+ }
1389
+ this.openPromise = (async () => {
1390
+ if (this.closing) return;
1391
+ await this.adapter.open();
1392
+ if (this.closing) return;
1393
+ await this.state.hydrate();
1394
+ })();
1395
+ return this.openPromise;
1396
+ }
1397
+ async close() {
1398
+ this.closing = true;
1399
+ if (this.openPromise) {
1400
+ await this.openPromise.catch(() => {
1401
+ });
1402
+ this.openPromise = void 0;
1403
+ }
1404
+ await this.enableSync(false);
1405
+ await this.adapter.close();
1406
+ this.tableCache.clear();
1407
+ this.mutationWrappedTables.clear();
1408
+ this.syncEnhancedTables.clear();
1409
+ }
1410
+ async delete() {
1411
+ await this.adapter.delete();
1412
+ this.tableCache.clear();
1413
+ this.mutationWrappedTables.clear();
1414
+ this.syncEnhancedTables.clear();
1415
+ }
1416
+ async query(callback) {
1417
+ return this.adapter.query(callback);
1418
+ }
1419
+ table(name) {
1420
+ if (this.tableCache.has(name)) {
1421
+ return this.tableCache.get(name);
1422
+ }
1423
+ const table = this.adapter.table(name);
1424
+ const isSyncTable = this.syncedTables.has(name);
1425
+ if (isSyncTable && !this.syncEnhancedTables.has(name)) {
1426
+ this.enhanceSyncTable(table, name);
1427
+ } else if (!isSyncTable && !this.mutationWrappedTables.has(name) && name !== DYNC_STATE_TABLE) {
1428
+ wrapWithMutationEmitter(table, name, this.emitMutation.bind(this));
1429
+ this.mutationWrappedTables.add(name);
1430
+ }
1431
+ this.tableCache.set(name, table);
1432
+ return table;
1433
+ }
1434
+ async withTransaction(mode, tableNames, fn) {
1435
+ await this.open();
1436
+ return this.adapter.transaction(mode, tableNames, async () => {
1437
+ const tables = {};
1438
+ for (const tableName of tableNames) {
1439
+ tables[tableName] = this.table(tableName);
1440
+ }
1441
+ return fn(tables);
1442
+ });
1443
+ }
1444
+ setupEnhancedTables(tableNames) {
1445
+ setupEnhancedTables(
1446
+ {
1447
+ owner: this,
1448
+ tableCache: this.tableCache,
1449
+ enhancedTables: this.syncEnhancedTables,
1450
+ getTable: (name) => this.table(name)
1451
+ },
1452
+ tableNames
1453
+ );
1454
+ for (const tableName of tableNames) {
1455
+ this.mutationWrappedTables.delete(tableName);
1456
+ }
1457
+ }
1458
+ injectSyncColumns(schema) {
1459
+ const columns = schema.columns ?? {};
1460
+ if (columns[LOCAL_PK]) {
1461
+ throw new Error(`Column '${LOCAL_PK}' is auto-injected for sync tables and cannot be defined manually.`);
1462
+ }
1463
+ if (columns[SERVER_PK]) {
1464
+ throw new Error(`Column '${SERVER_PK}' is auto-injected for sync tables and cannot be defined manually.`);
1465
+ }
1466
+ if (columns[UPDATED_AT]) {
1467
+ throw new Error(`Column '${UPDATED_AT}' is auto-injected for sync tables and cannot be defined manually.`);
1468
+ }
1469
+ const injectedColumns = {
1470
+ ...columns,
1471
+ [LOCAL_PK]: { type: "TEXT" },
1472
+ [SERVER_PK]: { type: "INTEGER", unique: true },
1473
+ [UPDATED_AT]: { type: "TEXT" }
1474
+ };
1475
+ const userIndexes = schema.indexes ?? [];
1476
+ const hasUpdatedAtIndex = userIndexes.some((idx) => idx.columns.length === 1 && idx.columns[0] === UPDATED_AT);
1477
+ const injectedIndexes = hasUpdatedAtIndex ? userIndexes : [...userIndexes, { columns: [UPDATED_AT] }];
1478
+ return {
1479
+ ...schema,
1480
+ columns: injectedColumns,
1481
+ indexes: injectedIndexes
1482
+ };
1483
+ }
1484
+ enhanceSyncTable(table, tableName) {
1485
+ enhanceSyncTable({
1486
+ table,
1487
+ tableName,
1488
+ withTransaction: this.withTransaction.bind(this),
1489
+ state: this.state,
1490
+ enhancedTables: this.syncEnhancedTables,
1491
+ emitMutation: this.emitMutation.bind(this)
1492
+ });
1493
+ }
1494
+ async syncOnce() {
1495
+ if (this.closing) {
1496
+ return;
1497
+ }
1498
+ if (this.syncStatus === "syncing") {
1499
+ this.mutationsDuringSync = true;
1500
+ return;
1501
+ }
1502
+ this.syncStatus = "syncing";
1503
+ this.mutationsDuringSync = false;
1504
+ const pullResult = await this.pullAll();
1505
+ const firstPushSyncError = await this.pushAll();
1506
+ for (const tableName of pullResult.changedTables) {
1507
+ this.emitMutation({ type: "pull", tableName });
1508
+ }
1509
+ this.syncStatus = "idle";
1510
+ this.state.setApiError(pullResult.error ?? firstPushSyncError);
1511
+ if (this.mutationsDuringSync) {
1512
+ this.mutationsDuringSync = false;
1513
+ this.syncOnce().catch(() => {
1514
+ });
1515
+ }
1516
+ }
1517
+ async pullAll() {
1518
+ const baseContext = {
1519
+ logger: this.logger,
1520
+ state: this.state,
1521
+ table: this.table.bind(this),
1522
+ withTransaction: this.withTransaction.bind(this),
1523
+ conflictResolutionStrategy: this.syncOptions.conflictResolutionStrategy
1524
+ };
1525
+ if (this.batchSync) {
1526
+ return pullAllBatch({
1527
+ ...baseContext,
1528
+ batchSync: this.batchSync
1529
+ });
1530
+ }
1531
+ return pullAll({
1532
+ ...baseContext,
1533
+ syncApis: this.syncApis
1534
+ });
1535
+ }
1536
+ async pushAll() {
1537
+ const baseContext = {
1538
+ logger: this.logger,
1539
+ state: this.state,
1540
+ table: this.table.bind(this),
1541
+ withTransaction: this.withTransaction.bind(this),
1542
+ syncOptions: this.syncOptions
1543
+ };
1544
+ if (this.batchSync) {
1545
+ return pushAllBatch({
1546
+ ...baseContext,
1547
+ batchSync: this.batchSync
1548
+ });
1549
+ }
1550
+ return pushAll({
1551
+ ...baseContext,
1552
+ syncApis: this.syncApis
1553
+ });
1554
+ }
1555
+ startSyncTimer(start) {
1556
+ if (start) {
1557
+ void this.tryStart();
1558
+ } else {
1559
+ this.syncTimerStarted = false;
1560
+ }
1561
+ }
1562
+ async tryStart() {
1563
+ if (this.syncTimerStarted) return;
1564
+ this.syncTimerStarted = true;
1565
+ while (this.syncTimerStarted) {
1566
+ this.sleepAbortController = new AbortController();
1567
+ await this.syncOnce();
1568
+ await sleep(this.syncOptions.syncInterval, this.sleepAbortController.signal);
1569
+ }
1570
+ this.syncStatus = "disabled";
1571
+ this.disableSyncPromiseResolver?.();
1572
+ }
1573
+ setupVisibilityListener(add) {
1574
+ this.visibilitySubscription = addVisibilityChangeListener(add, this.visibilitySubscription, (isVisible) => this.handleVisibilityChange(isVisible));
1575
+ }
1576
+ handleVisibilityChange(isVisible) {
1577
+ if (isVisible) {
1578
+ this.logger.debug("[dync] sync:start-in-foreground");
1579
+ this.startSyncTimer(true);
1580
+ } else {
1581
+ this.logger.debug("[dync] sync:pause-in-background");
1582
+ this.startSyncTimer(false);
1583
+ }
1584
+ }
1585
+ async startFirstLoad(onProgress) {
1586
+ await this.open();
1587
+ const baseContext = {
1588
+ logger: this.logger,
1589
+ state: this.state,
1590
+ table: this.table.bind(this),
1591
+ withTransaction: this.withTransaction.bind(this),
1592
+ onProgress
1593
+ };
1594
+ if (this.batchSync) {
1595
+ await startFirstLoadBatch({
1596
+ ...baseContext,
1597
+ batchSync: this.batchSync
1598
+ });
1599
+ } else {
1600
+ await startFirstLoad({
1601
+ ...baseContext,
1602
+ syncApis: this.syncApis
1603
+ });
1604
+ }
1605
+ for (const tableName of this.syncedTables) {
1606
+ this.emitMutation({ type: "pull", tableName });
1607
+ }
1608
+ }
1609
+ getSyncState() {
1610
+ return this.state.getSyncState();
1611
+ }
1612
+ async resolveConflict(localId, keepLocal) {
1613
+ const conflict = this.state.getState().conflicts?.[localId];
1614
+ if (!conflict) {
1615
+ this.logger.warn(`[dync] No conflict found for localId: ${localId}`);
1616
+ return;
1617
+ }
1618
+ await this.withTransaction("rw", [conflict.tableName, DYNC_STATE_TABLE], async (tables) => {
1619
+ const txTable = tables[conflict.tableName];
1620
+ if (!keepLocal) {
1621
+ const item = await txTable.get(localId);
1622
+ if (item) {
1623
+ for (const field of conflict.fields) {
1624
+ item[field.key] = field.remoteValue;
1625
+ }
1626
+ await txTable.raw.update(localId, item);
1627
+ } else {
1628
+ this.logger.warn(`[dync] No local item found for localId: ${localId} to apply remote values`);
1629
+ }
1630
+ await this.state.setState((syncState) => ({
1631
+ ...syncState,
1632
+ pendingChanges: syncState.pendingChanges.filter((p) => !(p.localId === localId && p.tableName === conflict.tableName))
1633
+ }));
1634
+ }
1635
+ await this.state.setState((syncState) => {
1636
+ const ss = { ...syncState };
1637
+ delete ss.conflicts?.[localId];
1638
+ return ss;
1639
+ });
1640
+ });
1641
+ }
1642
+ async enableSync(enabled) {
1643
+ if (!enabled) {
1644
+ if (this.syncTimerStarted) {
1645
+ this.disableSyncPromise = new Promise((resolve) => {
1646
+ this.disableSyncPromiseResolver = resolve;
1647
+ });
1648
+ this.sleepAbortController?.abort();
1649
+ this.syncStatus = "disabling";
1650
+ this.startSyncTimer(false);
1651
+ this.setupVisibilityListener(false);
1652
+ return this.disableSyncPromise;
1653
+ }
1654
+ this.syncStatus = "disabled";
1655
+ this.setupVisibilityListener(false);
1656
+ return Promise.resolve();
1657
+ }
1658
+ this.syncStatus = "idle";
1659
+ this.startSyncTimer(true);
1660
+ this.setupVisibilityListener(true);
1661
+ return Promise.resolve();
1662
+ }
1663
+ get syncStatus() {
1664
+ return this.state.getSyncStatus();
1665
+ }
1666
+ set syncStatus(status) {
1667
+ this.state.setSyncStatus(status);
1668
+ }
1669
+ onSyncStateChange(fn) {
1670
+ return this.state.subscribe(fn);
1671
+ }
1672
+ onMutation(fn) {
1673
+ this.mutationListeners.add(fn);
1674
+ return () => this.mutationListeners.delete(fn);
1675
+ }
1676
+ emitMutation(event) {
1677
+ if (event.type === "add" || event.type === "update" || event.type === "delete") {
1678
+ if (this.syncTimerStarted) {
1679
+ this.syncOnce().catch(() => {
1680
+ });
1681
+ }
1682
+ }
1683
+ for (const listener of this.mutationListeners) {
1684
+ listener(event);
1685
+ }
1686
+ }
1687
+ // Public API
1688
+ sync = {
1689
+ enable: this.enableSync.bind(this),
1690
+ startFirstLoad: this.startFirstLoad.bind(this),
1691
+ state: void 0,
1692
+ // getter in constructor
1693
+ resolveConflict: this.resolveConflict.bind(this),
1694
+ onStateChange: this.onSyncStateChange.bind(this),
1695
+ onMutation: this.onMutation.bind(this)
1696
+ };
1697
+ };
1698
+ var DyncConstructor = DyncBase;
1699
+ var Dync = DyncConstructor;
1700
+
1701
+ // src/storage/memory/MemoryQueryContext.ts
1702
+ var MemoryQueryContext = class {
1703
+ constructor(adapter) {
1704
+ this.adapter = adapter;
1705
+ }
1706
+ table(name) {
1707
+ return this.adapter.table(name);
1708
+ }
1709
+ transaction(mode, tableNames, callback) {
1710
+ return this.adapter.transaction(mode, tableNames, callback);
1711
+ }
1712
+ };
1713
+
1714
+ // src/storage/memory/types.ts
1715
+ var createDefaultState = () => ({
1716
+ predicate: () => true,
1717
+ orderBy: void 0,
1718
+ reverse: false,
1719
+ offset: 0,
1720
+ limit: void 0,
1721
+ distinct: false
1722
+ });
1723
+
1724
+ // src/storage/memory/MemoryCollection.ts
1725
+ var MemoryCollection = class _MemoryCollection {
1726
+ table;
1727
+ state;
1728
+ constructor(table, state) {
1729
+ this.table = table;
1730
+ this.state = state;
1731
+ }
1732
+ getState() {
1733
+ return { ...this.state };
1734
+ }
1735
+ matches(record, key) {
1736
+ return this.state.predicate(record, key);
1737
+ }
1738
+ clone(_props) {
1739
+ return new _MemoryCollection(this.table, { ...this.state });
1740
+ }
1741
+ reverse() {
1742
+ return this.withState({ reverse: !this.state.reverse });
1743
+ }
1744
+ offset(offset) {
1745
+ return this.withState({ offset });
1746
+ }
1747
+ limit(count) {
1748
+ return this.withState({ limit: count });
1749
+ }
1750
+ toCollection() {
1751
+ return this.clone();
1752
+ }
1753
+ distinct() {
1754
+ return this.withState({ distinct: true });
1755
+ }
1756
+ jsFilter(predicate) {
1757
+ return this.withState({ predicate: this.combinePredicate(predicate, "and") });
1758
+ }
1759
+ or(index) {
1760
+ return this.table.createWhereClause(index, this);
1761
+ }
1762
+ async first() {
1763
+ const entries = this.materializeEntries(true);
1764
+ return entries.at(0)?.[1];
1765
+ }
1766
+ async last() {
1767
+ const entries = this.materializeEntries(true);
1768
+ return entries.at(-1)?.[1];
1769
+ }
1770
+ async each(callback) {
1771
+ const entries = this.materializeEntries(true);
1772
+ for (let index = 0; index < entries.length; index += 1) {
1773
+ const [, record] = entries[index];
1774
+ await callback(record, index);
1775
+ }
1776
+ }
1777
+ async eachKey(callback) {
1778
+ const keys = await this.keys();
1779
+ for (let index = 0; index < keys.length; index += 1) {
1780
+ await callback(keys[index], index);
1781
+ }
1782
+ }
1783
+ async eachPrimaryKey(callback) {
1784
+ const keys = await this.primaryKeys();
1785
+ for (let index = 0; index < keys.length; index += 1) {
1786
+ await callback(keys[index], index);
1787
+ }
1788
+ }
1789
+ async eachUniqueKey(callback) {
1790
+ const keys = await this.uniqueKeys();
1791
+ for (let index = 0; index < keys.length; index += 1) {
1792
+ await callback(keys[index], index);
1793
+ }
1794
+ }
1795
+ async keys() {
1796
+ return this.materializeEntries(false).map(([key, record]) => this.table.resolvePublicKey(record, key));
1797
+ }
1798
+ async primaryKeys() {
1799
+ return this.keys();
1800
+ }
1801
+ async uniqueKeys() {
1802
+ const seen = /* @__PURE__ */ new Set();
1803
+ const keys = [];
1804
+ for (const [key, record] of this.materializeEntries(false)) {
1805
+ const publicKey = this.table.resolvePublicKey(record, key);
1806
+ const signature = JSON.stringify(publicKey);
1807
+ if (!seen.has(signature)) {
1808
+ seen.add(signature);
1809
+ keys.push(publicKey);
1810
+ }
1811
+ }
1812
+ return keys;
1813
+ }
1814
+ async count() {
1815
+ return this.materializeEntries(false).length;
1816
+ }
1817
+ async sortBy(key) {
1818
+ const entries = this.materializeEntries(true);
1819
+ entries.sort((a, b) => this.table.compareValues(a[1][key], b[1][key]));
1820
+ return entries.map(([, record]) => record);
1821
+ }
1822
+ async delete() {
1823
+ const entries = this.materializeEntries(false);
1824
+ for (const [key] of entries) {
1825
+ this.table.deleteByKey(key);
1826
+ }
1827
+ return entries.length;
1828
+ }
1829
+ async modify(changes) {
1830
+ const entries = this.materializeEntries(false);
1831
+ let modified = 0;
1832
+ for (const [key] of entries) {
1833
+ const current = this.table.getMutableRecord(key);
1834
+ if (!current) {
1835
+ continue;
1836
+ }
1837
+ if (typeof changes === "function") {
1838
+ const clone = this.table.cloneRecord(current);
1839
+ await changes(clone);
1840
+ clone._localId = current._localId ?? key;
1841
+ this.table.setMutableRecord(key, clone);
1842
+ } else {
1843
+ const updated = { ...current, ...changes, _localId: current._localId ?? key };
1844
+ this.table.setMutableRecord(key, updated);
1845
+ }
1846
+ modified += 1;
1847
+ }
1848
+ return modified;
1849
+ }
1850
+ async toArray() {
1851
+ return this.materializeEntries(true).map(([, record]) => record);
1852
+ }
1853
+ withState(overrides) {
1854
+ return new _MemoryCollection(this.table, {
1855
+ ...this.state,
1856
+ ...overrides,
1857
+ predicate: overrides.predicate ?? this.state.predicate
1858
+ });
1859
+ }
1860
+ combinePredicate(predicate, mode) {
1861
+ if (mode === "and") {
1862
+ return (record, key) => this.state.predicate(record, key) && predicate(record);
1863
+ }
1864
+ return (record, key) => this.state.predicate(record, key) || predicate(record);
1865
+ }
1866
+ materializeEntries(clone) {
1867
+ let entries = this.table.entries().filter(([key, record]) => this.state.predicate(record, key));
1868
+ if (this.state.orderBy) {
1869
+ const { index, direction } = this.state.orderBy;
1870
+ entries = [...entries].sort((a, b) => this.table.compareEntries(a[1], b[1], index));
1871
+ if (direction === "desc") {
1872
+ entries.reverse();
1873
+ }
1874
+ }
1875
+ if (this.state.reverse) {
1876
+ entries = [...entries].reverse();
1877
+ }
1878
+ if (this.state.distinct) {
1879
+ const seen = /* @__PURE__ */ new Set();
1880
+ entries = entries.filter(([, record]) => {
1881
+ const signature = JSON.stringify(record);
1882
+ if (seen.has(signature)) {
1883
+ return false;
1884
+ }
1885
+ seen.add(signature);
1886
+ return true;
1887
+ });
1888
+ }
1889
+ if (this.state.offset > 0) {
1890
+ entries = entries.slice(this.state.offset);
1891
+ }
1892
+ if (typeof this.state.limit === "number") {
1893
+ entries = entries.slice(0, this.state.limit);
1894
+ }
1895
+ if (clone) {
1896
+ return entries.map(([key, record]) => [key, this.table.cloneRecord(record)]);
1897
+ }
1898
+ return entries;
1899
+ }
1900
+ };
1901
+
1902
+ // src/storage/memory/MemoryWhereClause.ts
1903
+ var MemoryWhereClause = class {
1904
+ table;
1905
+ column;
1906
+ baseCollection;
1907
+ constructor(table, column, baseCollection) {
1908
+ this.table = table;
1909
+ this.column = column;
1910
+ this.baseCollection = baseCollection;
1911
+ }
1912
+ equals(value) {
1913
+ return this.createCollection((current) => this.table.compareValues(current, value) === 0);
1914
+ }
1915
+ above(value) {
1916
+ return this.createCollection((current) => this.table.compareValues(current, value) > 0);
1917
+ }
1918
+ aboveOrEqual(value) {
1919
+ return this.createCollection((current) => this.table.compareValues(current, value) >= 0);
1920
+ }
1921
+ below(value) {
1922
+ return this.createCollection((current) => this.table.compareValues(current, value) < 0);
1923
+ }
1924
+ belowOrEqual(value) {
1925
+ return this.createCollection((current) => this.table.compareValues(current, value) <= 0);
1926
+ }
1927
+ between(lower, upper, includeLower = true, includeUpper = false) {
1928
+ return this.createCollection((current) => {
1929
+ const lowerCmp = this.table.compareValues(current, lower);
1930
+ const upperCmp = this.table.compareValues(current, upper);
1931
+ const lowerOk = includeLower ? lowerCmp >= 0 : lowerCmp > 0;
1932
+ const upperOk = includeUpper ? upperCmp <= 0 : upperCmp < 0;
1933
+ return lowerOk && upperOk;
1934
+ });
1935
+ }
1936
+ inAnyRange(ranges, options) {
1937
+ const includeLower = options?.includeLower ?? true;
1938
+ const includeUpper = options?.includeUpper ?? false;
1939
+ return this.createCollection((current) => {
1940
+ for (const [lower, upper] of ranges) {
1941
+ const lowerCmp = this.table.compareValues(current, lower);
1942
+ const upperCmp = this.table.compareValues(current, upper);
1943
+ const lowerOk = includeLower ? lowerCmp >= 0 : lowerCmp > 0;
1944
+ const upperOk = includeUpper ? upperCmp <= 0 : upperCmp < 0;
1945
+ if (lowerOk && upperOk) {
1946
+ return true;
1947
+ }
1948
+ }
1949
+ return false;
1950
+ });
1951
+ }
1952
+ startsWith(prefix) {
1953
+ return this.createCollection((current) => typeof current === "string" && current.startsWith(prefix));
1954
+ }
1955
+ startsWithIgnoreCase(prefix) {
1956
+ return this.createCollection((current) => typeof current === "string" && current.toLowerCase().startsWith(prefix.toLowerCase()));
1957
+ }
1958
+ startsWithAnyOf(...args) {
1959
+ const prefixes = this.flattenArgs(args);
1960
+ return this.createCollection((current) => typeof current === "string" && prefixes.some((prefix) => current.startsWith(prefix)));
1961
+ }
1962
+ startsWithAnyOfIgnoreCase(...args) {
1963
+ const prefixes = this.flattenArgs(args).map((prefix) => prefix.toLowerCase());
1964
+ return this.createCollection((current) => typeof current === "string" && prefixes.some((prefix) => current.toLowerCase().startsWith(prefix)));
1965
+ }
1966
+ equalsIgnoreCase(value) {
1967
+ return this.createCollection((current) => typeof current === "string" && current.toLowerCase() === value.toLowerCase());
1968
+ }
1969
+ anyOf(...args) {
1970
+ const values = this.flattenArgs(args);
1971
+ const valueSet = new Set(values.map((entry) => JSON.stringify(entry)));
1972
+ return this.createCollection((current) => valueSet.has(JSON.stringify(current)));
1973
+ }
1974
+ anyOfIgnoreCase(...args) {
1975
+ const values = this.flattenArgs(args).map((value) => value.toLowerCase());
1976
+ const valueSet = new Set(values);
1977
+ return this.createCollection((current) => typeof current === "string" && valueSet.has(current.toLowerCase()));
1978
+ }
1979
+ noneOf(...args) {
1980
+ const values = this.flattenArgs(args);
1981
+ const valueSet = new Set(values.map((entry) => JSON.stringify(entry)));
1982
+ return this.createCollection((current) => !valueSet.has(JSON.stringify(current)));
1983
+ }
1984
+ notEqual(value) {
1985
+ return this.createCollection((current) => this.table.compareValues(current, value) !== 0);
1986
+ }
1987
+ createCollection(predicate) {
1988
+ const condition = (record, _key) => predicate(this.table.getIndexValue(record, this.column));
1989
+ if (this.baseCollection) {
1990
+ const combined = (record, key) => this.baseCollection.matches(record, key) || predicate(this.table.getIndexValue(record, this.column));
1991
+ return this.table.createCollectionFromPredicate(combined, this.baseCollection);
1992
+ }
1993
+ return this.table.createCollectionFromPredicate(condition);
1994
+ }
1995
+ flattenArgs(args) {
1996
+ if (args.length === 1 && Array.isArray(args[0])) {
1997
+ return args[0];
1998
+ }
1999
+ return args;
2000
+ }
2001
+ };
2002
+
2003
+ // src/storage/memory/MemoryTable.ts
2004
+ var MemoryTable = class {
2005
+ name;
2006
+ schema = void 0;
2007
+ primaryKey = LOCAL_PK;
2008
+ raw;
2009
+ records = /* @__PURE__ */ new Map();
2010
+ constructor(name) {
2011
+ this.name = name;
2012
+ this.raw = {
2013
+ add: async (item) => this.baseAdd(item),
2014
+ put: async (item) => this.basePut(item),
2015
+ update: async (key, changes) => this.baseUpdate(key, changes),
2016
+ delete: async (key) => {
2017
+ this.baseDelete(key);
2018
+ },
2019
+ get: async (key) => this.baseGet(key),
2020
+ bulkAdd: async (items) => this.baseBulkAdd(items),
2021
+ bulkPut: async (items) => this.baseBulkPut(items),
2022
+ bulkUpdate: async (keysAndChanges) => this.baseBulkUpdate(keysAndChanges),
2023
+ bulkDelete: async (keys) => this.baseBulkDelete(keys),
2024
+ clear: async () => this.baseClear()
2025
+ };
2026
+ }
2027
+ async add(item) {
2028
+ return this.baseAdd(item);
2029
+ }
2030
+ async put(item) {
2031
+ return this.basePut(item);
2032
+ }
2033
+ async update(key, changes) {
2034
+ return this.baseUpdate(key, changes);
2035
+ }
2036
+ async delete(key) {
2037
+ this.baseDelete(key);
2038
+ }
2039
+ async clear() {
2040
+ this.baseClear();
2041
+ }
2042
+ baseClear() {
2043
+ this.records.clear();
2044
+ }
2045
+ async get(key) {
2046
+ const stored = this.baseGet(key);
2047
+ return stored ? this.cloneRecord(stored) : void 0;
2048
+ }
2049
+ async toArray() {
2050
+ return this.entries().map(([, record]) => this.cloneRecord(record));
2051
+ }
2052
+ async count() {
2053
+ return this.records.size;
2054
+ }
2055
+ async bulkAdd(items) {
2056
+ return this.baseBulkAdd(items);
2057
+ }
2058
+ baseBulkAdd(items) {
2059
+ const keys = [];
2060
+ for (let index = 0; index < items.length; index += 1) {
2061
+ const item = items[index];
2062
+ keys.push(this.baseAdd(item));
2063
+ }
2064
+ return keys;
2065
+ }
2066
+ async bulkPut(items) {
2067
+ return this.baseBulkPut(items);
2068
+ }
2069
+ baseBulkPut(items) {
2070
+ const keys = [];
2071
+ for (let index = 0; index < items.length; index += 1) {
2072
+ const item = items[index];
2073
+ keys.push(this.basePut(item));
2074
+ }
2075
+ return keys;
2076
+ }
2077
+ async bulkGet(keys) {
2078
+ return Promise.all(keys.map((key) => this.get(key)));
2079
+ }
2080
+ async bulkUpdate(keysAndChanges) {
2081
+ return this.baseBulkUpdate(keysAndChanges);
2082
+ }
2083
+ baseBulkUpdate(keysAndChanges) {
2084
+ let updatedCount = 0;
2085
+ for (const { key, changes } of keysAndChanges) {
2086
+ const result = this.baseUpdate(key, changes);
2087
+ updatedCount += result;
2088
+ }
2089
+ return updatedCount;
2090
+ }
2091
+ async bulkDelete(keys) {
2092
+ this.baseBulkDelete(keys);
2093
+ }
2094
+ baseBulkDelete(keys) {
2095
+ for (const key of keys) {
2096
+ this.baseDelete(key);
2097
+ }
2098
+ }
2099
+ where(index) {
2100
+ return this.createWhereClause(index);
2101
+ }
2102
+ orderBy(index) {
2103
+ return this.createCollection({
2104
+ orderBy: { index, direction: "asc" }
2105
+ });
2106
+ }
2107
+ reverse() {
2108
+ return this.createCollection({ reverse: true });
2109
+ }
2110
+ offset(offset) {
2111
+ return this.createCollection({ offset });
2112
+ }
2113
+ limit(count) {
2114
+ return this.createCollection({ limit: count });
2115
+ }
2116
+ async each(callback) {
2117
+ for (const [, record] of this.entries()) {
2118
+ await callback(this.cloneRecord(record));
2119
+ }
2120
+ }
2121
+ jsFilter(predicate) {
2122
+ return this.createCollection({ predicate: (record) => predicate(record) });
2123
+ }
2124
+ createCollection(stateOverrides) {
2125
+ const baseState = createDefaultState();
2126
+ const state = {
2127
+ ...baseState,
2128
+ ...stateOverrides,
2129
+ predicate: stateOverrides?.predicate ?? baseState.predicate
2130
+ };
2131
+ return new MemoryCollection(this, state);
2132
+ }
2133
+ createCollectionFromPredicate(predicate, template) {
2134
+ const baseState = template ? template.getState() : createDefaultState();
2135
+ return new MemoryCollection(this, {
2136
+ ...baseState,
2137
+ predicate
2138
+ });
2139
+ }
2140
+ createWhereClause(column, baseCollection) {
2141
+ return new MemoryWhereClause(this, column, baseCollection);
2142
+ }
2143
+ entries() {
2144
+ return Array.from(this.records.entries());
2145
+ }
2146
+ cloneRecord(record) {
2147
+ return { ...record };
2148
+ }
2149
+ deleteByKey(key) {
2150
+ this.records.delete(key);
2151
+ }
2152
+ getMutableRecord(key) {
2153
+ return this.records.get(key);
2154
+ }
2155
+ setMutableRecord(key, record) {
2156
+ this.records.set(key, { ...record, _localId: record._localId ?? key });
2157
+ }
2158
+ resolvePublicKey(record, key) {
2159
+ if (record._localId !== void 0) {
2160
+ return record._localId;
2161
+ }
2162
+ if (record.id !== void 0) {
2163
+ return record.id;
2164
+ }
2165
+ return key;
2166
+ }
2167
+ getIndexValue(record, index) {
2168
+ if (Array.isArray(index)) {
2169
+ return index.map((key) => record[key]);
2170
+ }
2171
+ return record[index];
2172
+ }
2173
+ compareEntries(left, right, index) {
2174
+ if (Array.isArray(index)) {
2175
+ for (const key of index) {
2176
+ const diff = this.compareValues(left[key], right[key]);
2177
+ if (diff !== 0) {
2178
+ return diff;
2179
+ }
2180
+ }
2181
+ return 0;
2182
+ }
2183
+ return this.compareValues(left[index], right[index]);
2184
+ }
2185
+ compareValues(left, right) {
2186
+ const normalizedLeft = this.normalizeComparableValue(left);
2187
+ const normalizedRight = this.normalizeComparableValue(right);
2188
+ if (normalizedLeft < normalizedRight) {
2189
+ return -1;
2190
+ }
2191
+ if (normalizedLeft > normalizedRight) {
2192
+ return 1;
2193
+ }
2194
+ return 0;
2195
+ }
2196
+ normalizeComparableValue(value) {
2197
+ if (Array.isArray(value)) {
2198
+ return value.map((entry) => this.normalizeComparableValue(entry));
2199
+ }
2200
+ if (value instanceof Date) {
2201
+ return value.valueOf();
2202
+ }
2203
+ return value ?? null;
2204
+ }
2205
+ baseAdd(item) {
2206
+ const primaryKey = this.createPrimaryKey(item);
2207
+ const stored = { ...item, _localId: primaryKey };
2208
+ this.records.set(primaryKey, stored);
2209
+ return primaryKey;
2210
+ }
2211
+ basePut(item) {
2212
+ const primaryKey = this.createPrimaryKey(item);
2213
+ const stored = { ...item, _localId: primaryKey };
2214
+ this.records.set(primaryKey, stored);
2215
+ return primaryKey;
2216
+ }
2217
+ baseUpdate(key, changes) {
2218
+ const primaryKey = this.resolveKey(key);
2219
+ if (!primaryKey) {
2220
+ return 0;
2221
+ }
2222
+ const existing = this.records.get(primaryKey);
2223
+ if (!existing) {
2224
+ return 0;
2225
+ }
2226
+ const updated = { ...existing, ...changes, _localId: existing._localId ?? primaryKey };
2227
+ this.records.set(primaryKey, updated);
2228
+ return 1;
2229
+ }
2230
+ baseDelete(key) {
2231
+ const primaryKey = this.resolveKey(key);
2232
+ if (primaryKey) {
2233
+ this.records.delete(primaryKey);
2234
+ }
2235
+ }
2236
+ baseGet(key) {
2237
+ const primaryKey = this.resolveKey(key);
2238
+ if (!primaryKey) {
2239
+ return void 0;
2240
+ }
2241
+ return this.records.get(primaryKey);
2242
+ }
2243
+ createPrimaryKey(item) {
2244
+ if (item._localId && typeof item._localId === "string") {
2245
+ return item._localId;
2246
+ }
2247
+ if (item.id !== void 0 && (typeof item.id === "string" || typeof item.id === "number" || typeof item.id === "bigint")) {
2248
+ return String(item.id);
2249
+ }
2250
+ return createLocalId();
2251
+ }
2252
+ resolveKey(key) {
2253
+ if (typeof key === "string") {
2254
+ return key;
2255
+ }
2256
+ if (typeof key === "number" || typeof key === "bigint") {
2257
+ return String(key);
2258
+ }
2259
+ if (key && typeof key === "object" && "id" in key) {
2260
+ const lookup = key.id;
2261
+ for (const [storedKey, record] of this.records.entries()) {
2262
+ if (record.id === lookup) {
2263
+ return storedKey;
2264
+ }
2265
+ }
2266
+ }
2267
+ return void 0;
2268
+ }
2269
+ };
2270
+
2271
+ // src/storage/memory/MemoryAdapter.ts
2272
+ var MemoryAdapter = class {
2273
+ type = "MemoryAdapter";
2274
+ name;
2275
+ tables = /* @__PURE__ */ new Map();
2276
+ constructor(name) {
2277
+ this.name = name;
2278
+ }
2279
+ async open() {
2280
+ }
2281
+ async close() {
2282
+ this.tables.clear();
2283
+ }
2284
+ async delete() {
2285
+ this.tables.clear();
2286
+ }
2287
+ async query(callback) {
2288
+ return callback(new MemoryQueryContext(this));
2289
+ }
2290
+ defineSchema(_version, schema, _options) {
2291
+ for (const tableName of Object.keys(schema)) {
2292
+ this.ensureTable(tableName);
2293
+ }
2294
+ }
2295
+ table(name) {
2296
+ return this.ensureTable(name);
2297
+ }
2298
+ async transaction(_mode, tableNames, callback) {
2299
+ const tables = {};
2300
+ for (const tableName of tableNames) {
2301
+ tables[tableName] = this.ensureTable(tableName);
2302
+ }
2303
+ return callback({ tables });
2304
+ }
2305
+ ensureTable(name) {
2306
+ if (!this.tables.has(name)) {
2307
+ this.tables.set(name, new MemoryTable(name));
2308
+ }
2309
+ return this.tables.get(name);
2310
+ }
2311
+ };
2312
+
2313
+ // src/storage/sqlite/helpers.ts
2314
+ var SQLITE_SCHEMA_VERSION_STATE_KEY = "sqlite_schema_version";
2315
+ var DEFAULT_STREAM_BATCH_SIZE = 200;
2316
+ var createDefaultState2 = () => ({
2317
+ orGroups: [[]],
2318
+ jsPredicate: void 0,
2319
+ orderBy: void 0,
2320
+ reverse: false,
2321
+ offset: 0,
2322
+ limit: void 0,
2323
+ distinct: false
2324
+ });
2325
+ var buildWhereClause = (orGroups) => {
2326
+ const nonEmptyGroups = orGroups.filter((group) => group.length > 0);
2327
+ if (nonEmptyGroups.length === 0) {
2328
+ return { whereClause: "", parameters: [] };
2329
+ }
2330
+ const groupClauses = [];
2331
+ const parameters = [];
2332
+ for (const group of nonEmptyGroups) {
2333
+ const conditionClauses = [];
2334
+ for (const condition of group) {
2335
+ const built = buildCondition(condition);
2336
+ conditionClauses.push(built.clause);
2337
+ parameters.push(...built.parameters);
2338
+ }
2339
+ const groupClause = conditionClauses.length === 1 ? conditionClauses[0] : `(${conditionClauses.join(" AND ")})`;
2340
+ groupClauses.push(groupClause);
2341
+ }
2342
+ const whereContent = groupClauses.length === 1 ? groupClauses[0] : `(${groupClauses.join(" OR ")})`;
2343
+ return {
2344
+ whereClause: `WHERE ${whereContent}`,
2345
+ parameters
2346
+ };
2347
+ };
2348
+ var buildCondition = (condition) => {
2349
+ if (condition.type === "or") {
2350
+ if (condition.conditions.length === 0) {
2351
+ return { clause: "0 = 1", parameters: [] };
2352
+ }
2353
+ const subClauses = [];
2354
+ const subParams = [];
2355
+ for (const sub of condition.conditions) {
2356
+ const built = buildCondition(sub);
2357
+ subClauses.push(built.clause);
2358
+ subParams.push(...built.parameters);
2359
+ }
2360
+ return { clause: `(${subClauses.join(" OR ")})`, parameters: subParams };
2361
+ }
2362
+ const col = quoteIdentifier(condition.column);
2363
+ switch (condition.type) {
2364
+ case "equals": {
2365
+ if (condition.caseInsensitive) {
2366
+ return { clause: `${col} = ? COLLATE NOCASE`, parameters: [condition.value] };
2367
+ }
2368
+ return { clause: `${col} = ?`, parameters: [condition.value] };
2369
+ }
2370
+ case "comparison": {
2371
+ return { clause: `${col} ${condition.op} ?`, parameters: [condition.value] };
2372
+ }
2373
+ case "between": {
2374
+ const lowerOp = condition.includeLower ? ">=" : ">";
2375
+ const upperOp = condition.includeUpper ? "<=" : "<";
2376
+ return {
2377
+ clause: `(${col} ${lowerOp} ? AND ${col} ${upperOp} ?)`,
2378
+ parameters: [condition.lower, condition.upper]
2379
+ };
2380
+ }
2381
+ case "in": {
2382
+ if (condition.values.length === 0) {
2383
+ return { clause: "0 = 1", parameters: [] };
2384
+ }
2385
+ const placeholders = condition.values.map(() => "?").join(", ");
2386
+ if (condition.caseInsensitive) {
2387
+ return {
2388
+ clause: `${col} COLLATE NOCASE IN (${placeholders})`,
2389
+ parameters: condition.values
2390
+ };
2391
+ }
2392
+ return { clause: `${col} IN (${placeholders})`, parameters: condition.values };
2393
+ }
2394
+ case "notIn": {
2395
+ if (condition.values.length === 0) {
2396
+ return { clause: "1 = 1", parameters: [] };
2397
+ }
2398
+ const placeholders = condition.values.map(() => "?").join(", ");
2399
+ return { clause: `${col} NOT IN (${placeholders})`, parameters: condition.values };
2400
+ }
2401
+ case "like": {
2402
+ if (condition.caseInsensitive) {
2403
+ return { clause: `${col} LIKE ?`, parameters: [condition.pattern] };
2404
+ }
2405
+ const globPattern = condition.pattern.replace(/%/g, "*").replace(/_/g, "?");
2406
+ return { clause: `${col} GLOB ?`, parameters: [globPattern] };
2407
+ }
2408
+ }
2409
+ };
2410
+ var cloneValue = (value) => {
2411
+ if (value == null || typeof value !== "object") return value;
2412
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype) {
2413
+ const obj = value;
2414
+ let isFlat = true;
2415
+ for (const key in obj) {
2416
+ const v = obj[key];
2417
+ if (v !== null && typeof v === "object") {
2418
+ isFlat = false;
2419
+ break;
2420
+ }
2421
+ }
2422
+ if (isFlat) return { ...obj };
2423
+ }
2424
+ if (typeof globalThis.structuredClone === "function") {
2425
+ return globalThis.structuredClone(value);
2426
+ }
2427
+ return JSON.parse(JSON.stringify(value));
2428
+ };
2429
+ var quoteIdentifier = (name) => `"${name.replace(/"/g, '""')}"`;
2430
+ var normalizeComparableValue = (value) => {
2431
+ if (Array.isArray(value)) {
2432
+ return value.map((entry) => normalizeComparableValue(entry));
2433
+ }
2434
+ if (value instanceof Date) {
2435
+ return value.valueOf();
2436
+ }
2437
+ if (value === void 0) {
2438
+ return null;
2439
+ }
2440
+ return value;
2441
+ };
2442
+
2443
+ // src/storage/sqlite/SqliteQueryContext.ts
2444
+ var SqliteQueryContext = class {
2445
+ constructor(driver, adapter) {
2446
+ this.driver = driver;
2447
+ this.adapter = adapter;
2448
+ }
2449
+ table(name) {
2450
+ return this.adapter.table(name);
2451
+ }
2452
+ transaction(mode, tableNames, callback) {
2453
+ return this.adapter.transaction(mode, tableNames, callback);
2454
+ }
2455
+ async execute(statement) {
2456
+ return this.driver.execute(statement);
2457
+ }
2458
+ async run(statement, values) {
2459
+ return this.driver.run(statement, values);
2460
+ }
2461
+ async queryRows(statement, values) {
2462
+ return this.adapter.queryRows(statement, values);
2463
+ }
2464
+ };
2465
+
2466
+ // src/storage/sqlite/SQLiteAdapter.ts
2467
+ var SQLiteAdapter2 = class {
2468
+ type = "SQLiteAdapter";
2469
+ name;
2470
+ options;
2471
+ schemas = /* @__PURE__ */ new Map();
2472
+ versionSchemas = /* @__PURE__ */ new Map();
2473
+ versionOptions = /* @__PURE__ */ new Map();
2474
+ tableCache = /* @__PURE__ */ new Map();
2475
+ driver;
2476
+ openPromise;
2477
+ isOpen = false;
2478
+ schemaApplied = false;
2479
+ transactionDepth = 0;
2480
+ targetVersion = 0;
2481
+ constructor(driver, options = {}) {
2482
+ this.driver = driver;
2483
+ this.name = driver.name;
2484
+ this.options = options;
2485
+ }
2486
+ get driverType() {
2487
+ return this.driver.type;
2488
+ }
2489
+ /**
2490
+ * Opens the database connection and applies schema.
2491
+ * This is called automatically when performing operations,
2492
+ * so explicit calls are optional but safe (idempotent).
2493
+ * When called explicitly after schema changes, it will run any pending migrations.
2494
+ */
2495
+ async open() {
2496
+ if (this.isOpen) {
2497
+ await this.runPendingMigrations();
2498
+ return;
2499
+ }
2500
+ return this.ensureOpen();
2501
+ }
2502
+ async ensureOpen() {
2503
+ if (this.isOpen) {
2504
+ return;
2505
+ }
2506
+ if (this.openPromise) {
2507
+ return this.openPromise;
2508
+ }
2509
+ this.openPromise = this.performOpen();
2510
+ try {
2511
+ await this.openPromise;
2512
+ } finally {
2513
+ this.openPromise = void 0;
2514
+ }
2515
+ }
2516
+ async performOpen() {
2517
+ await this.driver.open();
2518
+ await this.applySchema();
2519
+ await this.runPendingMigrations();
2520
+ this.isOpen = true;
2521
+ }
2522
+ async close() {
2523
+ if (this.driver) {
2524
+ await this.driver.close();
2525
+ }
2526
+ this.isOpen = false;
2527
+ this.tableCache.clear();
2528
+ }
2529
+ async delete() {
2530
+ for (const table of this.schemas.keys()) {
2531
+ await this.execute(`DROP TABLE IF EXISTS ${quoteIdentifier(table)}`);
2532
+ }
2533
+ await this.execute(`DROP TABLE IF EXISTS ${quoteIdentifier(DYNC_STATE_TABLE)}`);
2534
+ this.tableCache.clear();
2535
+ this.schemaApplied = false;
2536
+ this.refreshActiveSchema();
2537
+ }
2538
+ defineSchema(version, schema, options) {
2539
+ const normalized = /* @__PURE__ */ new Map();
2540
+ for (const [tableName, definition] of Object.entries(schema)) {
2541
+ if (typeof definition === "string") {
2542
+ throw new Error(`SQLite adapter requires structured schema definitions. Table '${tableName}' must provide an object-based schema.`);
2543
+ }
2544
+ normalized.set(tableName, this.parseStructuredSchema(tableName, definition));
2545
+ }
2546
+ this.versionSchemas.set(version, normalized);
2547
+ this.versionOptions.set(version, options ?? {});
2548
+ this.refreshActiveSchema();
2549
+ }
2550
+ refreshActiveSchema() {
2551
+ if (!this.versionSchemas.size) {
2552
+ this.schemas.clear();
2553
+ this.targetVersion = 0;
2554
+ this.schemaApplied = false;
2555
+ this.tableCache.clear();
2556
+ return;
2557
+ }
2558
+ const versions = Array.from(this.versionSchemas.keys());
2559
+ const latestVersion = Math.max(...versions);
2560
+ const latestSchema = this.versionSchemas.get(latestVersion);
2561
+ if (!latestSchema) {
2562
+ return;
2563
+ }
2564
+ this.schemas.clear();
2565
+ for (const [name, schema] of latestSchema.entries()) {
2566
+ this.schemas.set(name, schema);
2567
+ }
2568
+ if (this.targetVersion !== latestVersion) {
2569
+ this.tableCache.clear();
2570
+ }
2571
+ this.targetVersion = latestVersion;
2572
+ this.schemaApplied = false;
2573
+ }
2574
+ table(name) {
2575
+ if (!this.schemas.has(name)) {
2576
+ throw new Error(`Table '${name}' is not part of the defined schema`);
2577
+ }
2578
+ if (!this.tableCache.has(name)) {
2579
+ this.tableCache.set(name, new SQLiteTable(this, this.schemas.get(name)));
2580
+ }
2581
+ return this.tableCache.get(name);
2582
+ }
2583
+ async transaction(_mode, tableNames, callback) {
2584
+ const driver = await this.getDriver();
2585
+ const shouldManageTransaction = this.transactionDepth === 0;
2586
+ this.transactionDepth += 1;
2587
+ if (shouldManageTransaction) {
2588
+ this.logSql("BEGIN TRANSACTION");
2589
+ await driver.execute("BEGIN TRANSACTION");
2590
+ }
2591
+ try {
2592
+ const tables = {};
2593
+ for (const tableName of tableNames) {
2594
+ tables[tableName] = this.table(tableName);
2595
+ }
2596
+ const result = await callback({ tables });
2597
+ if (shouldManageTransaction) {
2598
+ this.logSql("COMMIT");
2599
+ await driver.execute("COMMIT");
2600
+ }
2601
+ return result;
2602
+ } catch (err) {
2603
+ if (shouldManageTransaction) {
2604
+ this.logSql("ROLLBACK");
2605
+ await driver.execute("ROLLBACK");
2606
+ }
2607
+ throw err;
2608
+ } finally {
2609
+ this.transactionDepth -= 1;
2610
+ }
2611
+ }
2612
+ async execute(statement, values) {
2613
+ if (values && values.length) {
2614
+ await this.run(statement, values);
2615
+ return;
2616
+ }
2617
+ const driver = await this.getDriver();
2618
+ this.logSql(statement);
2619
+ await driver.execute(statement);
2620
+ }
2621
+ async run(statement, values) {
2622
+ const driver = await this.getDriver();
2623
+ const params = values ?? [];
2624
+ this.logSql(statement, params);
2625
+ return driver.run(statement, params);
2626
+ }
2627
+ async query(arg1, arg2) {
2628
+ if (typeof arg1 === "function") {
2629
+ const driver2 = await this.getDriver();
2630
+ return arg1(new SqliteQueryContext(driver2, this));
2631
+ }
2632
+ const statement = arg1;
2633
+ const values = arg2;
2634
+ const driver = await this.getDriver();
2635
+ const params = values ?? [];
2636
+ this.logSql(statement, params);
2637
+ return driver.query(statement, params);
2638
+ }
2639
+ async queryRows(statement, values) {
2640
+ const result = await this.query(statement, values);
2641
+ const columns = result.columns ?? [];
2642
+ return (result.values ?? []).map((row) => {
2643
+ const record = {};
2644
+ for (let index = 0; index < columns.length; index += 1) {
2645
+ record[columns[index]] = row[index];
2646
+ }
2647
+ return record;
2648
+ });
2649
+ }
2650
+ /**
2651
+ * Ensures the database is open and returns the driver.
2652
+ * This is the main entry point for all public database operations.
2653
+ */
2654
+ async getDriver() {
2655
+ await this.ensureOpen();
2656
+ return this.driver;
2657
+ }
2658
+ /**
2659
+ * Internal execute that uses driver directly.
2660
+ * Used during the open process to avoid recursion.
2661
+ */
2662
+ async internalExecute(statement, values) {
2663
+ if (values && values.length) {
2664
+ await this.internalRun(statement, values);
2665
+ return;
2666
+ }
2667
+ this.logSql(statement);
2668
+ await this.driver.execute(statement);
2669
+ }
2670
+ /**
2671
+ * Internal run that uses driver directly.
2672
+ * Used during the open process to avoid recursion.
2673
+ */
2674
+ async internalRun(statement, values) {
2675
+ const params = values ?? [];
2676
+ this.logSql(statement, params);
2677
+ return this.driver.run(statement, params);
2678
+ }
2679
+ /**
2680
+ * Internal queryRows that uses driver directly.
2681
+ * Used during the open process to avoid recursion.
2682
+ */
2683
+ async internalQueryRows(statement, values) {
2684
+ const params = values ?? [];
2685
+ this.logSql(statement, params);
2686
+ const result = await this.driver.query(statement, params);
2687
+ const columns = result.columns ?? [];
2688
+ return (result.values ?? []).map((row) => {
2689
+ const record = {};
2690
+ for (let index = 0; index < columns.length; index += 1) {
2691
+ record[columns[index]] = row[index];
2692
+ }
2693
+ return record;
2694
+ });
2695
+ }
2696
+ /**
2697
+ * Internal query that uses driver directly.
2698
+ * Used during migrations to avoid recursion.
2699
+ */
2700
+ async internalQuery(statement, values) {
2701
+ const params = values ?? [];
2702
+ this.logSql(statement, params);
2703
+ return this.driver.query(statement, params);
2704
+ }
2705
+ logSql(statement, parameters) {
2706
+ const { debug } = this.options;
2707
+ if (!debug) {
2708
+ return;
2709
+ }
2710
+ const hasParams = parameters && parameters.length;
2711
+ if (typeof debug === "function") {
2712
+ debug(statement, hasParams ? parameters : void 0);
2713
+ return;
2714
+ }
2715
+ if (debug === true) {
2716
+ if (hasParams) {
2717
+ console.debug("[dync][sqlite]", statement, parameters);
2718
+ } else {
2719
+ console.debug("[dync][sqlite]", statement);
2720
+ }
2721
+ }
2722
+ }
2723
+ async getStoredSchemaVersion() {
2724
+ const rows = await this.internalQueryRows(`SELECT value FROM ${quoteIdentifier(DYNC_STATE_TABLE)} WHERE ${quoteIdentifier(LOCAL_PK)} = ? LIMIT 1`, [
2725
+ SQLITE_SCHEMA_VERSION_STATE_KEY
2726
+ ]);
2727
+ const rawValue = rows[0]?.value;
2728
+ const parsed = Number(rawValue ?? 0);
2729
+ return Number.isFinite(parsed) ? parsed : 0;
2730
+ }
2731
+ async setStoredSchemaVersion(version) {
2732
+ await this.internalRun(
2733
+ `INSERT INTO ${quoteIdentifier(DYNC_STATE_TABLE)} (${quoteIdentifier(LOCAL_PK)}, value) VALUES (?, ?) ON CONFLICT(${quoteIdentifier(LOCAL_PK)}) DO UPDATE SET value = excluded.value`,
2734
+ [SQLITE_SCHEMA_VERSION_STATE_KEY, String(version)]
2735
+ );
2736
+ }
2737
+ async runPendingMigrations() {
2738
+ if (!this.versionSchemas.size) {
2739
+ await this.setStoredSchemaVersion(0);
2740
+ return;
2741
+ }
2742
+ const targetVersion = this.targetVersion;
2743
+ const currentVersion = await this.getStoredSchemaVersion();
2744
+ if (currentVersion === targetVersion) {
2745
+ return;
2746
+ }
2747
+ if (currentVersion < targetVersion) {
2748
+ for (let version = currentVersion + 1; version <= targetVersion; version += 1) {
2749
+ await this.runMigrationStep(version, "upgrade", version - 1, version);
2750
+ await this.setStoredSchemaVersion(version);
2751
+ }
2752
+ return;
2753
+ }
2754
+ for (let version = currentVersion; version > targetVersion; version -= 1) {
2755
+ await this.runMigrationStep(version, "downgrade", version, version - 1);
2756
+ await this.setStoredSchemaVersion(version - 1);
2757
+ }
2758
+ }
2759
+ async runMigrationStep(version, direction, fromVersion, toVersion) {
2760
+ const handler = this.getMigrationHandler(version, direction);
2761
+ if (!handler) {
2762
+ return;
2763
+ }
2764
+ const context = {
2765
+ direction,
2766
+ fromVersion,
2767
+ toVersion,
2768
+ execute: (statement) => this.internalExecute(statement),
2769
+ run: (statement, values) => this.internalRun(statement, values),
2770
+ query: (statement, values) => this.internalQuery(statement, values)
2771
+ };
2772
+ await handler(context);
2773
+ }
2774
+ getMigrationHandler(version, direction) {
2775
+ const options = this.versionOptions.get(version);
2776
+ const migrations = options?.sqlite?.migrations;
2777
+ if (!migrations) {
2778
+ return void 0;
2779
+ }
2780
+ return direction === "upgrade" ? migrations.upgrade : migrations.downgrade;
2781
+ }
2782
+ async applySchema() {
2783
+ if (this.schemaApplied) {
2784
+ return;
2785
+ }
2786
+ for (const schema of this.schemas.values()) {
2787
+ await this.internalExecute(this.buildCreateTableStatement(schema));
2788
+ const indexStatements = this.buildIndexStatements(schema);
2789
+ for (const statement of indexStatements) {
2790
+ await this.internalExecute(statement);
2791
+ }
2792
+ }
2793
+ this.schemaApplied = true;
2794
+ }
2795
+ buildCreateTableStatement(schema) {
2796
+ const columns = [];
2797
+ for (const column of Object.values(schema.definition.columns)) {
2798
+ columns.push(this.buildStructuredColumnDefinition(column));
2799
+ }
2800
+ if (schema.definition.source === "structured" && Array.isArray(schema.definition.tableConstraints)) {
2801
+ columns.push(...schema.definition.tableConstraints.filter(Boolean));
2802
+ }
2803
+ const trailingClauses = [schema.definition.withoutRowId ? "WITHOUT ROWID" : void 0, schema.definition.strict ? "STRICT" : void 0].filter(Boolean);
2804
+ const suffix = trailingClauses.length ? ` ${trailingClauses.join(" ")}` : "";
2805
+ return `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(schema.name)} (${columns.join(", ")})${suffix}`;
2806
+ }
2807
+ buildStructuredColumnDefinition(column) {
2808
+ const parts = [];
2809
+ parts.push(quoteIdentifier(column.name));
2810
+ parts.push(this.formatColumnType(column));
2811
+ if (column.name === LOCAL_PK) {
2812
+ parts.push("PRIMARY KEY");
2813
+ }
2814
+ if (column.collate) {
2815
+ parts.push(`COLLATE ${column.collate}`);
2816
+ }
2817
+ if (column.generatedAlwaysAs) {
2818
+ const storage = column.stored ? "STORED" : "VIRTUAL";
2819
+ parts.push(`GENERATED ALWAYS AS (${column.generatedAlwaysAs}) ${storage}`);
2820
+ }
2821
+ if (column.unique) {
2822
+ parts.push("UNIQUE");
2823
+ }
2824
+ if (column.default !== void 0) {
2825
+ parts.push(`DEFAULT ${this.formatDefaultValue(column.default)}`);
2826
+ }
2827
+ if (column.check) {
2828
+ parts.push(`CHECK (${column.check})`);
2829
+ }
2830
+ if (column.references) {
2831
+ parts.push(this.buildReferencesClause(column.references));
2832
+ }
2833
+ if (column.constraints?.length) {
2834
+ parts.push(...column.constraints);
2835
+ }
2836
+ return parts.filter(Boolean).join(" ");
2837
+ }
2838
+ formatColumnType(column) {
2839
+ const declaredType = column.type?.trim().toUpperCase();
2840
+ const base = !declaredType || !declaredType.length ? "NUMERIC" : declaredType === "BOOLEAN" ? "INTEGER" : declaredType;
2841
+ if (column.length && !base.includes("(")) {
2842
+ return `${base}(${column.length})`;
2843
+ }
2844
+ return base;
2845
+ }
2846
+ formatDefaultValue(value) {
2847
+ if (value === null) {
2848
+ return "NULL";
2849
+ }
2850
+ if (typeof value === "number") {
2851
+ return String(value);
2852
+ }
2853
+ if (typeof value === "boolean") {
2854
+ return value ? "1" : "0";
2855
+ }
2856
+ const escaped = String(value).replace(/'/g, "''");
2857
+ return `'${escaped}'`;
2858
+ }
2859
+ buildReferencesClause(reference) {
2860
+ if (typeof reference === "string") {
2861
+ return `REFERENCES ${reference}`;
2862
+ }
2863
+ const parts = [];
2864
+ parts.push(`REFERENCES ${quoteIdentifier(reference.table)}`);
2865
+ if (reference.column) {
2866
+ parts.push(`(${quoteIdentifier(reference.column)})`);
2867
+ }
2868
+ if (reference.match) {
2869
+ parts.push(`MATCH ${reference.match}`);
2870
+ }
2871
+ if (reference.onDelete) {
2872
+ parts.push(`ON DELETE ${reference.onDelete}`);
2873
+ }
2874
+ if (reference.onUpdate) {
2875
+ parts.push(`ON UPDATE ${reference.onUpdate}`);
2876
+ }
2877
+ return parts.join(" ");
2878
+ }
2879
+ buildIndexStatements(schema) {
2880
+ if (schema.definition.source !== "structured" || !schema.definition.indexes?.length) {
2881
+ return [];
2882
+ }
2883
+ const statements = [];
2884
+ schema.definition.indexes.forEach((index, position) => {
2885
+ if (!index.columns?.length) {
2886
+ return;
2887
+ }
2888
+ const indexName = this.generateIndexName(schema, index, position);
2889
+ const columnSegments = index.columns.map((columnName, columnIndex) => {
2890
+ const segments = [quoteIdentifier(columnName)];
2891
+ if (index.collate) {
2892
+ segments.push(`COLLATE ${index.collate}`);
2893
+ }
2894
+ const order = index.orders?.[columnIndex];
2895
+ if (order) {
2896
+ segments.push(order);
2897
+ }
2898
+ return segments.join(" ");
2899
+ });
2900
+ const whereClause = index.where ? ` WHERE ${index.where}` : "";
2901
+ statements.push(
2902
+ `CREATE ${index.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${quoteIdentifier(indexName)} ON ${quoteIdentifier(schema.name)} (${columnSegments.join(", ")})${whereClause}`
2903
+ );
2904
+ });
2905
+ return statements;
2906
+ }
2907
+ generateIndexName(schema, index, position) {
2908
+ if (index.name) {
2909
+ return index.name;
2910
+ }
2911
+ const sanitizedColumns = index.columns.map((column) => column.replace(/[^A-Za-z0-9_]/g, "_")).join("_");
2912
+ const suffix = sanitizedColumns || String(position);
2913
+ return `${schema.name}_${suffix}_idx`;
2914
+ }
2915
+ parseStructuredSchema(tableName, definition) {
2916
+ if (!definition?.columns || !Object.keys(definition.columns).length) {
2917
+ throw new Error(`SQLite schema for table '${tableName}' must define at least one column.`);
2918
+ }
2919
+ if (!definition.columns[LOCAL_PK]) {
2920
+ throw new Error(`SQLite schema for table '${tableName}' must define a column named '${LOCAL_PK}'.`);
2921
+ }
2922
+ const normalizedColumns = this.normalizeColumns(definition.columns);
2923
+ return {
2924
+ name: tableName,
2925
+ definition: {
2926
+ ...definition,
2927
+ name: tableName,
2928
+ columns: normalizedColumns,
2929
+ source: "structured"
2930
+ }
2931
+ };
2932
+ }
2933
+ normalizeColumns(columns) {
2934
+ const normalized = {};
2935
+ for (const [name, column] of Object.entries(columns)) {
2936
+ normalized[name] = {
2937
+ name,
2938
+ ...column,
2939
+ nullable: column?.nullable ?? true
2940
+ };
2941
+ }
2942
+ return normalized;
2943
+ }
2944
+ };
2945
+
2946
+ // src/storage/sqlite/SQLiteWhereClause.ts
2947
+ var SQLiteWhereClause = class {
2948
+ table;
2949
+ column;
2950
+ baseCollection;
2951
+ constructor(table, column, baseCollection) {
2952
+ this.table = table;
2953
+ this.column = column;
2954
+ this.baseCollection = baseCollection;
2955
+ }
2956
+ createCollectionWithCondition(condition) {
2957
+ const base = this.baseCollection ?? this.table.createCollection();
2958
+ return base.addSqlCondition(condition);
2959
+ }
2960
+ flattenArgs(args) {
2961
+ if (args.length === 1 && Array.isArray(args[0])) {
2962
+ return args[0];
2963
+ }
2964
+ return args;
2965
+ }
2966
+ equals(value) {
2967
+ return this.createCollectionWithCondition({
2968
+ type: "equals",
2969
+ column: this.column,
2970
+ value
2971
+ });
2972
+ }
2973
+ above(value) {
2974
+ return this.createCollectionWithCondition({
2975
+ type: "comparison",
2976
+ column: this.column,
2977
+ op: ">",
2978
+ value
2979
+ });
2980
+ }
2981
+ aboveOrEqual(value) {
2982
+ return this.createCollectionWithCondition({
2983
+ type: "comparison",
2984
+ column: this.column,
2985
+ op: ">=",
2986
+ value
2987
+ });
2988
+ }
2989
+ below(value) {
2990
+ return this.createCollectionWithCondition({
2991
+ type: "comparison",
2992
+ column: this.column,
2993
+ op: "<",
2994
+ value
2995
+ });
2996
+ }
2997
+ belowOrEqual(value) {
2998
+ return this.createCollectionWithCondition({
2999
+ type: "comparison",
3000
+ column: this.column,
3001
+ op: "<=",
3002
+ value
3003
+ });
3004
+ }
3005
+ between(lower, upper, includeLower = true, includeUpper = false) {
3006
+ return this.createCollectionWithCondition({
3007
+ type: "between",
3008
+ column: this.column,
3009
+ lower,
3010
+ upper,
3011
+ includeLower,
3012
+ includeUpper
3013
+ });
3014
+ }
3015
+ inAnyRange(ranges, options) {
3016
+ if (ranges.length === 0) {
3017
+ return this.createCollectionWithCondition({
3018
+ type: "comparison",
3019
+ column: this.column,
3020
+ op: "=",
3021
+ value: null
3022
+ }).jsFilter(() => false);
3023
+ }
3024
+ const orConditions = ranges.map(([lower, upper]) => ({
3025
+ type: "between",
3026
+ column: this.column,
3027
+ lower,
3028
+ upper,
3029
+ includeLower: options?.includeLower !== false,
3030
+ includeUpper: options?.includeUpper ?? false
3031
+ }));
3032
+ return this.createCollectionWithCondition({
3033
+ type: "or",
3034
+ conditions: orConditions
3035
+ });
3036
+ }
3037
+ startsWith(prefix) {
3038
+ const escapedPrefix = prefix.replace(/[%_\\]/g, "\\$&");
3039
+ return this.createCollectionWithCondition({
3040
+ type: "like",
3041
+ column: this.column,
3042
+ pattern: `${escapedPrefix}%`
3043
+ });
3044
+ }
3045
+ startsWithIgnoreCase(prefix) {
3046
+ const escapedPrefix = prefix.replace(/[%_\\]/g, "\\$&");
3047
+ return this.createCollectionWithCondition({
3048
+ type: "like",
3049
+ column: this.column,
3050
+ pattern: `${escapedPrefix}%`,
3051
+ caseInsensitive: true
3052
+ });
3053
+ }
3054
+ startsWithAnyOf(...args) {
3055
+ const prefixes = this.flattenArgs(args);
3056
+ if (prefixes.length === 0) {
3057
+ return this.createCollectionWithCondition({
3058
+ type: "comparison",
3059
+ column: this.column,
3060
+ op: "=",
3061
+ value: null
3062
+ }).jsFilter(() => false);
3063
+ }
3064
+ const orConditions = prefixes.map((prefix) => {
3065
+ const escapedPrefix = prefix.replace(/[%_\\]/g, "\\$&");
3066
+ return {
3067
+ type: "like",
3068
+ column: this.column,
3069
+ pattern: `${escapedPrefix}%`
3070
+ };
3071
+ });
3072
+ return this.createCollectionWithCondition({
3073
+ type: "or",
3074
+ conditions: orConditions
3075
+ });
3076
+ }
3077
+ startsWithAnyOfIgnoreCase(...args) {
3078
+ const prefixes = this.flattenArgs(args);
3079
+ if (prefixes.length === 0) {
3080
+ return this.createCollectionWithCondition({
3081
+ type: "comparison",
3082
+ column: this.column,
3083
+ op: "=",
3084
+ value: null
3085
+ }).jsFilter(() => false);
3086
+ }
3087
+ const orConditions = prefixes.map((prefix) => {
3088
+ const escapedPrefix = prefix.replace(/[%_\\]/g, "\\$&");
3089
+ return {
3090
+ type: "like",
3091
+ column: this.column,
3092
+ pattern: `${escapedPrefix}%`,
3093
+ caseInsensitive: true
3094
+ };
3095
+ });
3096
+ return this.createCollectionWithCondition({
3097
+ type: "or",
3098
+ conditions: orConditions
3099
+ });
3100
+ }
3101
+ equalsIgnoreCase(value) {
3102
+ return this.createCollectionWithCondition({
3103
+ type: "equals",
3104
+ column: this.column,
3105
+ value,
3106
+ caseInsensitive: true
3107
+ });
3108
+ }
3109
+ anyOf(...args) {
3110
+ const values = this.flattenArgs(args);
3111
+ return this.createCollectionWithCondition({
3112
+ type: "in",
3113
+ column: this.column,
3114
+ values
3115
+ });
3116
+ }
3117
+ anyOfIgnoreCase(...args) {
3118
+ const values = this.flattenArgs(args);
3119
+ return this.createCollectionWithCondition({
3120
+ type: "in",
3121
+ column: this.column,
3122
+ values,
3123
+ caseInsensitive: true
3124
+ });
3125
+ }
3126
+ noneOf(...args) {
3127
+ const values = this.flattenArgs(args);
3128
+ return this.createCollectionWithCondition({
3129
+ type: "notIn",
3130
+ column: this.column,
3131
+ values
3132
+ });
3133
+ }
3134
+ notEqual(value) {
3135
+ return this.createCollectionWithCondition({
3136
+ type: "comparison",
3137
+ column: this.column,
3138
+ op: "!=",
3139
+ value
3140
+ });
3141
+ }
3142
+ };
3143
+
3144
+ // src/storage/sqlite/SQLiteTable.ts
3145
+ var SQLiteTable = class {
3146
+ name;
3147
+ schema;
3148
+ raw;
3149
+ adapter;
3150
+ columnNames;
3151
+ booleanColumns;
3152
+ constructor(adapter, schema) {
3153
+ this.adapter = adapter;
3154
+ this.schema = schema;
3155
+ this.name = schema.name;
3156
+ this.columnNames = Object.keys(schema.definition.columns ?? {});
3157
+ this.booleanColumns = new Set(
3158
+ Object.entries(schema.definition.columns ?? {}).filter(([_, col]) => col.type?.toUpperCase() === "BOOLEAN").map(([name]) => name)
3159
+ );
3160
+ this.raw = Object.freeze({
3161
+ add: this.baseAdd.bind(this),
3162
+ put: this.basePut.bind(this),
3163
+ update: this.baseUpdate.bind(this),
3164
+ delete: this.baseDelete.bind(this),
3165
+ get: this.get.bind(this),
3166
+ bulkAdd: this.baseBulkAdd.bind(this),
3167
+ bulkPut: this.baseBulkPut.bind(this),
3168
+ bulkUpdate: this.baseBulkUpdate.bind(this),
3169
+ bulkDelete: this.baseBulkDelete.bind(this),
3170
+ clear: this.baseClear.bind(this)
3171
+ });
3172
+ }
3173
+ async add(item) {
3174
+ return this.baseAdd(item);
3175
+ }
3176
+ async put(item) {
3177
+ return this.basePut(item);
3178
+ }
3179
+ async update(key, changes) {
3180
+ return this.baseUpdate(key, changes);
3181
+ }
3182
+ async delete(key) {
3183
+ await this.baseDelete(key);
3184
+ }
3185
+ async clear() {
3186
+ await this.baseClear();
3187
+ }
3188
+ async baseClear() {
3189
+ await this.adapter.execute(`DELETE FROM ${quoteIdentifier(this.name)}`);
3190
+ }
3191
+ async get(key) {
3192
+ if (!key || typeof key !== "string") {
3193
+ return void 0;
3194
+ }
3195
+ const row = await this.fetchRow(key);
3196
+ return row ? this.cloneRecord(row) : void 0;
3197
+ }
3198
+ async toArray() {
3199
+ const entries = await this.getEntries();
3200
+ return entries.map((entry) => this.cloneRecord(entry.value));
3201
+ }
3202
+ async count() {
3203
+ const rows = await this.adapter.queryRows(`SELECT COUNT(*) as count FROM ${quoteIdentifier(this.name)}`);
3204
+ return Number(rows[0]?.count ?? 0);
3205
+ }
3206
+ async bulkAdd(items) {
3207
+ return this.baseBulkAdd(items);
3208
+ }
3209
+ async baseBulkAdd(items) {
3210
+ if (!items.length) return [];
3211
+ const columns = this.columnNames;
3212
+ const columnCount = columns.length;
3213
+ const maxParamsPerBatch = 500;
3214
+ const batchSize = Math.max(1, Math.floor(maxParamsPerBatch / columnCount));
3215
+ const allKeys = [];
3216
+ for (let i = 0; i < items.length; i += batchSize) {
3217
+ const batch = items.slice(i, i + batchSize);
3218
+ const records = batch.map((item) => this.prepareRecordForWrite(item));
3219
+ const placeholderRow = `(${columns.map(() => "?").join(", ")})`;
3220
+ const placeholders = records.map(() => placeholderRow).join(", ");
3221
+ const values = [];
3222
+ for (const record of records) {
3223
+ values.push(...this.extractColumnValues(record));
3224
+ allKeys.push(record[LOCAL_PK]);
3225
+ }
3226
+ await this.adapter.run(
3227
+ `INSERT INTO ${quoteIdentifier(this.name)} (${columns.map((c) => quoteIdentifier(c)).join(", ")}) VALUES ${placeholders}`,
3228
+ values
3229
+ );
3230
+ }
3231
+ return allKeys;
3232
+ }
3233
+ async bulkPut(items) {
3234
+ return this.baseBulkPut(items);
3235
+ }
3236
+ async baseBulkPut(items) {
3237
+ if (!items.length) return [];
3238
+ const columns = this.columnNames;
3239
+ const columnCount = columns.length;
3240
+ const maxParamsPerBatch = 500;
3241
+ const batchSize = Math.max(1, Math.floor(maxParamsPerBatch / columnCount));
3242
+ const allKeys = [];
3243
+ for (let i = 0; i < items.length; i += batchSize) {
3244
+ const batch = items.slice(i, i + batchSize);
3245
+ const records = batch.map((item) => this.prepareRecordForWrite(item));
3246
+ const placeholderRow = `(${columns.map(() => "?").join(", ")})`;
3247
+ const placeholders = records.map(() => placeholderRow).join(", ");
3248
+ const values = [];
3249
+ for (const record of records) {
3250
+ values.push(...this.extractColumnValues(record));
3251
+ allKeys.push(record[LOCAL_PK]);
3252
+ }
3253
+ await this.adapter.run(
3254
+ `INSERT OR REPLACE INTO ${quoteIdentifier(this.name)} (${columns.map((c) => quoteIdentifier(c)).join(", ")}) VALUES ${placeholders}`,
3255
+ values
3256
+ );
3257
+ }
3258
+ return allKeys;
3259
+ }
3260
+ async bulkGet(keys) {
3261
+ if (!keys.length) return [];
3262
+ const validKeys = keys.filter((k) => k && typeof k === "string");
3263
+ if (!validKeys.length) return keys.map(() => void 0);
3264
+ const selectClause = this.buildSelectClause();
3265
+ const placeholders = validKeys.map(() => "?").join(", ");
3266
+ const rows = await this.adapter.queryRows(
3267
+ `SELECT ${selectClause} FROM ${quoteIdentifier(this.name)} WHERE ${quoteIdentifier(LOCAL_PK)} IN (${placeholders})`,
3268
+ validKeys
3269
+ );
3270
+ const recordMap = /* @__PURE__ */ new Map();
3271
+ for (const row of rows) {
3272
+ const record = this.hydrateRow(row);
3273
+ recordMap.set(String(row[LOCAL_PK]), this.cloneRecord(record));
3274
+ }
3275
+ return keys.map((key) => key && typeof key === "string" ? recordMap.get(key) : void 0);
3276
+ }
3277
+ async bulkUpdate(keysAndChanges) {
3278
+ return this.baseBulkUpdate(keysAndChanges);
3279
+ }
3280
+ async baseBulkUpdate(keysAndChanges) {
3281
+ if (!keysAndChanges.length) return 0;
3282
+ let updatedCount = 0;
3283
+ for (const { key, changes } of keysAndChanges) {
3284
+ const result = await this.baseUpdate(key, changes);
3285
+ updatedCount += result;
3286
+ }
3287
+ return updatedCount;
3288
+ }
3289
+ async bulkDelete(keys) {
3290
+ await this.baseBulkDelete(keys);
3291
+ }
3292
+ async baseBulkDelete(keys) {
3293
+ if (!keys.length) return;
3294
+ const validKeys = keys.filter((k) => k && typeof k === "string");
3295
+ if (!validKeys.length) return;
3296
+ const placeholders = validKeys.map(() => "?").join(", ");
3297
+ await this.adapter.run(`DELETE FROM ${quoteIdentifier(this.name)} WHERE ${quoteIdentifier(LOCAL_PK)} IN (${placeholders})`, validKeys);
3298
+ }
3299
+ where(index) {
3300
+ return this.createWhereClause(index);
3301
+ }
3302
+ orderBy(index) {
3303
+ return this.createCollection({
3304
+ orderBy: { index, direction: "asc" }
3305
+ });
3306
+ }
3307
+ reverse() {
3308
+ return this.createCollection({ reverse: true });
3309
+ }
3310
+ offset(offset) {
3311
+ return this.createCollection({ offset });
3312
+ }
3313
+ limit(count) {
3314
+ return this.createCollection({ limit: count });
3315
+ }
3316
+ async each(callback) {
3317
+ const entries = await this.getEntries();
3318
+ for (const entry of entries) {
3319
+ await callback(this.cloneRecord(entry.value));
3320
+ }
3321
+ }
3322
+ jsFilter(predicate) {
3323
+ return this.createCollection({ jsPredicate: (record) => predicate(record) });
3324
+ }
3325
+ createCollection(stateOverrides) {
3326
+ return new SQLiteCollection2(this, stateOverrides);
3327
+ }
3328
+ createCollectionFromPredicate(predicate, template) {
3329
+ const baseState = template ? template.getState() : createDefaultState2();
3330
+ const existingPredicate = baseState.jsPredicate;
3331
+ const combinedPredicate = existingPredicate ? (record, key, index) => existingPredicate(record, key, index) && predicate(record, key, index) : predicate;
3332
+ return new SQLiteCollection2(this, {
3333
+ ...baseState,
3334
+ jsPredicate: combinedPredicate
3335
+ });
3336
+ }
3337
+ createWhereClause(column, baseCollection) {
3338
+ return new SQLiteWhereClause(this, column, baseCollection);
3339
+ }
3340
+ async *iterateEntries(options) {
3341
+ const selectClause = this.buildSelectClause();
3342
+ const chunkSize = options?.chunkSize ?? DEFAULT_STREAM_BATCH_SIZE;
3343
+ const orderClause = this.buildOrderByClause(options?.orderBy);
3344
+ let offset = 0;
3345
+ while (true) {
3346
+ const statementParts = [`SELECT ${selectClause} FROM ${quoteIdentifier(this.name)}`];
3347
+ if (orderClause) {
3348
+ statementParts.push(orderClause);
3349
+ }
3350
+ statementParts.push(`LIMIT ${chunkSize} OFFSET ${offset}`);
3351
+ const rows = await this.adapter.queryRows(statementParts.join(" "));
3352
+ if (!rows.length) {
3353
+ break;
3354
+ }
3355
+ for (const row of rows) {
3356
+ yield { key: String(row[LOCAL_PK]), value: this.hydrateRow(row) };
3357
+ }
3358
+ if (rows.length < chunkSize) {
3359
+ break;
3360
+ }
3361
+ offset += rows.length;
3362
+ }
3363
+ }
3364
+ /**
3365
+ * Execute a query with pre-built WHERE clause and parameters.
3366
+ * This is used by SQLiteCollection for native SQL performance.
3367
+ */
3368
+ async queryWithConditions(options) {
3369
+ const selectClause = this.buildSelectClause();
3370
+ const distinctKeyword = options.distinct ? "DISTINCT " : "";
3371
+ const parts = [`SELECT ${distinctKeyword}${selectClause} FROM ${quoteIdentifier(this.name)}`];
3372
+ if (options.whereClause) {
3373
+ parts.push(options.whereClause);
3374
+ }
3375
+ if (options.orderBy) {
3376
+ parts.push(this.buildOrderByClause(options.orderBy));
3377
+ }
3378
+ if (options.limit !== void 0) {
3379
+ parts.push(`LIMIT ${options.limit}`);
3380
+ }
3381
+ if (options.offset !== void 0 && options.offset > 0) {
3382
+ parts.push(`OFFSET ${options.offset}`);
3383
+ }
3384
+ const rows = await this.adapter.queryRows(parts.join(" "), options.parameters);
3385
+ return rows.map((row) => this.hydrateRow(row));
3386
+ }
3387
+ /**
3388
+ * Execute a COUNT query with pre-built WHERE clause.
3389
+ */
3390
+ async countWithConditions(options) {
3391
+ const distinctKeyword = options.distinct ? "DISTINCT " : "";
3392
+ const selectClause = this.buildSelectClause();
3393
+ const countExpr = options.distinct ? `COUNT(${distinctKeyword}${selectClause})` : "COUNT(*)";
3394
+ const parts = [`SELECT ${countExpr} as count FROM ${quoteIdentifier(this.name)}`];
3395
+ if (options.whereClause) {
3396
+ parts.push(options.whereClause);
3397
+ }
3398
+ const rows = await this.adapter.queryRows(parts.join(" "), options.parameters);
3399
+ return Number(rows[0]?.count ?? 0);
3400
+ }
3401
+ /**
3402
+ * Execute a DELETE query with pre-built WHERE clause.
3403
+ * Returns the number of deleted rows.
3404
+ */
3405
+ async deleteWithConditions(options) {
3406
+ const parts = [`DELETE FROM ${quoteIdentifier(this.name)}`];
3407
+ if (options.whereClause) {
3408
+ parts.push(options.whereClause);
3409
+ }
3410
+ const result = await this.adapter.run(parts.join(" "), options.parameters);
3411
+ return result.changes ?? 0;
3412
+ }
3413
+ /**
3414
+ * Execute an UPDATE query with pre-built WHERE clause.
3415
+ * Returns the number of updated rows.
3416
+ */
3417
+ async updateWithConditions(options) {
3418
+ const changeEntries = Object.entries(options.changes);
3419
+ if (changeEntries.length === 0) {
3420
+ return 0;
3421
+ }
3422
+ const setClauses = changeEntries.map(([column]) => `${quoteIdentifier(column)} = ?`);
3423
+ const setValues = changeEntries.map(([, value]) => this.normalizeColumnValue(value));
3424
+ const parts = [`UPDATE ${quoteIdentifier(this.name)} SET ${setClauses.join(", ")}`];
3425
+ if (options.whereClause) {
3426
+ parts.push(options.whereClause);
3427
+ }
3428
+ const result = await this.adapter.run(parts.join(" "), [...setValues, ...options.parameters]);
3429
+ return result.changes ?? 0;
3430
+ }
3431
+ /**
3432
+ * Query only primary keys with pre-built WHERE clause.
3433
+ * This is more efficient than fetching full rows when only keys are needed.
3434
+ */
3435
+ async queryKeysWithConditions(options) {
3436
+ const distinctKeyword = options.distinct ? "DISTINCT " : "";
3437
+ const parts = [`SELECT ${distinctKeyword}${quoteIdentifier(LOCAL_PK)} FROM ${quoteIdentifier(this.name)}`];
3438
+ if (options.whereClause) {
3439
+ parts.push(options.whereClause);
3440
+ }
3441
+ if (options.orderBy) {
3442
+ parts.push(this.buildOrderByClause(options.orderBy));
3443
+ }
3444
+ if (options.limit !== void 0) {
3445
+ parts.push(`LIMIT ${options.limit}`);
3446
+ }
3447
+ if (options.offset !== void 0 && options.offset > 0) {
3448
+ parts.push(`OFFSET ${options.offset}`);
3449
+ }
3450
+ const rows = await this.adapter.queryRows(parts.join(" "), options.parameters);
3451
+ return rows.map((row) => String(row[LOCAL_PK]));
3452
+ }
3453
+ async getEntries() {
3454
+ const entries = [];
3455
+ for await (const entry of this.iterateEntries()) {
3456
+ entries.push(entry);
3457
+ }
3458
+ return entries;
3459
+ }
3460
+ cloneRecord(record) {
3461
+ return cloneValue(record);
3462
+ }
3463
+ compareValues(left, right) {
3464
+ const normalizedLeft = normalizeComparableValue(left);
3465
+ const normalizedRight = normalizeComparableValue(right);
3466
+ if (normalizedLeft < normalizedRight) return -1;
3467
+ if (normalizedLeft > normalizedRight) return 1;
3468
+ return 0;
3469
+ }
3470
+ compareByIndex(left, right, index) {
3471
+ if (Array.isArray(index)) {
3472
+ for (const key of index) {
3473
+ const diff = this.compareValues(left[key], right[key]);
3474
+ if (diff !== 0) {
3475
+ return diff;
3476
+ }
3477
+ }
3478
+ return 0;
3479
+ }
3480
+ return this.compareValues(left[index], right[index]);
3481
+ }
3482
+ getIndexValue(record, index) {
3483
+ if (Array.isArray(index)) {
3484
+ return index.map((key) => record[key]);
3485
+ }
3486
+ return record[index];
3487
+ }
3488
+ async replaceRecord(record) {
3489
+ if (!this.columnNames.length) {
3490
+ return;
3491
+ }
3492
+ const assignments = this.columnNames.map((column) => `${quoteIdentifier(column)} = ?`).join(", ");
3493
+ const values = this.extractColumnValues(record);
3494
+ await this.adapter.run(`UPDATE ${quoteIdentifier(this.name)} SET ${assignments} WHERE ${quoteIdentifier(LOCAL_PK)} = ?`, [
3495
+ ...values,
3496
+ record[LOCAL_PK]
3497
+ ]);
3498
+ }
3499
+ async deleteByPrimaryKey(primaryKey) {
3500
+ await this.adapter.run(`DELETE FROM ${quoteIdentifier(this.name)} WHERE ${quoteIdentifier(LOCAL_PK)} = ?`, [primaryKey]);
3501
+ }
3502
+ async baseAdd(item) {
3503
+ const record = this.prepareRecordForWrite(item);
3504
+ const columns = this.columnNames;
3505
+ const placeholders = columns.map(() => "?").join(", ");
3506
+ const values = this.extractColumnValues(record);
3507
+ await this.adapter.run(
3508
+ `INSERT INTO ${quoteIdentifier(this.name)} (${columns.map((column) => quoteIdentifier(column)).join(", ")}) VALUES (${placeholders})`,
3509
+ values
3510
+ );
3511
+ return record[LOCAL_PK];
3512
+ }
3513
+ async basePut(item) {
3514
+ const record = this.prepareRecordForWrite(item);
3515
+ const columns = this.columnNames;
3516
+ const placeholders = columns.map(() => "?").join(", ");
3517
+ const values = this.extractColumnValues(record);
3518
+ await this.adapter.run(
3519
+ `INSERT OR REPLACE INTO ${quoteIdentifier(this.name)} (${columns.map((column) => quoteIdentifier(column)).join(", ")}) VALUES (${placeholders})`,
3520
+ values
3521
+ );
3522
+ return record[LOCAL_PK];
3523
+ }
3524
+ async baseUpdate(key, changes) {
3525
+ if (!key || typeof key !== "string") {
3526
+ return 0;
3527
+ }
3528
+ const existing = await this.fetchRow(key);
3529
+ if (!existing) {
3530
+ return 0;
3531
+ }
3532
+ const updated = { ...existing, ...changes };
3533
+ await this.replaceRecord(updated);
3534
+ return 1;
3535
+ }
3536
+ async baseDelete(key) {
3537
+ if (!key || typeof key !== "string") {
3538
+ return;
3539
+ }
3540
+ await this.deleteByPrimaryKey(key);
3541
+ }
3542
+ prepareRecordForWrite(item) {
3543
+ const clone = this.cloneRecord(item);
3544
+ const primaryValue = clone[LOCAL_PK];
3545
+ if (!primaryValue || typeof primaryValue !== "string") {
3546
+ throw new Error(`Missing required primary key field "${LOCAL_PK}" - a string value must be provided`);
3547
+ }
3548
+ return clone;
3549
+ }
3550
+ async fetchRow(primaryKey) {
3551
+ const selectClause = this.buildSelectClause();
3552
+ const rows = await this.adapter.queryRows(`SELECT ${selectClause} FROM ${quoteIdentifier(this.name)} WHERE ${quoteIdentifier(LOCAL_PK)} = ? LIMIT 1`, [
3553
+ primaryKey
3554
+ ]);
3555
+ if (!rows.length) {
3556
+ return void 0;
3557
+ }
3558
+ return this.hydrateRow(rows[0]);
3559
+ }
3560
+ buildSelectClause() {
3561
+ const dataColumns = this.columnNames.map((column) => quoteIdentifier(column));
3562
+ return dataColumns.join(", ");
3563
+ }
3564
+ hydrateRow(row) {
3565
+ const record = {};
3566
+ for (const column of this.columnNames) {
3567
+ let value = row[column];
3568
+ if (this.booleanColumns.has(column) && value !== null && value !== void 0) {
3569
+ value = value === 1 || value === true;
3570
+ }
3571
+ record[column] = value;
3572
+ }
3573
+ return record;
3574
+ }
3575
+ buildOrderByClause(orderBy) {
3576
+ const target = orderBy ?? { index: LOCAL_PK, direction: "asc" };
3577
+ const columns = Array.isArray(target.index) ? target.index : [target.index];
3578
+ const direction = target.direction.toUpperCase();
3579
+ const clause = columns.map((column) => `${quoteIdentifier(column)} ${direction}`).join(", ");
3580
+ return `ORDER BY ${clause}`;
3581
+ }
3582
+ extractColumnValues(record) {
3583
+ return this.columnNames.map((column) => this.normalizeColumnValue(record[column]));
3584
+ }
3585
+ normalizeColumnValue(value) {
3586
+ if (value === void 0) {
3587
+ return null;
3588
+ }
3589
+ if (value instanceof Date) {
3590
+ return value.toISOString();
3591
+ }
3592
+ if (typeof value === "boolean") {
3593
+ return value ? 1 : 0;
3594
+ }
3595
+ return value;
3596
+ }
3597
+ };
3598
+
3599
+ // src/storage/sqlite/SQLiteCollection.ts
3600
+ var SQLiteCollection2 = class _SQLiteCollection {
3601
+ table;
3602
+ state;
3603
+ constructor(table, state) {
3604
+ this.table = table;
3605
+ const base = createDefaultState2();
3606
+ this.state = {
3607
+ ...base,
3608
+ ...state,
3609
+ orGroups: state?.orGroups ?? base.orGroups,
3610
+ jsPredicate: state?.jsPredicate
3611
+ };
3612
+ }
3613
+ getState() {
3614
+ return { ...this.state, orGroups: this.state.orGroups.map((g) => [...g]) };
3615
+ }
3616
+ // Add a SQL-expressible condition to the current OR group
3617
+ addSqlCondition(condition) {
3618
+ const newGroups = this.state.orGroups.map((g, i) => i === this.state.orGroups.length - 1 ? [...g, condition] : g);
3619
+ return new _SQLiteCollection(this.table, {
3620
+ ...this.state,
3621
+ orGroups: newGroups
3622
+ });
3623
+ }
3624
+ replicate(overrides) {
3625
+ return new _SQLiteCollection(this.table, {
3626
+ ...this.state,
3627
+ ...overrides,
3628
+ orGroups: overrides?.orGroups ?? this.state.orGroups,
3629
+ jsPredicate: overrides?.jsPredicate !== void 0 ? overrides.jsPredicate : this.state.jsPredicate
3630
+ });
3631
+ }
3632
+ withJsPredicate(predicate) {
3633
+ const existingPredicate = this.state.jsPredicate;
3634
+ const combined = existingPredicate ? (record, key, index) => existingPredicate(record, key, index) && predicate(record, key, index) : predicate;
3635
+ return new _SQLiteCollection(this.table, {
3636
+ ...this.state,
3637
+ jsPredicate: combined
3638
+ });
3639
+ }
3640
+ hasJsPredicate() {
3641
+ return this.state.jsPredicate !== void 0;
3642
+ }
3643
+ resolveOrdering() {
3644
+ const base = this.state.orderBy ?? { index: LOCAL_PK, direction: "asc" };
3645
+ const direction = this.state.reverse ? base.direction === "asc" ? "desc" : "asc" : base.direction;
3646
+ return { index: base.index, direction };
3647
+ }
3648
+ /**
3649
+ * Execute a native SQL query with all SQL conditions.
3650
+ * If there's a JS predicate, we fetch rows without LIMIT/OFFSET in SQL
3651
+ * and apply them after JS filtering.
3652
+ */
3653
+ async executeQuery(options = {}) {
3654
+ const { whereClause, parameters } = buildWhereClause(this.state.orGroups);
3655
+ const ordering = options.orderByOverride ?? this.resolveOrdering();
3656
+ const cloneValues = options.clone !== false;
3657
+ const hasJsFilter = this.hasJsPredicate();
3658
+ const distinct = this.state.distinct;
3659
+ const sqlLimit = hasJsFilter ? void 0 : options.limitOverride ?? this.state.limit;
3660
+ const sqlOffset = hasJsFilter ? void 0 : this.state.offset;
3661
+ const rows = await this.table.queryWithConditions({
3662
+ whereClause,
3663
+ parameters,
3664
+ orderBy: ordering,
3665
+ limit: sqlLimit,
3666
+ offset: sqlOffset,
3667
+ distinct
3668
+ });
3669
+ let results = rows.map((row) => ({
3670
+ key: String(row[LOCAL_PK]),
3671
+ value: row
3672
+ }));
3673
+ if (hasJsFilter) {
3674
+ const predicate = this.state.jsPredicate;
3675
+ results = results.filter((entry, index) => predicate(entry.value, entry.key, index));
3676
+ const offset = Math.max(0, this.state.offset ?? 0);
3677
+ const limit = options.limitOverride ?? this.state.limit;
3678
+ if (offset > 0 || limit !== void 0) {
3679
+ const end = limit !== void 0 ? offset + limit : void 0;
3680
+ results = results.slice(offset, end);
3681
+ }
3682
+ }
3683
+ if (cloneValues) {
3684
+ results = results.map((entry) => ({
3685
+ key: entry.key,
3686
+ value: this.table.cloneRecord(entry.value)
3687
+ }));
3688
+ }
3689
+ return results;
3690
+ }
3691
+ async first() {
3692
+ const entries = await this.executeQuery({ limitOverride: 1 });
3693
+ return entries[0]?.value;
3694
+ }
3695
+ async last() {
3696
+ return this.replicate({ reverse: !this.state.reverse }).first();
3697
+ }
3698
+ async each(callback) {
3699
+ const entries = await this.executeQuery();
3700
+ for (const [index, entry] of entries.entries()) {
3701
+ await callback(entry.value, index);
3702
+ }
3703
+ }
3704
+ async eachKey(callback) {
3705
+ const entries = await this.executeQuery({ clone: false });
3706
+ for (const [index, entry] of entries.entries()) {
3707
+ await callback(entry.key, index);
3708
+ }
3709
+ }
3710
+ async eachPrimaryKey(callback) {
3711
+ return this.eachKey(callback);
3712
+ }
3713
+ async eachUniqueKey(callback) {
3714
+ const keys = await this.uniqueKeys();
3715
+ for (let index = 0; index < keys.length; index += 1) {
3716
+ await callback(keys[index], index);
3717
+ }
3718
+ }
3719
+ async keys() {
3720
+ if (!this.hasJsPredicate()) {
3721
+ const { whereClause, parameters } = buildWhereClause(this.state.orGroups);
3722
+ const ordering = this.resolveOrdering();
3723
+ return this.table.queryKeysWithConditions({
3724
+ whereClause,
3725
+ parameters,
3726
+ orderBy: ordering,
3727
+ limit: this.state.limit,
3728
+ offset: this.state.offset,
3729
+ distinct: this.state.distinct
3730
+ });
3731
+ }
3732
+ const entries = await this.executeQuery({ clone: false });
3733
+ return entries.map((entry) => entry.key);
3734
+ }
3735
+ async primaryKeys() {
3736
+ return this.keys();
3737
+ }
3738
+ async uniqueKeys() {
3739
+ if (!this.hasJsPredicate()) {
3740
+ const { whereClause, parameters } = buildWhereClause(this.state.orGroups);
3741
+ const ordering = this.resolveOrdering();
3742
+ return this.table.queryKeysWithConditions({
3743
+ whereClause,
3744
+ parameters,
3745
+ orderBy: ordering,
3746
+ limit: this.state.limit,
3747
+ offset: this.state.offset,
3748
+ distinct: true
3749
+ });
3750
+ }
3751
+ const keys = await this.keys();
3752
+ return [...new Set(keys)];
3753
+ }
3754
+ async count() {
3755
+ if (!this.hasJsPredicate()) {
3756
+ return this.table.countWithConditions({
3757
+ whereClause: buildWhereClause(this.state.orGroups).whereClause,
3758
+ parameters: buildWhereClause(this.state.orGroups).parameters,
3759
+ distinct: this.state.distinct
3760
+ });
3761
+ }
3762
+ const entries = await this.executeQuery({ clone: false });
3763
+ return entries.length;
3764
+ }
3765
+ async sortBy(key) {
3766
+ const entries = await this.executeQuery({
3767
+ orderByOverride: { index: key, direction: "asc" }
3768
+ });
3769
+ return entries.map((entry) => entry.value);
3770
+ }
3771
+ distinct() {
3772
+ return this.replicate({ distinct: true });
3773
+ }
3774
+ jsFilter(predicate) {
3775
+ return this.withJsPredicate((record) => predicate(cloneValue(record)));
3776
+ }
3777
+ or(index) {
3778
+ const newCollection = new _SQLiteCollection(this.table, {
3779
+ ...this.state,
3780
+ orGroups: [...this.state.orGroups, []]
3781
+ });
3782
+ return this.table.createWhereClause(index, newCollection);
3783
+ }
3784
+ clone(_props) {
3785
+ return this.replicate();
3786
+ }
3787
+ reverse() {
3788
+ return this.replicate({ reverse: !this.state.reverse });
3789
+ }
3790
+ offset(offset) {
3791
+ return this.replicate({ offset });
3792
+ }
3793
+ limit(count) {
3794
+ return this.replicate({ limit: count });
3795
+ }
3796
+ toCollection() {
3797
+ return this.replicate();
3798
+ }
3799
+ async delete() {
3800
+ if (!this.hasJsPredicate()) {
3801
+ const { whereClause, parameters } = buildWhereClause(this.state.orGroups);
3802
+ return this.table.deleteWithConditions({ whereClause, parameters });
3803
+ }
3804
+ const entries = await this.executeQuery({ clone: false });
3805
+ for (const entry of entries) {
3806
+ await this.table.deleteByPrimaryKey(entry.key);
3807
+ }
3808
+ return entries.length;
3809
+ }
3810
+ async modify(changes) {
3811
+ if (typeof changes !== "function" && !this.hasJsPredicate()) {
3812
+ const { whereClause, parameters } = buildWhereClause(this.state.orGroups);
3813
+ return this.table.updateWithConditions({ whereClause, parameters, changes });
3814
+ }
3815
+ const entries = await this.executeQuery();
3816
+ for (const entry of entries) {
3817
+ const draft = cloneValue(entry.value);
3818
+ if (typeof changes === "function") {
3819
+ await changes(draft);
3820
+ } else {
3821
+ Object.assign(draft, changes);
3822
+ }
3823
+ await this.table.replaceRecord(draft);
3824
+ }
3825
+ return entries.length;
3826
+ }
3827
+ async toArray() {
3828
+ const entries = await this.executeQuery();
3829
+ return entries.map((entry) => entry.value);
3830
+ }
3831
+ };
11
3832
  export {
12
3833
  Dync,
13
3834
  MemoryAdapter,
14
3835
  MemoryQueryContext,
15
- SQLiteAdapter,
3836
+ SQLiteAdapter2 as SQLiteAdapter,
16
3837
  SqliteQueryContext,
17
3838
  SyncAction,
18
3839
  createLocalId