dexie 4.0.8 → 4.1.0-alpha.12

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/dexie.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * By David Fahlander, david.fahlander@gmail.com
6
6
  *
7
- * Version 4.0.8, Wed Jul 10 2024
7
+ * Version 4.1.0-alpha.12, Wed Oct 16 2024
8
8
  *
9
9
  * https://dexie.org
10
10
  *
@@ -52,6 +52,33 @@
52
52
  };
53
53
  return __assign.apply(this, arguments);
54
54
  };
55
+ function __values(o) {
56
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
57
+ if (m) return m.call(o);
58
+ if (o && typeof o.length === "number") return {
59
+ next: function () {
60
+ if (o && i >= o.length) o = void 0;
61
+ return { value: o && o[i++], done: !o };
62
+ }
63
+ };
64
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
65
+ }
66
+ function __read(o, n) {
67
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
68
+ if (!m) return o;
69
+ var i = m.call(o), r, ar = [], e;
70
+ try {
71
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
72
+ }
73
+ catch (error) { e = { error: error }; }
74
+ finally {
75
+ try {
76
+ if (r && !r.done && (m = i["return"])) m.call(i);
77
+ }
78
+ finally { if (e) throw e.error; }
79
+ }
80
+ return ar;
81
+ }
55
82
  function __spreadArray(to, from, pack) {
56
83
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
57
84
  if (ar || !(i in from)) {
@@ -1150,7 +1177,7 @@
1150
1177
  }
1151
1178
  }
1152
1179
 
1153
- var DEXIE_VERSION = '4.0.8';
1180
+ var DEXIE_VERSION = '4.1.0-alpha.12';
1154
1181
  var maxString = String.fromCharCode(65535);
1155
1182
  var minKey = -Infinity;
1156
1183
  var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.";
@@ -1268,6 +1295,98 @@
1268
1295
  return new Uint8Array(a);
1269
1296
  }
1270
1297
 
1298
+ function getDocCache(db) {
1299
+ var _a;
1300
+ var _b;
1301
+ return (_a = (_b = db._novip)['_docCache']) !== null && _a !== void 0 ? _a : (_b['_docCache'] = {
1302
+ cache: {},
1303
+ get size() {
1304
+ return Object.keys(this.cache).length;
1305
+ },
1306
+ find: function (table, primaryKey, ydocProp) {
1307
+ var cacheKey = getYDocCacheKey(table, primaryKey, ydocProp);
1308
+ var docRef = this.cache[cacheKey];
1309
+ return docRef ? docRef.deref() : undefined;
1310
+ },
1311
+ add: function (doc) {
1312
+ var _a = doc.meta, parentTable = _a.parentTable, parentId = _a.parentId, parentProp = _a.parentProp;
1313
+ if (!parentTable || !parentProp || parentId == null)
1314
+ throw new Error("Missing Dexie-related metadata in Y.Doc");
1315
+ var cacheKey = getYDocCacheKey(parentTable, parentId, parentProp);
1316
+ this.cache[cacheKey] = new WeakRef(doc);
1317
+ docRegistry.register(doc, { cache: this.cache, key: cacheKey });
1318
+ },
1319
+ delete: function (doc) {
1320
+ docRegistry.unregister(doc);
1321
+ delete this.cache[getYDocCacheKey(doc.meta.parentTable, doc.meta.parentId, doc.meta.parentProp)];
1322
+ },
1323
+ });
1324
+ }
1325
+ var docRegistry = new FinalizationRegistry(function (_a) {
1326
+ var cache = _a.cache, key = _a.key;
1327
+ delete cache[key];
1328
+ });
1329
+ var destroyedDocs = new WeakSet();
1330
+ function throwIfDestroyed(doc) {
1331
+ if (destroyedDocs.has(doc))
1332
+ throw new Error('Y.Doc has been destroyed');
1333
+ }
1334
+ function getYDocCacheKey(table, primaryKey, ydocProp) {
1335
+ return "".concat(table, "[").concat(primaryKey, "].").concat(ydocProp);
1336
+ }
1337
+
1338
+ function createYDocProperty(db, Y, table, prop, updatesTable) {
1339
+ var pkKeyPath = table.schema.primKey.keyPath;
1340
+ var docCache = getDocCache(db);
1341
+ return {
1342
+ set: function () {
1343
+ throw new TypeError("Y.Doc properties are read-only");
1344
+ },
1345
+ get: function () {
1346
+ var id = getByKeyPath(this, pkKeyPath);
1347
+ var doc = docCache.find(table.name, id, prop);
1348
+ if (doc)
1349
+ return doc;
1350
+ doc = new Y.Doc({
1351
+ meta: {
1352
+ db: db,
1353
+ updatesTable: updatesTable,
1354
+ parentProp: prop,
1355
+ parentTable: table.name,
1356
+ parentId: id
1357
+ },
1358
+ });
1359
+ docCache.add(doc);
1360
+ doc.on('destroy', function () {
1361
+ destroyedDocs.add(doc);
1362
+ docCache.delete(doc);
1363
+ });
1364
+ return doc;
1365
+ },
1366
+ };
1367
+ }
1368
+
1369
+ function builtInDeletionTrigger(table, keys, res) {
1370
+ var yProps = table.schema.yProps;
1371
+ if (!yProps)
1372
+ return res;
1373
+ if (keys && res.numFailures > 0)
1374
+ keys = keys.filter(function (_, i) { return !res.failures[i]; });
1375
+ return Promise.all(yProps.map(function (_a) {
1376
+ var updatesTable = _a.updatesTable;
1377
+ return keys
1378
+ ? table.db.table(updatesTable).where('k').anyOf(keys).delete()
1379
+ : table.db.table(updatesTable).clear();
1380
+ })).then(function () { return res; });
1381
+ }
1382
+
1383
+ function getYLibrary(db) {
1384
+ var Y = db._options.Y;
1385
+ if (!Y)
1386
+ throw new exceptions.MissingAPI('Y library not supplied to Dexie constructor');
1387
+ return Y;
1388
+ }
1389
+
1271
1390
  var Table = (function () {
1272
1391
  function Table() {
1273
1392
  }
@@ -1347,8 +1466,8 @@
1347
1466
  function equals(a, b) {
1348
1467
  return idb.cmp(a, b) === 0;
1349
1468
  }
1350
- var _a = keyPaths.reduce(function (_a, keyPath) {
1351
- var prevIndex = _a[0], prevFilterFn = _a[1];
1469
+ var _a = __read(keyPaths.reduce(function (_a, keyPath) {
1470
+ var _b = __read(_a, 2), prevIndex = _b[0], prevFilterFn = _b[1];
1352
1471
  var index = idxByName[keyPath];
1353
1472
  var value = indexOrCrit[keyPath];
1354
1473
  return [
@@ -1361,7 +1480,7 @@
1361
1480
  } : function (x) { return equals(value, getByKeyPath(x, keyPath)); })
1362
1481
  : prevFilterFn
1363
1482
  ];
1364
- }, [null, null]), idx = _a[0], filterFunction = _a[1];
1483
+ }, [null, null]), 2), idx = _a[0], filterFunction = _a[1];
1365
1484
  return idx ?
1366
1485
  this.where(idx.name).equals(indexOrCrit[idx.keyPath])
1367
1486
  .filter(filterFunction) :
@@ -1399,6 +1518,7 @@
1399
1518
  return this.toCollection().reverse();
1400
1519
  };
1401
1520
  Table.prototype.mapToClass = function (constructor) {
1521
+ var _this = this;
1402
1522
  var _a = this, db = _a.db, tableName = _a.name;
1403
1523
  this.schema.mappedClass = constructor;
1404
1524
  if (constructor.prototype instanceof Entity) {
@@ -1416,6 +1536,21 @@
1416
1536
  return class_1;
1417
1537
  }(constructor));
1418
1538
  }
