memorio 5.1.1 → 5.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/global.cjs CHANGED
@@ -1095,6 +1095,123 @@ var init_store = __esm({
1095
1095
  }
1096
1096
  });
1097
1097
 
1098
+ // core/hlc.ts
1099
+ function getNodeId() {
1100
+ if (typeof globalThis === "undefined") return "node";
1101
+ try {
1102
+ if (typeof sessionStorage !== "undefined" && sessionStorage) {
1103
+ let id = sessionStorage.getItem(NODE_ID_KEY);
1104
+ if (!id) {
1105
+ id = generateNodeId();
1106
+ sessionStorage.setItem(NODE_ID_KEY, id);
1107
+ }
1108
+ return id;
1109
+ }
1110
+ } catch {
1111
+ }
1112
+ if (!globalThis.__memorioHlcNodeId) {
1113
+ globalThis.__memorioHlcNodeId = generateNodeId();
1114
+ }
1115
+ return globalThis.__memorioHlcNodeId;
1116
+ }
1117
+ function generateNodeId() {
1118
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
1119
+ return crypto.randomUUID().slice(0, 8);
1120
+ }
1121
+ return Math.random().toString(36).slice(2, 10);
1122
+ }
1123
+ function tick(_incoming) {
1124
+ const now2 = Date.now();
1125
+ const base = local.physical;
1126
+ let physical;
1127
+ let logical;
1128
+ if (now2 > base) {
1129
+ physical = now2;
1130
+ logical = 0;
1131
+ } else if (now2 < base) {
1132
+ physical = base;
1133
+ logical = local.logical + 1;
1134
+ } else {
1135
+ physical = base;
1136
+ logical = local.logical + 1;
1137
+ }
1138
+ local.physical = physical;
1139
+ local.logical = logical;
1140
+ return { physical, logical, node: local.node };
1141
+ }
1142
+ function receive(remote) {
1143
+ const now2 = Date.now();
1144
+ if (remote.physical > local.physical) {
1145
+ local.physical = remote.physical > now2 ? remote.physical : now2;
1146
+ local.logical = 1;
1147
+ } else if (remote.physical === local.physical) {
1148
+ local.logical = Math.max(local.logical, remote.logical) + 1;
1149
+ }
1150
+ local.node = getNodeId();
1151
+ return { ...local };
1152
+ }
1153
+ function compare(a, b) {
1154
+ if (a.physical !== b.physical) {
1155
+ return a.physical < b.physical ? -1 : 1;
1156
+ }
1157
+ if (a.logical !== b.logical) {
1158
+ return a.logical < b.logical ? -1 : 1;
1159
+ }
1160
+ if (a.node !== b.node) {
1161
+ return a.node < b.node ? -1 : 1;
1162
+ }
1163
+ return 0;
1164
+ }
1165
+ function happenedBefore(a, b) {
1166
+ return compare(a, b) < 0;
1167
+ }
1168
+ function serialize(hlc2) {
1169
+ return `hlc:${hlc2.physical}:${hlc2.logical}:${hlc2.node}`;
1170
+ }
1171
+ function parse(serialized) {
1172
+ if (!serialized.startsWith("hlc:")) return null;
1173
+ const parts = serialized.split(":");
1174
+ if (parts.length !== 4) return null;
1175
+ const physical = parseInt(parts[1], 10);
1176
+ const logical = parseInt(parts[2], 10);
1177
+ const node = parts[3];
1178
+ if (isNaN(physical) || isNaN(logical)) return null;
1179
+ return { physical, logical, node };
1180
+ }
1181
+ var NODE_ID_KEY, HLC_KEY, local; exports.hlc = void 0;
1182
+ var init_hlc = __esm({
1183
+ "core/hlc.ts"() {
1184
+ init_cjs_shims();
1185
+ NODE_ID_KEY = "__memorio_hlc_node";
1186
+ __name(getNodeId, "getNodeId");
1187
+ __name(generateNodeId, "generateNodeId");
1188
+ HLC_KEY = "__memorio_hlc_local";
1189
+ local = globalThis[HLC_KEY] || {
1190
+ physical: 0,
1191
+ logical: 0,
1192
+ node: getNodeId()
1193
+ };
1194
+ if (!globalThis[HLC_KEY]) {
1195
+ globalThis[HLC_KEY] = local;
1196
+ }
1197
+ __name(tick, "tick");
1198
+ __name(receive, "receive");
1199
+ __name(compare, "compare");
1200
+ __name(happenedBefore, "happenedBefore");
1201
+ __name(serialize, "serialize");
1202
+ __name(parse, "parse");
1203
+ exports.hlc = {
1204
+ tick,
1205
+ receive,
1206
+ compare,
1207
+ happenedBefore,
1208
+ serialize,
1209
+ parse,
1210
+ getNodeId
1211
+ };
1212
+ }
1213
+ });
1214
+
1098
1215
  // functions/idb/tools/db.create.ts
1099
1216
  var db_create_exports = {};