1539
+ if (this.schema.yProps) {
1540
+ var Y_1 = getYLibrary(db);
1541
+ var DBObjectWithYProps = (function (_super) {
1542
+ __extends(DBObjectWithYProps, _super);
1543
+ function DBObjectWithYProps() {
1544
+ return _super !== null && _super.apply(this, arguments) || this;
1545
+ }
1546
+ return DBObjectWithYProps;
1547
+ }(constructor));
1548
+ constructor = DBObjectWithYProps;
1549
+ this.schema.yProps.forEach(function (_a) {
1550
+ var prop = _a.prop, updatesTable = _a.updatesTable;
1551
+ Object.defineProperty(constructor.prototype, prop, createYDocProperty(db, Y_1, _this, prop, updatesTable));
1552
+ });
1553
+ }
1419
1554
  var inheritedProps = new Set();
1420
1555
  for (var proto = constructor.prototype; proto; proto = getProto(proto)) {
1421
1556
  Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); });
@@ -1497,12 +1632,14 @@
1497
1632
  };
1498
1633
  Table.prototype.delete = function (key) {
1499
1634
  var _this = this;
1500
- return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); })
1501
- .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });
1635
+ return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] })
1636
+ .then(function (res) { return builtInDeletionTrigger(_this, [key], res); })
1637
+ .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); });
1502
1638
  };
1503
1639
  Table.prototype.clear = function () {
1504
1640
  var _this = this;
1505
- return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); })
1641
+ return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange })
1642
+ .then(function (res) { return builtInDeletionTrigger(_this, null, res); }); })
1506
1643
  .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });
1507
1644
  };
1508
1645
  Table.prototype.bulkGet = function (keys) {
@@ -1575,20 +1712,30 @@
1575
1712
  var resultKeys = [];
1576
1713
  var resultObjs = [];
1577
1714
  keysAndChanges.forEach(function (_a, idx) {
1715
+ var e_1, _b;
1578
1716
  var key = _a.key, changes = _a.changes;
1579
1717
  var obj = objs[idx];
1580
1718
  if (obj) {
1581
- for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) {
1582
- var keyPath = _b[_i];
1583
- var value = changes[keyPath];
1584
- if (keyPath === _this.schema.primKey.keyPath) {
1585
- if (cmp(value, key) !== 0) {
1586
- throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()");
1719
+ try {
1720
+ for (var _c = __values(Object.keys(changes)), _d = _c.next(); !_d.done; _d = _c.next()) {
1721
+ var keyPath = _d.value;
1722
+ var value = changes[keyPath];
1723
+ if (keyPath === _this.schema.primKey.keyPath) {
1724
+ if (cmp(value, key) !== 0) {
1725
+ throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()");
1726
+ }
1727
+ }
1728
+ else {
1729
+ setByKeyPath(obj, keyPath, value);
1587
1730
  }
1588
1731
  }
1589
- else {
1590
- setByKeyPath(obj, keyPath, value);
1732
+ }
1733
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1734
+ finally {
1735
+ try {
1736
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1591
1737
  }
1738
+ finally { if (e_1) throw e_1.error; }
1592
1739
  }
1593
1740
  offsetMap.push(idx);
1594
1741
  resultKeys.push(key);
@@ -1608,17 +1755,27 @@
1608
1755
  }
1609
1756
  })
1610
1757
  .then(function (_a) {
1758
+ var e_2, _b;
1611
1759
  var numFailures = _a.numFailures, failures = _a.failures;
1612
1760
  if (numFailures === 0)
1613
1761
  return numEntries;
1614
- for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) {
1615
- var offset = _b[_i];
1616
- var mappedOffset = offsetMap[Number(offset)];
1617
- if (mappedOffset != null) {
1618
- var failure = failures[offset];
1619
- delete failures[offset];
1620
- failures[mappedOffset] = failure;
1762
+ try {
1763
+ for (var _c = __values(Object.keys(failures)), _d = _c.next(); !_d.done; _d = _c.next()) {
1764
+ var offset = _d.value;
1765
+ var mappedOffset = offsetMap[Number(offset)];
1766
+ if (mappedOffset != null) {
1767
+ var failure = failures[offset];
1768
+ delete failures[offset];
1769
+ failures[mappedOffset] = failure;
1770
+ }
1771
+ }
1772
+ }
1773
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1774
+ finally {
1775
+ try {
1776
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1621
1777
  }
1778
+ finally { if (e_2) throw e_2.error; }
1622
1779
  }
1623
1780
  throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures);
1624
1781
  });
@@ -1629,7 +1786,8 @@
1629
1786
  var _this = this;
1630
1787
  var numKeys = keys.length;
1631
1788
  return this._trans('readwrite', function (trans) {
1632
- return _this.core.mutate({ trans: trans, type: 'delete', keys: keys });
1789
+ return _this.core.mutate({ trans: trans, type: 'delete', keys: keys })
1790
+ .then(function (res) { return builtInDeletionTrigger(_this, keys, res); });
1633
1791
  }).then(function (_a) {
1634
1792
  var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures;
1635
1793
  if (numFailures === 0)
@@ -1813,7 +1971,7 @@
1813
1971
  if (this.add !== undefined) {
1814
1972
  var term = this.add;
1815
1973
  if (isArray(term)) {
1816
- return __spreadArray(__spreadArray([], (isArray(value) ? value : []), true), term, true).sort();
1974
+ return __spreadArray(__spreadArray([], __read((isArray(value) ? value : [])), false), __read(term), false).sort();
1817
1975
  }
1818
1976
  if (typeof term === 'number')
1819
1977
  return (Number(value) || 0) + term;
@@ -2146,52 +2304,65 @@
2146
2304
  var successCount = 0;
2147
2305
  var failedKeys = [];
2148
2306
  var applyMutateResult = function (expectedCount, res) {
2307
+ var e_1, _a;
2149
2308
  var failures = res.failures, numFailures = res.numFailures;
2150
2309
  successCount += expectedCount - numFailures;
2151
- for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) {
2152
- var pos = _a[_i];
2153
- totalFailures.push(failures[pos]);
2310
+ try {
2311
+ for (var _b = __values(keys(failures)), _c = _b.next(); !_c.done; _c = _b.next()) {
2312
+ var pos = _c.value;
2313
+ totalFailures.push(failures[pos]);
2314
+ }
2315
+ }
2316
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2317
+ finally {
2318
+ try {
2319
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2320
+ }
2321
+ finally { if (e_1) throw e_1.error; }
2154
2322
  }
2155
2323
  };
2324
+ var isUnconditionalDelete = changes === deleteCallback;
2156
2325
  return _this.clone().primaryKeys().then(function (keys) {
2157
2326
  var criteria = isPlainKeyRange(ctx) &&
2158
2327
  ctx.limit === Infinity &&
2159
- (typeof changes !== 'function' || changes === deleteCallback) && {
2328
+ (typeof changes !== 'function' || isUnconditionalDelete) && {
2160
2329
  index: ctx.index,
2161
2330
  range: ctx.range
2162
2331
  };
2163
2332
  var nextChunk = function (offset) {
2164
2333
  var count = Math.min(limit, keys.length - offset);
2165
- return coreTable.getMany({
2334
+ var keysInChunk = keys.slice(offset, offset + count);
2335
+ return (isUnconditionalDelete ? Promise.resolve([]) : coreTable.getMany({
2166
2336
  trans: trans,
2167
- keys: keys.slice(offset, offset + count),
2337
+ keys: keysInChunk,
2168
2338
  cache: "immutable"
2169
- }).then(function (values) {
2339
+ })).then(function (values) {
2170
2340
  var addValues = [];
2171
2341
  var putValues = [];
2172
2342
  var putKeys = outbound ? [] : null;
2173
- var deleteKeys = [];
2174
- for (var i = 0; i < count; ++i) {
2175
- var origValue = values[i];
2176
- var ctx_1 = {
2177
- value: deepClone(origValue),
2178
- primKey: keys[offset + i]
2179
- };
2180
- if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {
2181
- if (ctx_1.value == null) {
2182
- deleteKeys.push(keys[offset + i]);
2183
- }
2184
- else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {
2185
- deleteKeys.push(keys[offset + i]);
2186
- addValues.push(ctx_1.value);
2187
- }
2188
- else {
2189
- putValues.push(ctx_1.value);
2190
- if (outbound)
2191
- putKeys.push(keys[offset + i]);
2343
+ var deleteKeys = isUnconditionalDelete ? keysInChunk : [];
2344
+ if (!isUnconditionalDelete)
2345
+ for (var i = 0; i < count; ++i) {
2346
+ var origValue = values[i];
2347
+ var ctx_1 = {
2348
+ value: deepClone(origValue),
2349
+ primKey: keys[offset + i]
2350
+ };
2351
+ if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {
2352
+ if (ctx_1.value == null) {
2353
+ deleteKeys.push(keys[offset + i]);
2354
+ }
2355
+ else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {
2356
+ deleteKeys.push(keys[offset + i]);
2357
+ addValues.push(ctx_1.value);
2358
+ }
2359
+ else {
2360
+ putValues.push(ctx_1.value);
2361
+ if (outbound)
2362
+ putKeys.push(keys[offset + i]);
2363
+ }
2192
2364
  }
2193
2365
  }
2194
- }
2195
2366
  return Promise.resolve(addValues.length > 0 &&
2196
2367
  coreTable.mutate({ trans: trans, type: 'add', values: addValues })
2197
2368
  .then(function (res) {
@@ -2209,14 +2380,15 @@
2209
2380
  changeSpec: typeof changes !== 'function'
2210
2381
  && changes,
2211
2382
  isAdditionalChunk: offset > 0
2212
- }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&
2383
+ }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && isUnconditionalDelete)) &&
2213
2384
  coreTable.mutate({
2214
2385
  trans: trans,
2215
2386
  type: 'delete',
2216
2387
  keys: deleteKeys,
2217
2388
  criteria: criteria,
2218
2389
  isAdditionalChunk: offset > 0
2219
- }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {
2390
+ }).then(function (res) { return builtInDeletionTrigger(ctx.table, deleteKeys, res); })
2391
+ .then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {
2220
2392
  return keys.length > offset + count && nextChunk(offset + limit);
2221
2393
  });
2222
2394
  });
@@ -2232,6 +2404,7 @@
2232
2404
  Collection.prototype.delete = function () {
2233
2405
  var ctx = this._ctx, range = ctx.range;
2234
2406
  if (isPlainKeyRange(ctx) &&
2407
+ !ctx.table.schema.yProps &&
2235
2408
  (ctx.isPrimKey || range.type === 3 ))
2236
2409
  {
2237
2410
  return this._write(function (trans) {
@@ -2240,7 +2413,7 @@
2240
2413
  return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) {
2241
2414
  return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange })
2242
2415
  .then(function (_a) {
2243
- var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures;
2416
+ var failures = _a.failures, numFailures = _a.numFailures;
2244
2417
  if (numFailures)
2245
2418
  throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures);
2246
2419
  return count - numFailures;
@@ -2842,6 +3015,13 @@
2842
3015
  function createTransactionConstructor(db) {
2843
3016
  return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) {
2844
3017
  var _this = this;
3018
+ if (mode !== 'readonly')
3019
+ storeNames.forEach(function (storeName) {
3020
+ var _a;
3021
+ var yProps = (_a = dbschema[storeName]) === null || _a === void 0 ? void 0 : _a.yProps;
3022
+ if (yProps)
3023
+ storeNames = storeNames.concat(yProps.map(function (p) { return p.updatesTable; }));
3024
+ });
2845
3025
  this.db = db;
2846
3026
  this.mode = mode;
2847
3027
  this.storeNames = storeNames;
@@ -2877,7 +3057,7 @@
2877
3057
  });
2878
3058
  }
2879
3059
 
2880
- function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) {
3060
+ function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey, type) {
2881
3061
  return {
2882
3062
  name: name,
2883
3063
  keyPath: keyPath,
@@ -2885,7 +3065,8 @@
2885
3065
  multi: multi,
2886
3066
  auto: auto,
2887
3067
  compound: compound,
2888
- src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath)
3068
+ src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath),
3069
+ type: type
2889
3070
  };
2890
3071
  }
2891
3072
  function nameFromKeyPath(keyPath) {
@@ -2894,13 +3075,17 @@
2894
3075
  keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : "";
2895
3076
  }
2896
3077
 
2897
- function createTableSchema(name, primKey, indexes) {
3078
+ function createTableSchema(name, primKey, indexes, yProps) {
2898
3079
  return {
2899
3080
  name: name,
2900
3081
  primKey: primKey,
2901
3082
  indexes: indexes,
2902
3083
  mappedClass: null,
2903
- idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; })
3084
+ yProps: yProps === null || yProps === void 0 ? void 0 : yProps.map(function (prop) { return ({
3085
+ prop: prop,
3086
+ updatesTable: "$".concat(name, ".").concat(prop, "_updates"),
3087
+ }); }),
3088
+ idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }),
2904
3089
  };
2905
3090
  }
2906
3091
 
@@ -3053,11 +3238,11 @@
3053
3238
  reqs.push(req = store.delete(makeIDBKeyRange(range)));
3054
3239
  }
3055
3240
  else {
3056
- var _a = isAddOrPut ?
3241
+ var _a = __read(isAddOrPut ?
3057
3242
  outbound ?
3058
3243
  [values, keys] :
3059
3244
  [values, null] :
3060
- [keys, null], args1 = _a[0], args2 = _a[1];
3245
+ [keys, null], 2), args1 = _a[0], args2 = _a[1];
3061
3246
  if (isAddOrPut) {
3062
3247
  for (var i = 0; i < length; ++i) {
3063
3248
  reqs.push(req = (args2 && args2[i] !== undefined ?
@@ -3382,6 +3567,7 @@
3382
3567
  });
3383
3568
  }
3384
3569
  function patchCurrentVersion(db, idbUpgradeTrans) {
3570
+ var e_1, _a;
3385
3571
  createMissingTables(db._dbSchema, idbUpgradeTrans);
3386
3572
  if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) {
3387
3573
  idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version');
@@ -3401,11 +3587,20 @@
3401
3587
  addIndex(store, idx);
3402
3588
  });
3403
3589
  };
3404
- for (var _i = 0, _a = diff.change; _i < _a.length; _i++) {
3405
- var tableChange = _a[_i];
3406
- var state_1 = _loop_1(tableChange);
3407
- if (typeof state_1 === "object")
3408
- return state_1.value;
3590
+ try {
3591
+ for (var _b = __values(diff.change), _c = _b.next(); !_c.done; _c = _b.next()) {
3592
+ var tableChange = _c.value;
3593
+ var state_1 = _loop_1(tableChange);
3594
+ if (typeof state_1 === "object")
3595
+ return state_1.value;
3596
+ }
3597
+ }
3598
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3599
+ finally {
3600
+ try {
3601
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3602
+ }
3603
+ finally { if (e_1) throw e_1.error; }
3409
3604
  }
3410
3605
  }
3411
3606
  function getExistingVersion(db, trans, oldVersion) {
@@ -3644,51 +3839,169 @@
3644
3839
  }
3645
3840
  function parseIndexSyntax(primKeyAndIndexes) {
3646
3841
  return primKeyAndIndexes.split(',').map(function (index, indexNum) {
3647
- index = index.trim();
3842
+ var _a;
3843
+ var typeSplit = index.split(':');
3844
+ var type = (_a = typeSplit[1]) === null || _a === void 0 ? void 0 : _a.trim();
3845
+ index = typeSplit[0].trim();
3846
+ if (type && type !== 'Y')
3847
+ throw new exceptions.Schema("Unsupported type '".concat(type, "'"));
3648
3848
  var name = index.replace(/([&*]|\+\+)/g, "");
3649
3849
  var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name;
3650
- return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0);
3850
+ return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0, type);
3651
3851
  });
3652
3852
  }
3653
3853
 
3854
+ var EMPTY_ARRAY = [];
3855
+ function createYjsMiddleware(dbSchema, Y) {
3856
+ return {
3857
+ stack: 'dbcore',
3858
+ name: 'yjsMiddleware',
3859
+ level: 50,
3860
+ create: function (downCore) {
3861
+ return (__assign(__assign({}, downCore), { table: function (tableName) {
3862
+ var downTable = downCore.table(tableName);
3863
+ var dbTableSchema = dbSchema[tableName];
3864
+ var yProps = dbTableSchema.yProps;
3865
+ if (!yProps || yProps.length === 0)
3866
+ return downTable;
3867
+ var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) {
3868
+ if (req.type !== 'add' && req.type !== 'put')
3869
+ return downTable.mutate(req);
3870
+ var reqClone = req;
3871
+ var updateSources = yProps
3872
+ .map(function (p) { return ({
3873
+ p: p,
3874
+ entries: req.values.flatMap(function (value, iter) {
3875
+ if (!value || typeof value !== 'object')
3876
+ throw new TypeError("Table ".concat(tableName, " (with Y-properties) must only contain objects"));
3877
+ if (!hasOwn(value, p.prop))
3878
+ return [];
3879
+ if (reqClone === req)
3880
+ reqClone = __assign(__assign({}, req), { values: req.values.map(function (v) { return (__assign({}, v)); }) });
3881
+ delete reqClone.values[iter][p.prop];
3882
+ var doc = value[p.prop];
3883
+ if (doc === null)
3884
+ throw new TypeError("Cannot set Y property to null");
3885
+ if (doc === undefined)
3886
+ return EMPTY_ARRAY;
3887
+ if (typeof doc !== 'object' || !('whenLoaded' in doc)) {
3888
+ throw new TypeError("Y properties can only be inited with an Y.Doc instance or undefined to create an empty Y.Doc");
3889
+ }
3890
+ if (req.type === 'put')
3891
+ throw new TypeError("Setting ".concat(tableName, ".").concat(p.prop, " (declared as ").concat(p.prop, ":Y) is only allowed when inserting new objects using db.").concat(tableName, ".add(), not put() or update()."));
3892
+ if (Y.encodeStateVector(doc).length === 1) {
3893
+ return EMPTY_ARRAY;
3894
+ }
3895
+ return {
3896
+ iter: iter,
3897
+ u: Y.encodeStateAsUpdateV2(doc),
3898
+ };
3899
+ }),
3900
+ }); })
3901
+ .filter(function (_a) {
3902
+ var entries = _a.entries;
3903
+ return entries.length > 0;
3904
+ });
3905
+ if (req === reqClone)
3906
+ return downTable.mutate(req);
3907
+ return downTable.mutate(reqClone).then(function (res) {
3908
+ if (updateSources.length === 0)
3909
+ return res;
3910
+ return Promise.all(updateSources.map(function (_a) {
3911
+ var p = _a.p, entries = _a.entries;
3912
+ var updatesTable = downCore.table(p.updatesTable);
3913
+ var updatesToInsert = entries.map(function (_a) {
3914
+ var iter = _a.iter, u = _a.u;
3915
+ return ({
3916
+ k: res.results[iter],
3917
+ u: u,
3918
+ f: 1,
3919
+ });
3920
+ });
3921
+ return updatesTable.mutate({
3922
+ type: 'add',
3923
+ values: updatesToInsert,
3924
+ trans: req.trans,
3925
+ });
3926
+ })).then(function () { return res; });
3927
+ });
3928
+ } });
3929
+ return tableMiddleware;
3930
+ } }));
3931
+ },
3932
+ };
3933
+ }
3934
+
3654
3935
  var Version = (function () {
3655
3936
  function Version() {
3656
3937
  }
3657
3938
  Version.prototype._parseStoresSpec = function (stores, outSchema) {
3939
+ var _this = this;
3658
3940
  keys(stores).forEach(function (tableName) {
3941
+ var e_1, _a, _b;
3659
3942
  if (stores[tableName] !== null) {
3660
3943
  var indexes = parseIndexSyntax(stores[tableName]);
3944
+ var yProps = indexes.filter(function (idx) { return idx.type === 'Y'; }).map(function (idx) { return idx.name; });
3945
+ indexes = indexes.filter(function (idx) { return idx.type !== 'Y'; });
3661
3946
  var primKey = indexes.shift();
3947
+ if (!primKey) {
3948
+ throw new exceptions.Schema('Invalid schema for table ' + tableName + ': ' + stores[tableName]);
3949
+ }
3662
3950
  primKey.unique = true;
3663
3951
  if (primKey.multi)
3664
- throw new exceptions.Schema("Primary key cannot be multi-valued");
3952
+ throw new exceptions.Schema('Primary key cannot be multiEntry*');
3665
3953
  indexes.forEach(function (idx) {
3666
3954
  if (idx.auto)
3667
- throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)");
3955
+ throw new exceptions.Schema('Only primary key can be marked as autoIncrement (++)');
3668
3956
  if (!idx.keyPath)
3669
- throw new exceptions.Schema("Index must have a name and cannot be an empty string");
3957
+ throw new exceptions.Schema('Index must have a name and cannot be an empty string');
3670
3958
  });
3671
- outSchema[tableName] = createTableSchema(tableName, primKey, indexes);
3959
+ var tblSchema = createTableSchema(tableName, primKey, indexes, yProps.length ? yProps : undefined);
3960
+ outSchema[tableName] = tblSchema;
3961
+ try {
3962
+ for (var _c = __values(tblSchema.yProps || []), _d = _c.next(); !_d.done; _d = _c.next()) {
3963
+ var yProp = _d.value;
3964
+ _this._parseStoresSpec((_b = {}, _b[yProp.updatesTable] = '++i,k', _b), outSchema);
3965
+ }
3966
+ }
3967
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3968
+ finally {
3969
+ try {
3970
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
3971
+ }
3972
+ finally { if (e_1) throw e_1.error; }
3973
+ }
3672
3974
  }
3673
3975
  });
3674
3976
  };
3675
3977
  Version.prototype.stores = function (stores) {
3676
3978
  var db = this.db;
3677
- this._cfg.storesSource = this._cfg.storesSource ?
3678
- extend(this._cfg.storesSource, stores) :
3679
- stores;
3979
+ this._cfg.storesSource = this._cfg.storesSource
3980
+ ? extend(this._cfg.storesSource, stores)
3981
+ : stores;
3680
3982
  var versions = db._versions;
3681
3983
  var storesSpec = {};
3682
3984
  var dbschema = {};
3683
3985
  versions.forEach(function (version) {
3684
3986
  extend(storesSpec, version._cfg.storesSource);
3685
- dbschema = (version._cfg.dbschema = {});
3987
+ dbschema = version._cfg.dbschema = {};
3686
3988
  version._parseStoresSpec(storesSpec, dbschema);
3687
3989
  });
3688
3990
  db._dbSchema = dbschema;
3689
3991
  removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);
3690
3992
  setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);
3691
3993
  db._storeNames = keys(dbschema);
3994
+ db._storeNames.forEach(function (tableName) {
3995
+ if (dbschema[tableName].yProps) {
3996
+ db.table(tableName).mapToClass(dbschema[tableName].mappedClass || Object);
3997
+ }
3998
+ });
3999
+ if (Object.values(dbschema).some(function (table) { return table.yProps; })) {
4000
+ db.use(createYjsMiddleware(dbschema, getYLibrary(db)));
4001
+ }
4002
+ else {
4003
+ db.unuse({ stack: 'dbcore', name: 'yjsMiddleware' });
4004
+ }
3692
4005
  return this;
3693
4006
  };
3694
4007
  Version.prototype.upgrade = function (upgradeFunction) {
@@ -3967,19 +4280,29 @@
3967
4280
  }
3968
4281
  }