1100
1217
  var init_db_create = __esm({
@@ -1733,13 +1850,41 @@ var init_db_support2 = __esm({
1733
1850
  });
1734
1851
 
1735
1852
  // functions/sqlite/tools/persist.ts
1853
+ var persist_exports = {};
1854
+ __export(persist_exports, {
1855
+ CHECKPOINT_INTERVAL: () => CHECKPOINT_INTERVAL,
1856
+ DEBOUNCE_MS: () => DEBOUNCE_MS,
1857
+ _attachJournal: () => _attachJournal,
1858
+ _checkpoint: () => _checkpoint,
1859
+ _clearJournal: () => _clearJournal,
1860
+ _journalAppend: () => _journalAppend,
1861
+ _journalCount: () => _journalCount,
1862
+ _journalEntries: () => _journalEntries,
1863
+ _journalReplay: () => _journalReplay,
1864
+ _loadCheckpoint: () => _loadCheckpoint,
1865
+ _removeCheckpoint: () => _removeCheckpoint,
1866
+ _saveCheckpoint: () => _saveCheckpoint,
1867
+ _scheduleCheckpoint: () => _scheduleCheckpoint
1868
+ });
1736
1869
  function _ns() {
1737
1870
  const cfg = g.sqliteConfig || {};
1738
1871
  return cfg.namespace ? `ns:${cfg.namespace}` : "default";
1739
1872
  }
1740
- function _key(name) {
1873
+ function _dbKey(name) {
1741
1874
  return `memorio:sqlite:db:${_ns()}:${name}`;
1742
1875
  }
1876
+ function _journalKey(name, seq) {
1877
+ return `memorio:sqlite:journal:${_ns()}:${name}:${seq}`;
1878
+ }
1879
+ function _journalIndexKey(name) {
1880
+ return `memorio:sqlite:journal:${_ns()}:${name}:index`;
1881
+ }
1882
+ function _journalSeqKey(name) {
1883
+ return `memorio:sqlite:journal:${_ns()}:${name}:seq`;
1884
+ }
1885
+ function _opCounterKey(name) {
1886
+ return `memorio:sqlite:journal:${_ns()}:${name}:ops`;
1887
+ }
1743
1888
  function _b64encode2(buf) {
1744
1889
  const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
1745
1890
  let binary = "";
@@ -1752,35 +1897,81 @@ function _b64decode2(b64) {
1752
1897
  if (typeof Buffer !== "undefined") {
1753
1898
  return new Uint8Array(Buffer.from(b64, "base64"));
1754
1899
  }
1755
- if (typeof atob !== "function") {
1756
- throw new Error("memorio sqlite: no base64 decoder available");
1900
+ if (typeof atob === "function") {
1901
+ const binary = atob(b64);
1902
+ const len = binary.length;
1903
+ const out = new Uint8Array(len);
1904
+ for (let i = 0; i < len; i++) out[i] = binary.charCodeAt(i);
1905
+ return out;
1757
1906
  }
1758
- const binary = atob(b64);
1759
- const len = binary.length;
1760
- const out = new Uint8Array(len);
1761
- for (let i = 0; i < len; i++) out[i] = binary.charCodeAt(i);
1762
- return out;
1907
+ throw new Error("memorio sqlite: no base64 decoder available");
1763
1908
  }
1764
- function saveSnapshot(name) {
1765
- return new Promise((resolve) => {
1766
- const db = g.__sqliteDbs && g.__sqliteDbs[name];
1767
- if (!db || typeof db.export !== "function") {
1768
- resolve(false);
1769
- return;
1770
- }
1771
- try {
1772
- const blob = db.export();
1773
- exports.store.set(_key(name), _b64encode2(blob));
1774
- message_default(`Memorio SQLite: persisted '${name}' to store`);
1775
- resolve(true);
1776
- } catch (err) {
1777
- console.warn("Memorio SQLite: persist snapshot failed", err);
1778
- resolve(false);
1779
- }
1909
+ function _nextSeq(name) {
1910
+ const seq = (exports.store.get(_journalSeqKey(name)) || 0) + 1;
1911
+ exports.store.set(_journalSeqKey(name), seq);
1912
+ return seq;
1913
+ }
1914
+ function _journalAppend(name, sql, params) {
1915
+ const seq = _nextSeq(name);
1916
+ const entry = {
1917
+ hlc: exports.hlc.serialize(exports.hlc.tick()),
1918
+ sql,
1919
+ params: params || [],
1920
+ seq,
1921
+ ts: Date.now()
1922
+ };
1923
+ exports.store.set(_journalKey(name, seq), entry);
1924
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1925
+ idx.push(seq);
1926
+ exports.store.set(_journalIndexKey(name), idx);
1927
+ return seq;
1928
+ }
1929
+ function _journalEntries(name) {
1930
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1931
+ const entries = [];
1932
+ for (const seq of idx) {
1933
+ const raw = exports.store.get(_journalKey(name, seq));
1934
+ if (raw && typeof raw === "object" && raw.hlc) entries.push(raw);
1935
+ }
1936
+ entries.sort((a, b) => {
1937
+ const ha = exports.hlc.parse(a.hlc);
1938
+ const hb = exports.hlc.parse(b.hlc);
1939
+ if (ha && hb) return exports.hlc.compare(ha, hb);
1940
+ return a.seq - b.seq;
1780
1941
  });
1942
+ return entries;
1943
+ }
1944
+ function _journalCount(name) {
1945
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1946
+ return idx.length;
1947
+ }
1948
+ function _clearJournal(name) {
1949
+ const idx = exports.store.get(_journalIndexKey(name)) || [];
1950
+ for (const seq of idx) {
1951
+ exports.store.remove(_journalKey(name, seq));
1952
+ }
1953
+ exports.store.remove(_journalIndexKey(name));
1954
+ exports.store.remove(_journalSeqKey(name));
1955
+ exports.store.remove(_opCounterKey(name));
1956
+ }
1957
+ async function _saveCheckpoint(name) {
1958
+ const db = g.__sqliteDbs && g.__sqliteDbs[name];
1959
+ if (!db || typeof db.export !== "function") return false;
1960
+ try {
1961
+ const blob = db.export();
1962
+ exports.store.set(_dbKey(name), _b64encode2(blob));
1963
+ message_default(`Memorio SQLite: checkpoint saved for '${name}'`);
1964
+ return true;
1965
+ } catch (err) {
1966
+ if (db && db.version === "bun:sqlite") {
1967
+ return false;
1968
+ }
1969
+ console.warn("Memorio SQLite: checkpoint failed", err);
1970
+ return false;
1971
+ }
1781
1972
  }
1782
- function loadSnapshot(name) {
1783
- const b64 = exports.store.get(_key(name));
1973
+ function _loadCheckpoint(name) {
1974
+ const b64 = exports.store.get(_dbKey(name));
1784
1975
  if (!b64) return null;
1785
1976
  try {
1786
1977
  return _b64decode2(b64);
@@ -1788,48 +1979,108 @@ function loadSnapshot(name) {
1788
1979
  return null;
1789
1980
  }
1790
1981
  }
1791
- function removeSnapshot(name) {
1792
- exports.store.remove(_key(name));
1982
+ function _removeCheckpoint(name) {
1983
+ exports.store.remove(_dbKey(name));
1793
1984
  }
1794
- function attachAutoExport(name, db) {
1795
- if (!db || typeof db.updateHook !== "function") return;
1796
- _persistDbs[name] = true;
1797
- try {
1798
- db.updateHook(() => {
1799
- if (_exportTimers[name]) clearTimeout(_exportTimers[name]);
1800
- _exportTimers[name] = setTimeout(() => {
1801
- _exportTimers[name] = null;
1802
- void saveSnapshot(name);
1803
- }, 250);
1804
- });
1805
- } catch (err) {
1806
- console.warn("Memorio SQLite: could not attach updateHook", err);
1985
+ async function _journalReplay(name, db) {
1986
+ const entries = _journalEntries(name);
1987
+ if (!entries.length) return 0;
1988
+ let replayed = 0;
1989
+ for (const entry of entries) {
1990
+ try {
1991
+ db.run(entry.sql, entry.params || []);
1992
+ replayed++;
1993
+ } catch (err) {
1994
+ console.warn(`Memorio SQLite: failed to replay journal entry ${entry.seq} for '${name}'`, err);
1995
+ }
1996
+ }
1997
+ message_default(`Memorio SQLite: replayed ${replayed} journal entries for '${name}'`);
1998
+ return replayed;
1999
+ }
2000
+ function _scheduleCheckpoint(name) {
2001
+ if (_checkpointTimers[name]) clearTimeout(_checkpointTimers[name]);
2002
+ _checkpointTimers[name] = setTimeout(() => {
2003
+ _checkpointTimers[name] = null;
2004
+ void _checkpoint(name);
2005
+ }, DEBOUNCE_MS);
2006
+ }
2007
+ async function _checkpoint(name) {
2008
+ if (_checkpointTimers[name]) {
2009
+ clearTimeout(_checkpointTimers[name]);
2010
+ _checkpointTimers[name] = null;
2011
+ }
2012
+ const saved = await _saveCheckpoint(name);
2013
+ if (saved) _clearJournal(name);
2014
+ return saved;
2015
+ }
2016
+ function _attachJournal(name, db) {
2017
+ if (!db || typeof db.run !== "function") return;
2018
+ if (db.__memorioJournalAttached) return;
2019
+ db.__memorioJournalAttached = true;
2020
+ const originalRun = db.run.bind(db);
2021
+ db.run = function(sql, params) {
2022
+ const paramArr = Array.isArray(params) ? params : params !== void 0 ? [params] : [];
2023
+ _journalAppend(name, sql, paramArr);
2024
+ const ops = (exports.store.get(_opCounterKey(name)) || 0) + 1;
2025
+ exports.store.set(_opCounterKey(name), ops);
2026
+ if (ops >= CHECKPOINT_INTERVAL) {
2027
+ exports.store.set(_opCounterKey(name), 0);
2028
+ void _checkpoint(name);
2029
+ } else {
2030
+ _scheduleCheckpoint(name);
2031
+ }
2032
+ return originalRun(sql, params);
2033
+ };
2034
+ if (typeof db.updateHook === "function") {
2035
+ try {
2036
+ db.updateHook(() => {
2037
+ _scheduleCheckpoint(name);
2038
+ });
2039
+ } catch (err) {
2040
+ console.warn("Memorio SQLite: could not attach updateHook", err);
2041
+ }
1807
2042
  }
1808
2043
  }
1809
- var g, _persistDbs, _exportTimers;
2044
+ var g, CHECKPOINT_INTERVAL, DEBOUNCE_MS, _checkpointTimers;
1810
2045
  var init_persist = __esm({
1811
2046
  "functions/sqlite/tools/persist.ts"() {
1812
2047
  init_cjs_shims();
1813
2048
  init_sqlite();
1814
2049
  init_store();
2050
+ init_hlc();
1815
2051
  init_message();
1816
2052
  g = globalThis;
1817
- _persistDbs = {};
1818
- _exportTimers = {};
2053
+ CHECKPOINT_INTERVAL = 50;
2054
+ DEBOUNCE_MS = 250;
2055
+ _checkpointTimers = {};
1819
2056
  __name(_ns, "_ns");
1820
- __name(_key, "_key");
2057
+ __name(_dbKey, "_dbKey");
2058
+ __name(_journalKey, "_journalKey");
2059
+ __name(_journalIndexKey, "_journalIndexKey");
2060
+ __name(_journalSeqKey, "_journalSeqKey");
2061
+ __name(_opCounterKey, "_opCounterKey");
1821
2062
  __name(_b64encode2, "_b64encode");
1822
2063
  __name(_b64decode2, "_b64decode");
1823
- __name(saveSnapshot, "saveSnapshot");
1824
- __name(loadSnapshot, "loadSnapshot");
1825
- __name(removeSnapshot, "removeSnapshot");
1826
- __name(attachAutoExport, "attachAutoExport");
2064
+ __name(_nextSeq, "_nextSeq");
2065
+ __name(_journalAppend, "_journalAppend");
2066
+ __name(_journalEntries, "_journalEntries");
2067
+ __name(_journalCount, "_journalCount");
2068
+ __name(_clearJournal, "_clearJournal");
2069
+ __name(_saveCheckpoint, "_saveCheckpoint");
2070
+ __name(_loadCheckpoint, "_loadCheckpoint");
2071
+ __name(_removeCheckpoint, "_removeCheckpoint");
2072
+ __name(_journalReplay, "_journalReplay");
2073
+ __name(_scheduleCheckpoint, "_scheduleCheckpoint");
2074
+ __name(_checkpoint, "_checkpoint");
2075
+ __name(_attachJournal, "_attachJournal");
1827
2076
  exports.sqlite.db.persist = async (name = "memorio") => {
1828
- return saveSnapshot(name);
2077
+ return _checkpoint(name);
2078
+ };
2079
+ exports.sqlite.db.flush = async (name = "memorio") => {
2080
+ return _checkpoint(name);
1829
2081
  };
1830
2082
  exports.sqlite.db.download = async (name = "memorio", filename = `${name}.sqlite`) => {
1831
- const g3 = globalThis;
1832
- const db = g3.__sqliteDbs && g3.__sqliteDbs[name];
2083
+ const db = g.__sqliteDbs && g.__sqliteDbs[name];
1833
2084
  if (!db) {
1834
2085
  console.warn(`Memorio SQLite: cannot download '${name}' - database not found. Create it with sqlite.db.create('${name}').`);
1835
2086
  return false;
@@ -1842,18 +2093,18 @@ var init_persist = __esm({
1842
2093
  return false;
1843
2094
  }
1844
2095
  if (!blob) return false;
1845
- if (typeof g3.document === "undefined" || typeof g3.Blob === "undefined") {
2096
+ if (typeof g.document === "undefined" || typeof g.Blob === "undefined") {
1846
2097
  console.warn("Memorio SQLite: sqlite.db.download() requires a browser environment.");
1847
2098
  return false;
1848
2099
  }
1849
- const URL2 = g3.URL || g3.webkitURL;
2100
+ const URL2 = g.URL || g.webkitURL;
1850
2101
  if (!URL2 || typeof URL2.createObjectURL !== "function") return false;
1851
2102
  const objectUrl = URL2.createObjectURL(new Blob([blob], { type: "application/x-sqlite3" }));
1852
- const a = g3.document.createElement("a");
2103
+ const a = g.document.createElement("a");
1853
2104
  a.style.display = "none";
1854
2105
  a.href = objectUrl;
1855
2106
  a.download = filename;
1856
- g3.document.body.appendChild(a);
2107
+ g.document.body.appendChild(a);
1857
2108
  a.click();
1858
2109
  setTimeout(() => {
1859
2110
  try {
@@ -1868,7 +2119,7 @@ var init_persist = __esm({
1868
2119
  const db = g.__sqliteDbs && g.__sqliteDbs[name];
1869
2120
  if (db && typeof db.close === "function") {
1870
2121
  try {
1871
- await saveSnapshot(name);
2122
+ await _checkpoint(name);
1872
2123
  } catch (_) {
1873
2124
  }
1874
2125
  try {
@@ -1882,15 +2133,22 @@ var init_persist = __esm({
1882
2133
  const idx = g.sqlbases.findIndex((x) => x && x.name === name);
1883
2134
  if (idx > -1) g.sqlbases.splice(idx, 1);
1884
2135
  }
1885
- delete _persistDbs[name];
1886
- if (_exportTimers[name]) {
1887
- clearTimeout(_exportTimers[name]);
1888
- _exportTimers[name] = null;
2136
+ if (_checkpointTimers[name]) {
2137
+ clearTimeout(_checkpointTimers[name]);
2138
+ _checkpointTimers[name] = null;
1889
2139
  }
1890
- removeSnapshot(name);
1891
2140
  };
1892
- exports.sqlite.db.loadSnapshot = loadSnapshot;
1893
- exports.sqlite.db.saveSnapshot = saveSnapshot;
2141
+ exports.sqlite.db.loadSnapshot = _loadCheckpoint;
2142
+ exports.sqlite.db.saveSnapshot = _saveCheckpoint;
2143
+ exports.sqlite.db.removeSnapshot = _removeCheckpoint;
2144
+ exports.sqlite.db.journal = {
2145
+ append: _journalAppend,
2146
+ entries: _journalEntries,
2147
+ count: _journalCount,
2148
+ clear: _clearJournal,
2149
+ replay: _journalReplay,
2150
+ checkpoint: _checkpoint
2151
+ };
1894
2152
  }
1895
2153
  });
1896
2154
 
@@ -1908,7 +2166,7 @@ var init_db_create2 = __esm({
1908
2166
  const persistence = !!(opts && opts.persistence) || !!(g3.sqliteConfig && g3.sqliteConfig.persistence);
1909
2167
  let data;
1910
2168
  if (persistence && !opts.data) {
1911
- const restored = loadSnapshot(name);
2169
+ const restored = _loadCheckpoint(name);
1912
2170
  if (restored) data = restored;
1913
2171
  }
1914
2172
  const useData = opts && opts.data || data;
@@ -1930,7 +2188,13 @@ var init_db_create2 = __esm({
1930
2188
  } else {
1931
2189
  g3.sqlbases.push({ name, db, persistence: createOpts.persistence });
1932
2190
  }
1933
- if (persistence) attachAutoExport(name, db);
2191
+ if (persistence && !opts.data) {
2192
+ _attachJournal(name, db);
2193
+ const replayed = await _journalReplay(name, db);
2194
+ if (replayed > 0) {
2195
+ message_default(`Memorio SQLite: replayed ${replayed} journal entries for '${name}'`);
2196
+ }
2197
+ }
1934
2198
  return db;
1935
2199
  };
1936
2200
  }
@@ -1961,9 +2225,14 @@ var init_db_delete2 = __esm({
1961
2225
  init_cjs_shims();
1962
2226
  init_sqlite();
1963
2227
  init_message();
1964
- exports.sqlite.db.delete = (name) => {
2228
+ init_persist();
2229
+ exports.sqlite.db.delete = async (name) => {
1965
2230
  const dbs = globalThis.__sqliteDbs;
1966
2231
  if (!dbs || !dbs[name]) return false;
2232
+ try {
2233
+ await _checkpoint(name);
2234
+ } catch (_) {
2235
+ }
1967
2236
  try {
1968
2237
  dbs[name].close();
1969
2238
  } catch (_) {
@@ -1971,6 +2240,7 @@ var init_db_delete2 = __esm({
1971
2240
  delete dbs[name];
1972
2241
  const g3 = globalThis;
1973
2242
  if (g3.sqlbases) g3.sqlbases = g3.sqlbases.filter((x) => x && x.name !== name);
2243
+ _removeCheckpoint(name);
1974
2244
  message_default(`Memorio SQLite: database '${name}' deleted`);
1975
2245
  return true;
1976
2246
  };
@@ -2115,7 +2385,7 @@ var init_data_get2 = __esm({
2115
2385
  });
2116
2386
 
2117
2387
  // functions/sqlite/index.ts
2118
- var _hasSqlJs, _hasBunSqlite; exports.sqlite = void 0;
2388
+ var _hasSqlJs, _hasBunSqlite; exports.sqlite = void 0; var _toolsLoaded;
2119
2389
  var init_sqlite = __esm({
2120
2390
  "functions/sqlite/index.ts"() {
2121
2391
  init_cjs_shims();
@@ -2128,6 +2398,7 @@ var init_sqlite = __esm({
2128
2398
  query: {},
2129
2399
  data: {}
2130
2400
  };
2401
+ _toolsLoaded = Promise.resolve();
2131
2402
  exports.sqlite.config = (opts) => {
2132
2403
  const g3 = globalThis;
2133
2404
  g3.sqliteConfig = { ...g3.sqliteConfig, ...opts };
@@ -2142,15 +2413,19 @@ var init_sqlite = __esm({
2142
2413
  get: /* @__PURE__ */ __name(() => {
2143
2414
  const g3 = globalThis;
2144
2415
  if (!g3.sqliteReady) {
2145
- g3.sqliteReady = typeof exports.sqlite.db.getSQL === "function" ? exports.sqlite.db.getSQL().then(() => {
2416
+ g3.sqliteReady = _toolsLoaded.then(() => {
2417
+ if (typeof exports.sqlite.db.getSQL !== "function") return;
2418
+ return exports.sqlite.db.getSQL().then(() => {
2419
+ }).catch(() => {
2420
+ });
2146
2421
  }).catch(() => {
2147
- }) : Promise.resolve();
2422
+ });
2148
2423
  }
2149
2424
  return g3.sqliteReady;
2150
2425
  }, "get")
2151
2426
  });
2152
2427
  if (_hasSqlJs || _hasBunSqlite) {
2153
- (async () => {
2428
+ _toolsLoaded = (async () => {
2154
2429
  Object.defineProperty(exports.sqlite, "db", { value: {}, writable: false, configurable: true, enumerable: true });
2155
2430
  Object.defineProperty(exports.sqlite, "query", { value: {}, writable: false, configurable: true, enumerable: true });
2156
2431
  Object.defineProperty(exports.sqlite, "data", { value: {}, writable: false, configurable: true, enumerable: true });
@@ -2162,6 +2437,7 @@ var init_sqlite = __esm({
2162
2437
  });
2163
2438
  await Promise.all([
2164
2439
  Promise.resolve().then(() => (init_db_support2(), db_support_exports2)),
2440
+ Promise.resolve().then(() => (init_persist(), persist_exports)),
2165
2441
  Promise.resolve().then(() => (init_db_create2(), db_create_exports2)),
2166
2442
  Promise.resolve().then(() => (init_db_get(), db_get_exports)),
2167
2443
  Promise.resolve().then(() => (init_db_delete2(), db_delete_exports2)),
@@ -2385,133 +2661,23 @@ init_env();
2385
2661
  // core/mutation/engine.ts
2386
2662
  init_cjs_shims();
2387
2663
  init_internal();
2388
-
2389
- // core/hlc.ts
2390
- init_cjs_shims();
2391
- var NODE_ID_KEY = "__memorio_hlc_node";
2392
- function getNodeId() {
2393
- if (typeof globalThis === "undefined") return "node";
2394
- try {
2395
- if (typeof sessionStorage !== "undefined" && sessionStorage) {
2396
- let id = sessionStorage.getItem(NODE_ID_KEY);
2397
- if (!id) {
2398
- id = generateNodeId();
2399
- sessionStorage.setItem(NODE_ID_KEY, id);
2400
- }
2401
- return id;
2402
- }
2403
- } catch {
2404
- }
2405
- if (!globalThis.__memorioHlcNodeId) {
2406
- globalThis.__memorioHlcNodeId = generateNodeId();
2407
- }
2408
- return globalThis.__memorioHlcNodeId;
2409
- }
2410
- __name(getNodeId, "getNodeId");
2411
- function generateNodeId() {
2412
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
2413
- return crypto.randomUUID().slice(0, 8);
2414
- }
2415
- return Math.random().toString(36).slice(2, 10);
2416
- }
2417
- __name(generateNodeId, "generateNodeId");
2418
- var HLC_KEY = "__memorio_hlc_local";
2419
- var local = globalThis[HLC_KEY] || {
2420
- physical: 0,
2421
- logical: 0,
2422
- node: getNodeId()
2423
- };
2424
- if (!globalThis[HLC_KEY]) {
2425
- globalThis[HLC_KEY] = local;
2426
- }
2427
- function tick(_incoming) {
2428
- const now2 = Date.now();
2429
- const base = local.physical;
2430
- let physical;
2431
- let logical;
2432
- if (now2 > base) {
2433
- physical = now2;
2434
- logical = 0;
2435
- } else if (now2 < base) {
2436
- physical = base;
2437
- logical = local.logical + 1;
2438
- } else {
2439
- physical = base;
2440
- logical = local.logical + 1;
2441
- }
2442
- local.physical = physical;
2443
- local.logical = logical;
2444
- return { physical, logical, node: local.node };
2445
- }
2446
- __name(tick, "tick");
2447
- function receive(remote) {
2448
- const now2 = Date.now();
2449
- if (remote.physical > local.physical) {
2450
- local.physical = remote.physical > now2 ? remote.physical : now2;
2451
- local.logical = 1;
2452
- } else if (remote.physical === local.physical) {
2453
- local.logical = Math.max(local.logical, remote.logical) + 1;
2454
- }
2455
- local.node = getNodeId();
2456
- return { ...local };
2457
- }
2458
- __name(receive, "receive");
2459
- function compare(a, b) {
2460
- if (a.physical !== b.physical) {
2461
- return a.physical < b.physical ? -1 : 1;
2462
- }
2463
- if (a.logical !== b.logical) {
2464
- return a.logical < b.logical ? -1 : 1;
2465
- }
2466
- if (a.node !== b.node) {
2467
- return a.node < b.node ? -1 : 1;
2468
- }
2469
- return 0;
2470
- }
2471
- __name(compare, "compare");
2472
- function happenedBefore(a, b) {
2473
- return compare(a, b) < 0;
2474
- }
2475
- __name(happenedBefore, "happenedBefore");
2476
- function serialize(hlc2) {
2477
- return `hlc:${hlc2.physical}:${hlc2.logical}:${hlc2.node}`;
2478
- }
2479
- __name(serialize, "serialize");
2480
- function parse(serialized) {
2481
- if (!serialized.startsWith("hlc:")) return null;
2482
- const parts = serialized.split(":");
2483
- if (parts.length !== 4) return null;
2484
- const physical = parseInt(parts[1], 10);
2485
- const logical = parseInt(parts[2], 10);
2486
- const node = parts[3];
2487
- if (isNaN(physical) || isNaN(logical)) return null;
2488
- return { physical, logical, node };
2489
- }
2490
- __name(parse, "parse");
2491
- var hlc = {
2492
- tick,
2493
- receive,
2494
- compare,
2495
- happenedBefore,
2496
- serialize,
2497
- parse,
2498
- getNodeId
2499
- };
2664
+ init_hlc();
2500
2665
 
2501
2666
  // core/mutation/id.ts
2502
2667
  init_cjs_shims();
2668
+ init_hlc();
2503
2669
  function generateMutationId() {
2504
- const now2 = hlc.tick();
2670
+ const now2 = exports.hlc.tick();
2505
2671
  return "m_" + encodeHLC(now2);
2506
2672
  }
2507
2673
  __name(generateMutationId, "generateMutationId");
2508
2674
  function generateTransactionId() {
2509
- const now2 = hlc.tick();
2675
+ const now2 = exports.hlc.tick();
2510
2676
  return "tx_" + encodeHLC(now2);
2511
2677
  }
2512
2678
  __name(generateTransactionId, "generateTransactionId");
2513
2679
  function generateCommitId() {
2514
- const now2 = hlc.tick();
2680
+ const now2 = exports.hlc.tick();
2515
2681
  return "c_" + encodeHLC(now2);
2516
2682
  }
2517
2683
  __name(generateCommitId, "generateCommitId");
@@ -2591,6 +2757,7 @@ __name(mergePatches, "mergePatches");
2591
2757
  // core/mutation/transaction.ts
2592
2758
  init_cjs_shims();
2593
2759
  init_internal();
2760
+ init_hlc();
2594
2761
  var TX_REGISTRY_KEY = "__memorio_transaction_registry__";
2595
2762
  var registry = globalThis[TX_REGISTRY_KEY] || /* @__PURE__ */ new Map();
2596
2763
  if (!globalThis[TX_REGISTRY_KEY]) {
@@ -2617,7 +2784,7 @@ function beginTransaction(source, message2, metadata) {
2617
2784
  const id = generateTransactionId();
2618
2785
  const ctx = {
2619
2786
  id,
2620
- startedAt: hlc.serialize(hlc.tick()),
2787
+ startedAt: exports.hlc.serialize(exports.hlc.tick()),
2621
2788
  source,
2622
2789
  message: message2,
2623
2790
  metadata,
@@ -2645,7 +2812,7 @@ function commitTransaction() {
2645
2812
  const ctx = registry.get(txId);
2646
2813
  if (!ctx || !ctx.active) return null;
2647
2814
  ctx.active = false;
2648
- ctx.committedAt = hlc.serialize(hlc.tick());
2815
+ ctx.committedAt = exports.hlc.serialize(exports.hlc.tick());
2649
2816
  const tx = {
2650
2817
  id: ctx.id,
2651
2818
  mutations: ctx.mutations,
@@ -2725,7 +2892,7 @@ function abortTransaction() {
2725
2892
  }
2726
2893
  }
2727
2894
  ctx.active = false;
2728
- ctx.committedAt = hlc.serialize(hlc.tick());
2895
+ ctx.committedAt = exports.hlc.serialize(exports.hlc.tick());
2729
2896
  const tx = {
2730
2897
  id: ctx.id,
2731
2898
  mutations: ctx.mutations,
@@ -2783,11 +2950,11 @@ __name(registerMutationInTransaction, "registerMutationInTransaction");
2783
2950
 
2784
2951
  // core/mutation/engine.ts
2785
2952
  function currentTimestamp() {
2786
- return hlc.serialize(hlc.tick());
2953
+ return exports.hlc.serialize(exports.hlc.tick());
2787
2954
  }
2788
2955
  __name(currentTimestamp, "currentTimestamp");
2789
2956
  function createMutation(path, operation, before2, after2, options) {
2790
- const now2 = hlc.tick();
2957
+ const now2 = exports.hlc.tick();
2791
2958
  const mutation = {
2792
2959
  id: generateMutationId(),
2793
2960
  path,
@@ -2795,7 +2962,7 @@ function createMutation(path, operation, before2, after2, options) {
2795
2962
  after: after2,
2796
2963
  before: before2,
2797
2964
  timestamp: now2.physical,
2798
- hlc: hlc.serialize(now2),
2965
+ hlc: exports.hlc.serialize(now2),
2799
2966
  context: options?.context || exports.internal.currentContext || void 0,
2800
2967
  source: options?.source,
2801
2968
  transactionId: options?.transactionId || (operation !== "length" ? tagForTransaction() : void 0),
@@ -4202,8 +4369,8 @@ function isAuditActive() {
4202
4369
  return _auditLogger !== null;
4203
4370
  }
4204
4371
  __name(isAuditActive, "isAuditActive");
4205
- function setAuditLogger(logger3) {
4206
- _auditLogger = logger3;
4372
+ function setAuditLogger(logger2) {
4373
+ _auditLogger = logger2;
4207
4374
  }
4208
4375
  __name(setAuditLogger, "setAuditLogger");
4209
4376
  function logAudit(entry) {
@@ -4446,6 +4613,9 @@ var logger = {
4446
4613
  exportLogs
4447
4614
  };
4448
4615
 
4616
+ // index.ts
4617
+ init_hlc();
4618
+
4449
4619
  // core/fractional.ts
4450
4620
  init_cjs_shims();
4451
4621
  function generateBetween(left, right, minChars = 2) {
@@ -4638,7 +4808,7 @@ init_internal();
4638
4808
 
4639
4809
  // package.json
4640
4810
  var package_default = {
4641
- version: "5.1.1"};
4811
+ version: "5.1.3"};
4642
4812
 
4643
4813
  // core/global.ts
4644
4814
  init_env();
@@ -4659,10 +4829,12 @@ __name(typed, "typed");
4659
4829
  init_cjs_shims();
4660
4830
  init_store();
4661
4831
  init_idb();
4832
+ init_hlc();
4662
4833
  init_env();
4663
4834
 
4664
4835
  // functions/memory/journal.ts
4665
4836
  init_cjs_shims();
4837
+ init_hlc();
4666
4838
  init_env();
4667
4839
  init_store();
4668
4840
  var g2 = globalThis;
@@ -4700,7 +4872,7 @@ var journal = {
4700
4872
  updatedAt: entry.updatedAt || Date.now(),
4701
4873
  version: entry.version || 1,
4702
4874
  sync: "pending",
4703
- hlc: entry.hlc || hlc.serialize(hlc.tick())
4875
+ hlc: entry.hlc || exports.hlc.serialize(exports.hlc.tick())
4704
4876
  };
4705
4877
  const key = `${STORE_PREFIX(ns)}${row.id}`;
4706
4878
  exports.store.set(key, row);
@@ -4722,9 +4894,9 @@ var journal = {
4722
4894
  }
4723
4895
  out.sort((a, b) => {
4724
4896
  if (a.hlc && b.hlc) {
4725
- const ha = hlc.parse(a.hlc);
4726
- const hb = hlc.parse(b.hlc);
4727
- if (ha && hb) return hlc.compare(ha, hb);
4897
+ const ha = exports.hlc.parse(a.hlc);
4898
+ const hb = exports.hlc.parse(b.hlc);
4899
+ if (ha && hb) return exports.hlc.compare(ha, hb);
4728
4900
  }
4729
4901
  return (a.updatedAt || 0) - (b.updatedAt || 0);
4730
4902
  });
@@ -4800,15 +4972,15 @@ var journal = {
4800
4972
  const remote = await provider.pull(since);
4801
4973
  for (const e of remote || []) {
4802
4974
  if (e.hlc) {
4803
- const parsed = hlc.parse(e.hlc);
4804
- if (parsed) hlc.receive(parsed);
4975
+ const parsed = exports.hlc.parse(e.hlc);
4976
+ if (parsed) exports.hlc.receive(parsed);
4805
4977
  }
4806
4978
  const localEntry = await this.get(e.id);
4807
4979
  if (localEntry && e.hlc && localEntry.hlc) {
4808
- const ha = hlc.parse(localEntry.hlc);
4809
- const hb = hlc.parse(e.hlc);
4980
+ const ha = exports.hlc.parse(localEntry.hlc);
4981
+ const hb = exports.hlc.parse(e.hlc);
4810
4982
  if (ha && hb) {
4811
- const cmp = hlc.compare(ha, hb);
4983
+ const cmp = exports.hlc.compare(ha, hb);
4812
4984
  if (cmp === 0) {
4813
4985
  const hasResolver = typeof provider.resolveConflict === "function";
4814
4986
  const resolution = hasResolver ? await provider.resolveConflict(localEntry, e) : "remote";
@@ -5150,7 +5322,7 @@ var memory = {
5150
5322
  version: existing ? existing.version ? existing.version + 1 : 1 : 1,
5151
5323
  sync: isSyncEnabled2() ? "pending" : void 0,
5152
5324
  supersededId: existing ? existing.id : null,
5153
- hlc: hlc.serialize(hlc.tick())
5325
+ hlc: exports.hlc.serialize(exports.hlc.tick())
5154
5326
  };
5155
5327
  await saveToScope(entry);
5156
5328
  await recordJournal(entry, "remember");
@@ -5203,7 +5375,7 @@ var memory = {
5203
5375
  updatedAt: now(),
5204
5376
  version: 1,
5205
5377
  sync: isSyncEnabled2() ? "pending" : void 0,
5206
- hlc: hlc.serialize(hlc.tick())
5378
+ hlc: exports.hlc.serialize(exports.hlc.tick())
5207
5379
  };
5208
5380
  await recordJournal(tombstone2, "delete");
5209
5381
  return;
@@ -5217,7 +5389,7 @@ var memory = {
5217
5389
  updatedAt: now(),
5218
5390
  version: (entry.version ? entry.version : 0) + 1,
5219
5391
  sync: isSyncEnabled2() ? "pending" : void 0,
5220
- hlc: hlc.serialize(hlc.tick())
5392
+ hlc: exports.hlc.serialize(exports.hlc.tick())
5221
5393
  };
5222
5394
  await recordJournal(tombstone, "delete");
5223
5395
  dispatch.set("memorio:memory:forgotten", { key });
@@ -5246,7 +5418,7 @@ var memory = {
5246
5418
  updatedAt: now(),
5247
5419
  version: (existing.version ? existing.version : 0) + 1,
5248
5420
  sync: isSyncEnabled2() ? "pending" : void 0,
5249
- hlc: hlc.serialize(hlc.tick()),
5421
+ hlc: exports.hlc.serialize(exports.hlc.tick()),
5250
5422
  ...opts.scope ? { scope: opts.scope } : {},
5251
5423
  ...opts.ttl !== void 0 ? { ttl: opts.ttl } : {},
5252
5424
  ...opts.type ? { type: opts.type } : {},
@@ -5329,7 +5501,7 @@ var memory = {
5329
5501
  lastConfirmedAt: now(),
5330
5502
  version: (entry.version ? entry.version : 0) + 1,
5331
5503
  sync: isSyncEnabled2() ? "pending" : void 0,
5332
- hlc: hlc.serialize(hlc.tick()),
5504
+ hlc: exports.hlc.serialize(exports.hlc.tick()),
5333
5505
  patches,
5334
5506
  path: patches[0]?.path
5335
5507
  };
@@ -5575,6 +5747,7 @@ if (!("memorio" in globalThis)) {
5575
5747
  );
5576
5748
  memorio.memory = memory;
5577
5749
  memorio.encryption = exports.encryption;
5750
+ memorio.sqlite = exports.sqlite;
5578
5751
  initializePlatform();
5579
5752
  memorio.isBrowser = isBrowser;
5580
5753
  memorio.isNode = isNode;
@@ -5696,7 +5869,6 @@ exports.generateTransactionId = generateTransactionId;
5696
5869
  exports.getCapabilities = getCapabilities;
5697
5870
  exports.getContext = getContext;
5698
5871
  exports.help = help;
5699
- exports.hlc = hlc;
5700
5872
  exports.isBrowser = isBrowser;
5701
5873
  exports.isBun = isBun;
5702
5874
  exports.isDeno = isDeno;