3969
4282
  function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) {
4283
+ var e_1, _a;
3970
4284
  if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; }
3971
4285
  var queriesToSignal = new Set();
3972
4286
  if (updatedParts.all) {
3973
- for (var _i = 0, _a = Object.values(cache); _i < _a.length; _i++) {
3974
- var tblCache = _a[_i];
3975
- collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
4287
+ try {
4288
+ for (var _b = __values(Object.values(cache)), _c = _b.next(); !_c.done; _c = _b.next()) {
4289
+ var tblCache = _c.value;
4290
+ collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
4291
+ }
4292
+ }
4293
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4294
+ finally {
4295
+ try {
4296
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4297
+ }
4298
+ finally { if (e_1) throw e_1.error; }
3976
4299
  }
3977
4300
  }
3978
4301
  else {
3979
4302
  for (var key in updatedParts) {
3980
4303
  var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key);
3981
4304
  if (parts) {
3982
- var dbName = parts[1], tableName = parts[2];
4305
+ var _d = __read(parts, 3), dbName = _d[1], tableName = _d[2];
3983
4306
  var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)];
3984
4307
  if (tblCache)
3985
4308
  collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
@@ -3989,26 +4312,54 @@
3989
4312
  queriesToSignal.forEach(function (requery) { return requery(); });
3990
4313
  }
3991
4314
  function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) {
4315
+ var e_2, _a, e_3, _b, e_4, _c;
3992
4316
  var updatedEntryLists = [];
3993
- for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) {
3994
- var _b = _a[_i], indexName = _b[0], entries = _b[1];
3995
- var filteredEntries = [];
3996
- for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) {
3997
- var entry = entries_1[_c];
3998
- if (obsSetsOverlap(updatedParts, entry.obsSet)) {
3999
- entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });
4317
+ try {
4318
+ for (var _d = __values(Object.entries(tblCache.queries.query)), _e = _d.next(); !_e.done; _e = _d.next()) {
4319
+ var _f = __read(_e.value, 2), indexName = _f[0], entries = _f[1];
4320
+ var filteredEntries = [];
4321
+ try {
4322
+ for (var entries_1 = (e_3 = void 0, __values(entries)), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
4323
+ var entry = entries_1_1.value;
4324
+ if (obsSetsOverlap(updatedParts, entry.obsSet)) {
4325
+ entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });
4326
+ }
4327
+ else if (deleteAffectedCacheEntries) {
4328
+ filteredEntries.push(entry);
4329
+ }
4330
+ }
4000
4331
  }
4001
- else if (deleteAffectedCacheEntries) {
4002
- filteredEntries.push(entry);
4332
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
4333
+ finally {
4334
+ try {
4335
+ if (entries_1_1 && !entries_1_1.done && (_b = entries_1.return)) _b.call(entries_1);
4336
+ }
4337
+ finally { if (e_3) throw e_3.error; }
4003
4338
  }
4339
+ if (deleteAffectedCacheEntries)
4340
+ updatedEntryLists.push([indexName, filteredEntries]);
4341
+ }
4342
+ }
4343
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
4344
+ finally {
4345
+ try {
4346
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
4004
4347
  }
4005
- if (deleteAffectedCacheEntries)
4006
- updatedEntryLists.push([indexName, filteredEntries]);
4348
+ finally { if (e_2) throw e_2.error; }
4007
4349
  }
4008
4350
  if (deleteAffectedCacheEntries) {
4009
- for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) {
4010
- var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1];
4011
- tblCache.queries.query[indexName] = filteredEntries;
4351
+ try {
4352
+ for (var updatedEntryLists_1 = __values(updatedEntryLists), updatedEntryLists_1_1 = updatedEntryLists_1.next(); !updatedEntryLists_1_1.done; updatedEntryLists_1_1 = updatedEntryLists_1.next()) {
4353
+ var _g = __read(updatedEntryLists_1_1.value, 2), indexName = _g[0], filteredEntries = _g[1];
4354
+ tblCache.queries.query[indexName] = filteredEntries;
4355
+ }
4356
+ }
4357
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
4358
+ finally {
4359
+ try {
4360
+ if (updatedEntryLists_1_1 && !updatedEntryLists_1_1.done && (_c = updatedEntryLists_1.return)) _c.call(updatedEntryLists_1);
4361
+ }
4362
+ finally { if (e_4) throw e_4.error; }
4012
4363
  }
4013
4364
  }
4014
4365
  }
@@ -4259,6 +4610,7 @@
4259
4610
  }
4260
4611
  function createVirtualIndexMiddleware(down) {
4261
4612
  return __assign(__assign({}, down), { table: function (tableName) {
4613
+ var e_1, _a;
4262
4614
  var table = down.table(tableName);
4263
4615
  var schema = table.schema;
4264
4616
  var indexLookup = {};
@@ -4286,9 +4638,18 @@
4286
4638
  }
4287
4639
  var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);
4288
4640
  indexLookup[":id"] = [primaryKey];
4289
- for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) {
4290
- var index = _a[_i];
4291
- addVirtualIndexes(index.keyPath, 0, index);
4641
+ try {
4642
+ for (var _b = __values(schema.indexes), _c = _b.next(); !_c.done; _c = _b.next()) {
4643
+ var index = _c.value;
4644
+ addVirtualIndexes(index.keyPath, 0, index);
4645
+ }
4646
+ }
4647
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4648
+ finally {
4649
+ try {
4650
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4651
+ }
4652
+ finally { if (e_1) throw e_1.error; }
4292
4653
  }
4293
4654
  function findBestIndex(keyPath) {
4294
4655
  var result = indexLookup[getKeyPathAlias(keyPath)];
@@ -4448,9 +4809,9 @@
4448
4809
  throw new Error("Keys missing");
4449
4810
  req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req);
4450
4811
  if (req.type !== 'delete')
4451
- req.values = __spreadArray([], req.values, true);
4812
+ req.values = __spreadArray([], __read(req.values), false);
4452
4813
  if (req.keys)
4453
- req.keys = __spreadArray([], req.keys, true);
4814
+ req.keys = __spreadArray([], __read(req.keys), false);
4454
4815
  return getExistingValues(downTable, req, keys).then(function (existingValues) {
4455
4816
  var contexts = keys.map(function (key, i) {
4456
4817
  var existingValue = existingValues[i];
@@ -4639,13 +5000,13 @@
4639
5000
  var pkRangeSet = getRangeSet("");
4640
5001
  var delsRangeSet = getRangeSet(":dels");
4641
5002
  var type = req.type;
4642
- var _a = req.type === "deleteRange"
5003
+ var _a = __read(req.type === "deleteRange"
4643
5004
  ? [req.range]
4644
5005
  : req.type === "delete"
4645
5006
  ? [req.keys]
4646
5007
  : req.values.length < 50
4647
5008
  ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values]
4648
- : [], keys = _a[0], newObjs = _a[1];
5009
+ : [], 2), keys = _a[0], newObjs = _a[1];
4649
5010
  var oldCache = req.trans["_cache"];
4650
5011
  if (isArray(keys)) {
4651
5012
  pkRangeSet.addKeys(keys);
@@ -4714,7 +5075,7 @@
4714
5075
  };
4715
5076
  var pkRangeSet_1 = getRangeSet("");
4716
5077
  var delsRangeSet_1 = getRangeSet(":dels");
4717
- var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1];
5078
+ var _a = __read(readSubscribers[method](req), 2), queriedIndex = _a[0], queriedRanges = _a[1];
4718
5079
  if (method === 'query' && queriedIndex.isPrimaryKey && !req.values) {
4719
5080
  delsRangeSet_1.add(queriedRanges);
4720
5081
  }
@@ -5038,60 +5399,106 @@
5038
5399
  var ac_1 = new AbortController();
5039
5400
  var signal = ac_1.signal;
5040
5401
  var endTransaction = function (wasCommitted) { return function () {
5402
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e;
5041
5403
  ac_1.abort();
5042
5404
  if (mode === 'readwrite') {
5043
5405
  var affectedSubscribers_1 = new Set();
5044
- for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) {
5045
- var storeName = stores_1[_i];
5046
- var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)];
5047
- if (tblCache) {
5048
- var table = core.table(storeName);
5049
- var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });
5050
- if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {
5051
- for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) {
5052
- var entries = _b[_a];
5053
- for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) {
5054
- var entry = _d[_c];
5055
- if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {
5056
- delArrayItem(entries, entry);
5057
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5406
+ try {
5407
+ for (var stores_1 = __values(stores), stores_1_1 = stores_1.next(); !stores_1_1.done; stores_1_1 = stores_1.next()) {
5408
+ var storeName = stores_1_1.value;
5409
+ var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)];
5410
+ if (tblCache) {
5411
+ var table = core.table(storeName);
5412
+ var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });
5413
+ if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {
5414
+ try {
5415
+ for (var _f = (e_2 = void 0, __values(Object.values(tblCache.queries.query))), _g = _f.next(); !_g.done; _g = _f.next()) {
5416
+ var entries = _g.value;
5417
+ try {
5418
+ for (var _h = (e_3 = void 0, __values(entries.slice())), _j = _h.next(); !_j.done; _j = _h.next()) {
5419
+ var entry = _j.value;
5420
+ if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {
5421
+ delArrayItem(entries, entry);
5422
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5423
+ }
5424
+ }
5425
+ }
5426
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
5427
+ finally {
5428
+ try {
5429
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
5430
+ }
5431
+ finally { if (e_3) throw e_3.error; }
5432
+ }
5433
+ }
5434
+ }
5435
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5436
+ finally {
5437
+ try {
5438
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
5058
5439
  }
5440
+ finally { if (e_2) throw e_2.error; }
5059
5441
  }
5060
5442
  }
5061
- }
5062
- else if (ops.length > 0) {
5063
- tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });
5064
- for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) {
5065
- var entries = _f[_e];
5066
- for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) {
5067
- var entry = _h[_g];
5068
- if (entry.res != null &&
5069
- idbtrans.mutatedParts
5443
+ else if (ops.length > 0) {
5444
+ tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });
5445
+ try {
5446
+ for (var _k = (e_4 = void 0, __values(Object.values(tblCache.queries.query))), _l = _k.next(); !_l.done; _l = _k.next()) {
5447
+ var entries = _l.value;
5448
+ try {
5449
+ for (var _m = (e_5 = void 0, __values(entries.slice())), _o = _m.next(); !_o.done; _o = _m.next()) {
5450
+ var entry = _o.value;
5451
+ if (entry.res != null &&
5452
+ idbtrans.mutatedParts
5070
5453
  ) {
5071
- if (wasCommitted && !entry.dirty) {
5072
- var freezeResults = Object.isFrozen(entry.res);
5073
- var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);
5074
- if (entry.dirty) {
5075
- delArrayItem(entries, entry);
5076
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5077
- }
5078
- else if (modRes !== entry.res) {
5079
- entry.res = modRes;
5080
- entry.promise = DexiePromise.resolve({ result: modRes });
5454
+ if (wasCommitted && !entry.dirty) {
5455
+ var freezeResults = Object.isFrozen(entry.res);
5456
+ var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);
5457
+ if (entry.dirty) {
5458
+ delArrayItem(entries, entry);
5459
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5460
+ }
5461
+ else if (modRes !== entry.res) {
5462
+ entry.res = modRes;
5463
+ entry.promise = DexiePromise.resolve({ result: modRes });
5464
+ }
5465
+ }
5466
+ else {
5467
+ if (entry.dirty) {
5468
+ delArrayItem(entries, entry);
5469
+ }
5470
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5471
+ }
5472
+ }
5081
5473
  }
5082
5474
  }
5083
- else {
5084
- if (entry.dirty) {
5085
- delArrayItem(entries, entry);
5475
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
5476
+ finally {
5477
+ try {
5478
+ if (_o && !_o.done && (_e = _m.return)) _e.call(_m);
5086
5479
  }
5087
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5480
+ finally { if (e_5) throw e_5.error; }
5088
5481
  }
5089
5482
  }
5090
5483
  }
5484
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
5485
+ finally {
5486
+ try {
5487
+ if (_l && !_l.done && (_d = _k.return)) _d.call(_k);
5488
+ }
5489
+ finally { if (e_4) throw e_4.error; }
5490
+ }
5091
5491
  }
5092
5492
  }
5093
5493
  }
5094
5494
  }
5495
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5496
+ finally {
5497
+ try {
5498
+ if (stores_1_1 && !stores_1_1.done && (_a = stores_1.return)) _a.call(stores_1);
5499
+ }
5500
+ finally { if (e_1) throw e_1.error; }
5501
+ }
5095
5502
  affectedSubscribers_1.forEach(function (requery) { return requery(); });
5096
5503
  }
5097
5504
  }; };
@@ -5161,7 +5568,7 @@
5161
5568
  return downTable.query(req);
5162
5569
  var freezeResults = ((_a = PSD.trans) === null || _a === void 0 ? void 0 : _a.db._options.cache) === 'immutable';
5163
5570
  var _b = PSD, requery = _b.requery, signal = _b.signal;
5164
- var _c = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];
5571
+ var _c = __read(findCompatibleQuery(dbName, tableName, 'query', req), 4), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];
5165
5572
  if (cacheEntry && exactMatch) {
5166
5573
  cacheEntry.obsSet = req.obsSet;
5167
5574
  }
@@ -5235,6 +5642,181 @@
5235
5642
  });
5236
5643
  }
5237
5644
 
5645
+ function compressYDocs(db, interval) {
5646
+ var e_1, _a, e_2, _b;
5647
+ var p = Promise.resolve();
5648
+ try {
5649
+ for (var _c = __values(db.tables), _d = _c.next(); !_d.done; _d = _c.next()) {
5650
+ var table = _d.value;
5651
+ var _loop_1 = function (yProp) {
5652
+ p = p.then(function () { return compressYDocsTable(db, yProp, interval); });
5653
+ };
5654
+ try {
5655
+ for (var _e = (e_2 = void 0, __values(table.schema.yProps || [])), _f = _e.next(); !_f.done; _f = _e.next()) {
5656
+ var yProp = _f.value;
5657
+ _loop_1(yProp);
5658
+ }
5659
+ }
5660
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5661
+ finally {
5662
+ try {
5663
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
5664
+ }
5665
+ finally { if (e_2) throw e_2.error; }
5666
+ }
5667
+ }
5668
+ }
5669
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5670
+ finally {
5671
+ try {
5672
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
5673
+ }
5674
+ finally { if (e_1) throw e_1.error; }
5675
+ }
5676
+ return p;
5677
+ }
5678
+ function compressYDocsTable(db, _a, skipIfRunnedSince
5679
+ ) {
5680
+ var updatesTable = _a.updatesTable;
5681
+ var updTbl = db.table(updatesTable);
5682
+ return Promise.all([
5683
+ updTbl
5684
+ .where('i')
5685
+ .startsWith('')
5686
+ .toArray(),
5687
+ db.transaction('rw', updatesTable, function () {
5688
+ return updTbl.get(0).then(function (lastCompressed) {
5689
+ if (lastCompressed &&
5690
+ skipIfRunnedSince &&
5691
+ lastCompressed.lastRun.getTime() > Date.now() - skipIfRunnedSince) {
5692
+ return null;
5693
+ }
5694
+ lastCompressed = lastCompressed || { i: 0, lastCompressed: 0 };
5695
+ return updTbl
5696
+ .put(__assign(__assign({}, lastCompressed), { lastRun: new Date() }))
5697
+ .then(function () { return lastCompressed; });
5698
+ });
5699
+ }),
5700
+ ]).then(function (_a) {
5701
+ var _b = __read(_a, 2), syncers = _b[0], stamp = _b[1];
5702
+ if (!stamp)
5703
+ return;
5704
+ var lastCompressedUpdate = stamp.lastCompressed;
5705
+ var unsyncedFrom = Math.min.apply(Math, __spreadArray([], __read(syncers.map(function (s) {
5706
+ return Math.min(s.unsentFrom || Infinity, s.receivedUntil != null ? s.receivedUntil + 1 : Infinity);
5707
+ })), false));
5708
+ return updTbl
5709
+ .where('i')
5710
+ .between(lastCompressedUpdate, Infinity, false)
5711
+ .toArray(function (addedUpdates) {
5712
+ var e_3, _a;
5713
+ if (addedUpdates.length === 0)
5714
+ return;
5715
+ var docsToCompress = [];
5716
+ var lastUpdateToCompress = lastCompressedUpdate;
5717
+ var _loop_2 = function (j) {
5718
+ var updateRow = addedUpdates[j];
5719
+ var i = updateRow.i, f = updateRow.f, k = updateRow.k;
5720
+ if (i >= unsyncedFrom && f & 0x01)
5721
+ return "break";
5722
+ var entry = docsToCompress.find(function (entry) { return cmp(entry.docId, k) === 0; });
5723
+ if (entry)
5724
+ entry.updates.push(updateRow);
5725
+ else
5726
+ docsToCompress.push({ docId: k, updates: [updateRow] });
5727
+ lastUpdateToCompress = i;
5728
+ };
5729
+ for (var j = 0; j < addedUpdates.length; ++j) {
5730
+ var state_1 = _loop_2(j);
5731
+ if (state_1 === "break")
5732
+ break;
5733
+ }
5734
+ if (lastUpdateToCompress === lastCompressedUpdate)
5735
+ return;
5736
+ var p = Promise.resolve();
5737
+ var _loop_3 = function (docId, updates) {
5738
+ p = p.then(function () {
5739
+ return compressUpdatesForDoc(db, updatesTable, docId, updates);
5740
+ });
5741
+ };
5742
+ try {
5743
+ for (var docsToCompress_1 = __values(docsToCompress), docsToCompress_1_1 = docsToCompress_1.next(); !docsToCompress_1_1.done; docsToCompress_1_1 = docsToCompress_1.next()) {
5744
+ var _b = docsToCompress_1_1.value, docId = _b.docId, updates = _b.updates;
5745
+ _loop_3(docId, updates);
5746
+ }
5747
+ }
5748
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
5749
+ finally {
5750
+ try {
5751
+ if (docsToCompress_1_1 && !docsToCompress_1_1.done && (_a = docsToCompress_1.return)) _a.call(docsToCompress_1);
5752
+ }
5753
+ finally { if (e_3) throw e_3.error; }
5754
+ }
5755
+ return p.then(function () {
5756
+ return db.transaction('rw', updTbl, function () {
5757
+ return updTbl.get(0).then(function (current) {
5758
+ if (current && lastUpdateToCompress <= current.lastCompressed) {
5759
+ return;
5760
+ }
5761
+ return updTbl.put(__assign(__assign({}, current), { lastCompressed: lastUpdateToCompress }));
5762
+ });
5763
+ });
5764
+ });
5765
+ });
5766
+ });
5767
+ }
5768
+ function compressUpdatesForDoc(db, updatesTable, parentId, addedUpdatesToCompress) {
5769
+ if (addedUpdatesToCompress.length < 1)
5770
+ throw new Error('Invalid input');
5771
+ return db.transaction('rw', updatesTable, function (tx) {
5772
+ var updTbl = tx.table(updatesTable);
5773
+ return updTbl.where({ k: parentId }).first(function (mainUpdate) {
5774
+ var updates = [mainUpdate].concat(addedUpdatesToCompress.filter(function (u) { return u.i !== mainUpdate.i; }));
5775
+ var Y = getYLibrary(db);
5776
+ var doc = new Y.Doc({ gc: true });
5777
+ updates.forEach(function (update) {
5778
+ Y.applyUpdateV2(doc, update.u);
5779
+ });
5780
+ var compressedUpdate = Y.encodeStateAsUpdateV2(doc);
5781
+ var lastUpdate = updates.pop();
5782
+ return updTbl
5783
+ .put({
5784
+ i: lastUpdate.i,
5785
+ k: parentId,
5786
+ u: compressedUpdate,
5787
+ })
5788
+ .then(function () { return updTbl.bulkDelete(updates.map(function (update) { return update.i; })); });
5789
+ });
5790
+ });
5791
+ }
5792
+
5793
+ var GC_DELAY = 10000;
5794
+ var GC_INTERVAL = 300000;
5795
+ function periodicGC(db) {
5796
+ var timer = null;
5797
+ db.on('ready', function (db) {
5798
+ if (db.tables.some(function (tbl) { return tbl.schema.yProps; })) {
5799
+ var gc_1 = function () {
5800
+ if (!db.isOpen())
5801
+ return;
5802
+ compressYDocs(db, GC_INTERVAL).catch(function (err) {
5803
+ if (err && err.name === 'DatabaseClosedError')
5804
+ return;
5805
+ console.debug('Error during periodic GC', err);
5806
+ }).then(function () {
5807
+ timer = setTimeout(gc_1, GC_INTERVAL);
5808
+ });
5809
+ };
5810
+ timer = setTimeout(gc_1, GC_DELAY);
5811
+ }
5812
+ }, true);
5813
+ db.on('close', function () {
5814
+ if (timer)
5815
+ clearTimeout(timer);
5816
+ timer = null;
5817
+ });
5818
+ }
5819
+
5238
5820
  var Dexie$1 = (function () {
5239
5821
  function Dexie(name, options) {
5240
5822
  var _this = this;
@@ -5276,7 +5858,18 @@
5276
5858
  });
5277
5859
  this._state = state;
5278
5860
  this.name = name;
5279
- this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] });
5861
+ this.on = Events(this, "populate", "blocked", "versionchange", "close", "y", { ready: [promisableChain, nop] });
5862
+ this.once = function (event, callback) {
5863
+ var fn = function () {
5864
+ var args = [];
5865
+ for (var _i = 0; _i < arguments.length; _i++) {
5866
+ args[_i] = arguments[_i];
5867
+ }
5868
+ _this.on(event).unsubscribe(fn);
5869
+ callback.apply(_this, args);
5870
+ };
5871
+ return _this.on(event, fn);
5872
+ };
5280
5873
  this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {
5281
5874
  return function (subscriber, bSticky) {
5282
5875
  Dexie.vip(function () {
@@ -5355,6 +5948,8 @@
5355
5948
  }
5356
5949
  });
5357
5950
  this.vip = vipDB;
5951
+ if ((options === null || options === void 0 ? void 0 : options.Y) && (options === null || options === void 0 ? void 0 : options.gc) !== false)
5952
+ periodicGC(this);
5358
5953
  addons.forEach(function (addon) { return addon(_this); });
5359
5954
  }
5360
5955
  Dexie.prototype.version = function (versionNumber) {
@@ -5417,6 +6012,7 @@
5417
6012
  function () { return dexieOpen(_this); });
5418
6013
  };
5419
6014
  Dexie.prototype._close = function () {
6015
+ this.on.close.fire(new CustomEvent('close'));
5420
6016
  var state = this._state;
5421
6017
  var idx = connections.indexOf(this);
5422
6018
  if (idx >= 0)
@@ -5574,6 +6170,9 @@
5574
6170
  }
5575
6171
  return this._allTables[tableName];
5576
6172
  };
6173
+ Dexie.prototype.gc = function () {
6174
+ return compressYDocs(this);
6175
+ };
5577
6176
  return Dexie;
5578
6177
  }());
5579
6178
 
@@ -5874,6 +6473,175 @@
5874
6473
  return new PropModification({ replacePrefix: [a, b] });
5875
6474
  }
5876
6475
 
6476
+ function observeYDocUpdates(provider, doc, db, parentTableName, updatesTableName, parentId, Y) {
6477
+ var lastUpdateId = 0;
6478
+ var initial = true;
6479
+ var subscription = liveQuery(function () {
6480
+ throwIfDestroyed(doc);
6481
+ var updatesTable = db.table(updatesTableName);
6482
+ return Promise.all([
6483
+ (lastUpdateId > 0
6484
+ ? updatesTable
6485
+ .where('i')
6486
+ .between(lastUpdateId, Infinity, false)
6487
+ .toArray()
6488
+ .then(function (updates) {
6489
+ return updates.filter(function (update) { return cmp(update.k, parentId) === 0; });
6490
+ })
6491
+ : updatesTable.where({ k: parentId }).toArray()).then(function (updates) {
6492
+ return updates;
6493
+ }),
6494
+ db.table(parentTableName).where(':id').equals(parentId).toArray(),
6495
+ ]);
6496
+ }).subscribe(function (_a) {
6497
+ var _b = __read(_a, 2), updates = _b[0], parentRow = _b[1];
6498
+ if (updates.length > 0)
6499
+ lastUpdateId = updates[updates.length - 1].i;
6500
+ if (parentRow.length === 0) {
6501
+ doc.destroy();
6502
+ return;
6503
+ }
6504
+ throwIfDestroyed(doc);
6505
+ if (updates.length > 0) {
6506
+ Y.transact(doc, function () {
6507
+ updates.forEach(function (update) {
6508
+ try {
6509
+ DexieYProvider.currentUpdateRow = update;
6510
+ Y.applyUpdateV2(doc, update.u);
6511
+ }
6512
+ finally {
6513
+ DexieYProvider.currentUpdateRow = null;
6514
+ }
6515
+ });
6516
+ }, provider, false);
6517
+ }
6518
+ if (initial) {
6519
+ initial = false;
6520
+ doc.emit('load', [doc]);
6521
+ }
6522
+ }, function (error) {
6523
+ provider.on('error').fire(error);
6524
+ });
6525
+ var onUpdate = function (update, origin) {
6526
+ if (origin === provider)
6527
+ return;
6528
+ db.table(updatesTableName)
6529
+ .add({
6530
+ k: parentId,
6531
+ u: update,
6532
+ f: 1,
6533
+ })
6534
+ .then(function (i) {
6535
+ if (i === lastUpdateId - 1)
6536
+ ++lastUpdateId;
6537
+ })
6538
+ .catch(function (error) {
6539
+ provider.on('error').fire(error);
6540
+ });
6541
+ };
6542
+ var stopObserving = function () {
6543
+ subscription.unsubscribe();
6544
+ doc.off('updateV2', onUpdate);
6545
+ doc.off('destroy', stopObserving);
6546
+ };
6547
+ doc.on('updateV2', onUpdate);
6548
+ doc.on('destroy', stopObserving);
6549
+ return stopObserving;
6550
+ }
6551
+
6552
+ var wm = new WeakMap();
6553
+ function createEvents() {
6554
+ return Events(null, 'load', 'sync', 'error');
6555
+ }
6556
+ var DexieYProvider = (function () {
6557
+ function DexieYProvider(doc) {
6558
+ var _this = this;
6559
+ this.refCount = 1;
6560
+ this.cleanupHandlers = [];
6561
+ this.destroyed = false;
6562
+ this.on = createEvents();
6563
+ this.doc = doc;
6564
+ this.off = function (name, f) { var _a; return (_a = _this.on[name]) === null || _a === void 0 ? void 0 : _a.unsubscribe(f); };
6565
+ this.whenLoaded = new Promise(function (resolve, reject) {
6566
+ _this.on('load', resolve);
6567
+ _this.on('error', reject);
6568
+ });
6569
+ this.whenSynced = new Promise(function (resolve, reject) {
6570
+ _this.on('sync', resolve);
6571
+ _this.on('error', reject);
6572
+ });
6573
+ if ('dispose' in Symbol) {
6574
+ this[Symbol.dispose] =
6575
+ function () { return DexieYProvider.release(doc); };
6576
+ }
6577
+ doc.on('load', function () { return _this.on('load').fire(); });
6578
+ doc.on('sync', function (sync) { return sync !== false && _this.on('sync').fire(); });
6579
+ doc.on('destroy', this.destroy.bind(this));
6580
+ var _a = doc.meta || {}, db = _a.db, parentTable = _a.parentTable, parentId = _a.parentId, updatesTable = _a.updatesTable;
6581
+ if (db && parentTable && updatesTable) {
6582
+ if (!db.table(parentTable) || !db.table(updatesTable)) {
6583
+ throw new Error("Table ".concat(parentTable, " or ").concat(updatesTable, " not found in db"));
6584
+ }
6585
+ throwIfDestroyed(doc);
6586
+ var Y = getYLibrary(db);
6587
+ this.stopObserving = observeYDocUpdates(this, doc, db, parentTable, updatesTable, parentId, Y);
6588
+ db.on.y.fire(this, Y);
6589
+ }
6590
+ }
6591
+ DexieYProvider.load = function (doc) {
6592
+ var p = wm.get(doc);
6593
+ if (p) {
6594
+ ++p.refCount;
6595
+ }
6596
+ else {
6597
+ p = new DexieYProvider(doc);
6598
+ wm.set(doc, p);
6599
+ }
6600
+ return p;
6601
+ };
6602
+ DexieYProvider.release = function (doc, options) {
6603
+ if (destroyedDocs.has(doc))
6604
+ return;
6605
+ var p = wm.get(doc);
6606
+ if (p) {
6607
+ if (--p.refCount <= 0) {
6608
+ if (isNaN(options === null || options === void 0 ? void 0 : options.gracePeriod)) {
6609
+ doc.destroy();
6610
+ }
6611
+ else {
6612
+ setTimeout(function () { return p.refCount || doc.destroy(); },
6613
+ options.gracePeriod
6614
+ );
6615
+ }
6616
+ }
6617
+ }
6618
+ else {
6619
+ doc.destroy();
6620
+ }
6621
+ };
6622
+ DexieYProvider.for = function (doc) {
6623
+ return wm.get(doc);
6624
+ };
6625
+ DexieYProvider.prototype.destroy = function () {
6626
+ var _a;
6627
+ wm.delete(this.doc);
6628
+ this.doc = null;
6629
+ this.destroyed = true;
6630
+ this.refCount = 0;
6631
+ (_a = this.stopObserving) === null || _a === void 0 ? void 0 : _a.call(this);
6632
+ this.on = createEvents();
6633
+ this.cleanupHandlers.forEach(function (cleanup) { return cleanup(); });
6634
+ };
6635
+ DexieYProvider.prototype.addCleanupHandler = function (cleanupHandler) {
6636
+ this.cleanupHandlers.push(typeof cleanupHandler === 'function'
6637
+ ? cleanupHandler
6638
+ : function () { return cleanupHandler.unsubscribe(); });
6639
+ };
6640
+ DexieYProvider.getDocCache = getDocCache;
6641
+ DexieYProvider.currentUpdateRow = null;
6642
+ return DexieYProvider;
6643
+ }());
6644
+
5877
6645
  DexiePromise.rejectionMapper = mapError;
5878
6646
  setDebug(debug);
5879
6647
 
@@ -5891,7 +6659,8 @@
5891
6659
  'default': Dexie$1,
5892
6660
  RangeSet: RangeSet,
5893
6661
  mergeRanges: mergeRanges,
5894
- rangesOverlap: rangesOverlap
6662
+ rangesOverlap: rangesOverlap,
6663
+ DexieYProvider: DexieYProvider
5895
6664
  });
5896
6665
 
5897
6666
  __assign(Dexie$1, namedExports, { default: Dexie$1 });