dexie 4.0.8 → 4.1.0-alpha.2

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.mjs 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.2, Fri Oct 04 2024
8
8
  *
9
9
  * https://dexie.org
10
10
  *
@@ -46,6 +46,33 @@ var __assign = function() {
46
46
  };
47
47
  return __assign.apply(this, arguments);
48
48
  };
49
+ function __values(o) {
50
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
51
+ if (m) return m.call(o);
52
+ if (o && typeof o.length === "number") return {
53
+ next: function () {
54
+ if (o && i >= o.length) o = void 0;
55
+ return { value: o && o[i++], done: !o };
56
+ }
57
+ };
58
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
59
+ }
60
+ function __read(o, n) {
61
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
62
+ if (!m) return o;
63
+ var i = m.call(o), r, ar = [], e;
64
+ try {
65
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
66
+ }
67
+ catch (error) { e = { error: error }; }
68
+ finally {
69
+ try {
70
+ if (r && !r.done && (m = i["return"])) m.call(i);
71
+ }
72
+ finally { if (e) throw e.error; }
73
+ }
74
+ return ar;
75
+ }
49
76
  function __spreadArray(to, from, pack) {
50
77
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
51
78
  if (ar || !(i in from)) {
@@ -1144,7 +1171,7 @@ function tempTransaction(db, mode, storeNames, fn) {
1144
1171
  }
1145
1172
  }
1146
1173
 
1147
- var DEXIE_VERSION = '4.0.8';
1174
+ var DEXIE_VERSION = '4.1.0-alpha.2';
1148
1175
  var maxString = String.fromCharCode(65535);
1149
1176
  var minKey = -Infinity;
1150
1177
  var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.";
@@ -1262,6 +1289,95 @@ function getUint8Array(a) {
1262
1289
  return new Uint8Array(a);
1263
1290
  }
1264
1291
 
1292
+ function getDocCache(db) {
1293
+ var _a;
1294
+ var _b;
1295
+ return (_a = (_b = db._novip)['_docCache']) !== null && _a !== void 0 ? _a : (_b['_docCache'] = {
1296
+ cache: {},
1297
+ get size() {
1298
+ return Object.keys(this.cache).length;
1299
+ },
1300
+ find: function (table, primaryKey, ydocProp) {
1301
+ var cacheKey = getYDocCacheKey(table, primaryKey, ydocProp);
1302
+ var docRef = this.cache[cacheKey];
1303
+ return docRef ? docRef.deref() : undefined;
1304
+ },
1305
+ add: function (doc) {
1306
+ var _a = doc.meta, parentTable = _a.parentTable, parentId = _a.parentId, parentProp = _a.parentProp;
1307
+ if (!parentTable || !parentProp || parentId == null)
1308
+ throw new Error("Missing Dexie-related metadata in Y.Doc");
1309
+ var cacheKey = getYDocCacheKey(parentTable, parentId, parentProp);
1310
+ this.cache[cacheKey] = new WeakRef(doc);
1311
+ docRegistry.register(doc, { cache: this.cache, key: cacheKey });
1312
+ },
1313
+ delete: function (doc) {
1314
+ docRegistry.unregister(doc);
1315
+ delete this.cache[getYDocCacheKey(doc.meta.parentTable, doc.meta.parentId, doc.meta.parentProp)];
1316
+ },
1317
+ });
1318
+ }
1319
+ var docRegistry = new FinalizationRegistry(function (_a) {
1320
+ var cache = _a.cache, key = _a.key;
1321
+ delete cache[key];
1322
+ });
1323
+ var destroyedDocs = new WeakSet();
1324
+ function throwIfDestroyed(doc) {
1325
+ if (destroyedDocs.has(doc))
1326
+ throw new Error('Y.Doc has been destroyed');
1327
+ }
1328
+ function getYDocCacheKey(table, primaryKey, ydocProp) {
1329
+ return "".concat(table, "[").concat(primaryKey, "].").concat(ydocProp);
1330
+ }
1331
+
1332
+ function createYDocProperty(db, Y, table, prop, updatesTable) {
1333
+ var pkKeyPath = table.schema.primKey.keyPath;
1334
+ var docCache = getDocCache(db);
1335
+ return {
1336
+ get: function () {
1337
+ var id = getByKeyPath(this, pkKeyPath);
1338
+ var doc = docCache.find(table.name, id, prop);
1339
+ if (doc)
1340
+ return doc;
1341
+ doc = new Y.Doc({
1342
+ meta: {
1343
+ db: db,
1344
+ updatesTable: updatesTable,
1345
+ parentProp: prop,
1346
+ parentTable: table.name,
1347
+ parentId: id
1348
+ },
1349
+ });
1350
+ docCache.add(doc);
1351
+ doc.on('destroy', function () {
1352
+ destroyedDocs.add(doc);
1353
+ docCache.delete(doc);
1354
+ });
1355
+ return doc;
1356
+ },
1357
+ };
1358
+ }
1359
+
1360
+ function builtInDeletionTrigger(table, keys, res) {
1361
+ var yProps = table.schema.yProps;
1362
+ if (!yProps)
1363
+ return res;
1364
+ if (keys && res.numFailures > 0)
1365
+ keys = keys.filter(function (_, i) { return !res.failures[i]; });
1366
+ return Promise.all(yProps.map(function (_a) {
1367
+ var updatesTable = _a.updatesTable;
1368
+ return keys
1369
+ ? table.db.table(updatesTable).where('k').anyOf(keys).delete()
1370
+ : table.db.table(updatesTable).clear();
1371
+ })).then(function () { return res; });
1372
+ }
1373
+
1374
+ function getYLibrary(db) {
1375
+ var Y = db._options.Y;
1376
+ if (!Y)
1377
+ throw new exceptions.MissingAPI('Y library not supplied to Dexie constructor');
1378
+ return Y;
1379
+ }
1380
+
1265
1381
  var Table = (function () {
1266
1382
  function Table() {
1267
1383
  }
@@ -1341,8 +1457,8 @@ var Table = (function () {
1341
1457
  function equals(a, b) {
1342
1458
  return idb.cmp(a, b) === 0;
1343
1459
  }
1344
- var _a = keyPaths.reduce(function (_a, keyPath) {
1345
- var prevIndex = _a[0], prevFilterFn = _a[1];
1460
+ var _a = __read(keyPaths.reduce(function (_a, keyPath) {
1461
+ var _b = __read(_a, 2), prevIndex = _b[0], prevFilterFn = _b[1];
1346
1462
  var index = idxByName[keyPath];
1347
1463
  var value = indexOrCrit[keyPath];
1348
1464
  return [
@@ -1355,7 +1471,7 @@ var Table = (function () {
1355
1471
  } : function (x) { return equals(value, getByKeyPath(x, keyPath)); })
1356
1472
  : prevFilterFn
1357
1473
  ];
1358
- }, [null, null]), idx = _a[0], filterFunction = _a[1];
1474
+ }, [null, null]), 2), idx = _a[0], filterFunction = _a[1];
1359
1475
  return idx ?
1360
1476
  this.where(idx.name).equals(indexOrCrit[idx.keyPath])
1361
1477
  .filter(filterFunction) :
@@ -1393,6 +1509,7 @@ var Table = (function () {
1393
1509
  return this.toCollection().reverse();
1394
1510
  };
1395
1511
  Table.prototype.mapToClass = function (constructor) {
1512
+ var _this = this;
1396
1513
  var _a = this, db = _a.db, tableName = _a.name;
1397
1514
  this.schema.mappedClass = constructor;
1398
1515
  if (constructor.prototype instanceof Entity) {
@@ -1410,6 +1527,20 @@ var Table = (function () {
1410
1527
  return class_1;
1411
1528
  }(constructor));
1412
1529
  }
1530
+ if (this.schema.yProps) {
1531
+ var Y_1 = getYLibrary(db);
1532
+ constructor = (function (_super) {
1533
+ __extends(class_2, _super);
1534
+ function class_2() {
1535
+ return _super !== null && _super.apply(this, arguments) || this;
1536
+ }
1537
+ return class_2;
1538
+ }(constructor));
1539
+ this.schema.yProps.forEach(function (_a) {
1540
+ var prop = _a.prop, updatesTable = _a.updatesTable;
1541
+ Object.defineProperty(constructor.prototype, prop, createYDocProperty(db, Y_1, _this, prop, updatesTable));
1542
+ });
1543
+ }
1413
1544
  var inheritedProps = new Set();
1414
1545
  for (var proto = constructor.prototype; proto; proto = getProto(proto)) {
1415
1546
  Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); });
@@ -1491,12 +1622,14 @@ var Table = (function () {
1491
1622
  };
1492
1623
  Table.prototype.delete = function (key) {
1493
1624
  var _this = this;
1494
- return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); })
1495
- .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });
1625
+ return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] })
1626
+ .then(function (res) { return builtInDeletionTrigger(_this, [key], res); })
1627
+ .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); });
1496
1628
  };
1497
1629
  Table.prototype.clear = function () {
1498
1630
  var _this = this;
1499
- return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); })
1631
+ return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange })
1632
+ .then(function (res) { return builtInDeletionTrigger(_this, null, res); }); })
1500
1633
  .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });
1501
1634
  };
1502
1635
  Table.prototype.bulkGet = function (keys) {
@@ -1569,20 +1702,30 @@ var Table = (function () {
1569
1702
  var resultKeys = [];
1570
1703
  var resultObjs = [];
1571
1704
  keysAndChanges.forEach(function (_a, idx) {
1705
+ var e_1, _b;
1572
1706
  var key = _a.key, changes = _a.changes;
1573
1707
  var obj = objs[idx];
1574
1708
  if (obj) {
1575
- for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) {
1576
- var keyPath = _b[_i];
1577
- var value = changes[keyPath];
1578
- if (keyPath === _this.schema.primKey.keyPath) {
1579
- if (cmp(value, key) !== 0) {
1580
- throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()");
1709
+ try {
1710
+ for (var _c = __values(Object.keys(changes)), _d = _c.next(); !_d.done; _d = _c.next()) {
1711
+ var keyPath = _d.value;
1712
+ var value = changes[keyPath];
1713
+ if (keyPath === _this.schema.primKey.keyPath) {
1714
+ if (cmp(value, key) !== 0) {
1715
+ throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()");
1716
+ }
1717
+ }
1718
+ else {
1719
+ setByKeyPath(obj, keyPath, value);
1581
1720
  }
1582
1721
  }
1583
- else {
1584
- setByKeyPath(obj, keyPath, value);
1722
+ }
1723
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1724
+ finally {
1725
+ try {
1726
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1585
1727
  }
1728
+ finally { if (e_1) throw e_1.error; }
1586
1729
  }
1587
1730
  offsetMap.push(idx);
1588
1731
  resultKeys.push(key);
@@ -1602,17 +1745,27 @@ var Table = (function () {
1602
1745
  }
1603
1746
  })
1604
1747
  .then(function (_a) {
1748
+ var e_2, _b;
1605
1749
  var numFailures = _a.numFailures, failures = _a.failures;
1606
1750
  if (numFailures === 0)
1607
1751
  return numEntries;
1608
- for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) {
1609
- var offset = _b[_i];
1610
- var mappedOffset = offsetMap[Number(offset)];
1611
- if (mappedOffset != null) {
1612
- var failure = failures[offset];
1613
- delete failures[offset];
1614
- failures[mappedOffset] = failure;
1752
+ try {
1753
+ for (var _c = __values(Object.keys(failures)), _d = _c.next(); !_d.done; _d = _c.next()) {
1754
+ var offset = _d.value;
1755
+ var mappedOffset = offsetMap[Number(offset)];
1756
+ if (mappedOffset != null) {
1757
+ var failure = failures[offset];
1758
+ delete failures[offset];
1759
+ failures[mappedOffset] = failure;
1760
+ }
1761
+ }
1762
+ }
1763
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1764
+ finally {
1765
+ try {
1766
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1615
1767
  }
1768
+ finally { if (e_2) throw e_2.error; }
1616
1769
  }
1617
1770
  throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures);
1618
1771
  });
@@ -1623,7 +1776,8 @@ var Table = (function () {
1623
1776
  var _this = this;
1624
1777
  var numKeys = keys.length;
1625
1778
  return this._trans('readwrite', function (trans) {
1626
- return _this.core.mutate({ trans: trans, type: 'delete', keys: keys });
1779
+ return _this.core.mutate({ trans: trans, type: 'delete', keys: keys })
1780
+ .then(function (res) { return builtInDeletionTrigger(_this, keys, res); });
1627
1781
  }).then(function (_a) {
1628
1782
  var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures;
1629
1783
  if (numFailures === 0)
@@ -1807,7 +1961,7 @@ var PropModification = (function () {
1807
1961
  if (this.add !== undefined) {
1808
1962
  var term = this.add;
1809
1963
  if (isArray(term)) {
1810
- return __spreadArray(__spreadArray([], (isArray(value) ? value : []), true), term, true).sort();
1964
+ return __spreadArray(__spreadArray([], __read((isArray(value) ? value : [])), false), __read(term), false).sort();
1811
1965
  }
1812
1966
  if (typeof term === 'number')
1813
1967
  return (Number(value) || 0) + term;
@@ -2140,52 +2294,65 @@ var Collection = (function () {
2140
2294
  var successCount = 0;
2141
2295
  var failedKeys = [];
2142
2296
  var applyMutateResult = function (expectedCount, res) {
2297
+ var e_1, _a;
2143
2298
  var failures = res.failures, numFailures = res.numFailures;
2144
2299
  successCount += expectedCount - numFailures;
2145
- for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) {
2146
- var pos = _a[_i];
2147
- totalFailures.push(failures[pos]);
2300
+ try {
2301
+ for (var _b = __values(keys(failures)), _c = _b.next(); !_c.done; _c = _b.next()) {
2302
+ var pos = _c.value;
2303
+ totalFailures.push(failures[pos]);
2304
+ }
2305
+ }
2306
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2307
+ finally {
2308
+ try {
2309
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2310
+ }
2311
+ finally { if (e_1) throw e_1.error; }
2148
2312
  }
2149
2313
  };
2314
+ var isUnconditionalDelete = changes === deleteCallback;
2150
2315
  return _this.clone().primaryKeys().then(function (keys) {
2151
2316
  var criteria = isPlainKeyRange(ctx) &&
2152
2317
  ctx.limit === Infinity &&
2153
- (typeof changes !== 'function' || changes === deleteCallback) && {
2318
+ (typeof changes !== 'function' || isUnconditionalDelete) && {
2154
2319
  index: ctx.index,
2155
2320
  range: ctx.range
2156
2321
  };
2157
2322
  var nextChunk = function (offset) {
2158
2323
  var count = Math.min(limit, keys.length - offset);
2159
- return coreTable.getMany({
2324
+ var keysInChunk = keys.slice(offset, offset + count);
2325
+ return (isUnconditionalDelete ? Promise.resolve([]) : coreTable.getMany({
2160
2326
  trans: trans,
2161
- keys: keys.slice(offset, offset + count),
2327
+ keys: keysInChunk,
2162
2328
  cache: "immutable"
2163
- }).then(function (values) {
2329
+ })).then(function (values) {
2164
2330
  var addValues = [];
2165
2331
  var putValues = [];
2166
2332
  var putKeys = outbound ? [] : null;
2167
- var deleteKeys = [];
2168
- for (var i = 0; i < count; ++i) {
2169
- var origValue = values[i];
2170
- var ctx_1 = {
2171
- value: deepClone(origValue),
2172
- primKey: keys[offset + i]
2173
- };
2174
- if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {
2175
- if (ctx_1.value == null) {
2176
- deleteKeys.push(keys[offset + i]);
2177
- }
2178
- else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {
2179
- deleteKeys.push(keys[offset + i]);
2180
- addValues.push(ctx_1.value);
2181
- }
2182
- else {
2183
- putValues.push(ctx_1.value);
2184
- if (outbound)
2185
- putKeys.push(keys[offset + i]);
2333
+ var deleteKeys = isUnconditionalDelete ? keysInChunk : [];
2334
+ if (!isUnconditionalDelete)
2335
+ for (var i = 0; i < count; ++i) {
2336
+ var origValue = values[i];
2337
+ var ctx_1 = {
2338
+ value: deepClone(origValue),
2339
+ primKey: keys[offset + i]
2340
+ };
2341
+ if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {
2342
+ if (ctx_1.value == null) {
2343
+ deleteKeys.push(keys[offset + i]);
2344
+ }
2345
+ else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {
2346
+ deleteKeys.push(keys[offset + i]);
2347
+ addValues.push(ctx_1.value);
2348
+ }
2349
+ else {
2350
+ putValues.push(ctx_1.value);
2351
+ if (outbound)
2352
+ putKeys.push(keys[offset + i]);
2353
+ }
2186
2354
  }
2187
2355
  }
2188
- }
2189
2356
  return Promise.resolve(addValues.length > 0 &&
2190
2357
  coreTable.mutate({ trans: trans, type: 'add', values: addValues })
2191
2358
  .then(function (res) {
@@ -2203,14 +2370,15 @@ var Collection = (function () {
2203
2370
  changeSpec: typeof changes !== 'function'
2204
2371
  && changes,
2205
2372
  isAdditionalChunk: offset > 0
2206
- }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&
2373
+ }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && isUnconditionalDelete)) &&
2207
2374
  coreTable.mutate({
2208
2375
  trans: trans,
2209
2376
  type: 'delete',
2210
2377
  keys: deleteKeys,
2211
2378
  criteria: criteria,
2212
2379
  isAdditionalChunk: offset > 0
2213
- }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {
2380
+ }).then(function (res) { return builtInDeletionTrigger(ctx.table, deleteKeys, res); })
2381
+ .then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {
2214
2382
  return keys.length > offset + count && nextChunk(offset + limit);
2215
2383
  });
2216
2384
  });
@@ -2226,6 +2394,7 @@ var Collection = (function () {
2226
2394
  Collection.prototype.delete = function () {
2227
2395
  var ctx = this._ctx, range = ctx.range;
2228
2396
  if (isPlainKeyRange(ctx) &&
2397
+ !ctx.table.schema.yProps &&
2229
2398
  (ctx.isPrimKey || range.type === 3 ))
2230
2399
  {
2231
2400
  return this._write(function (trans) {
@@ -2234,7 +2403,7 @@ var Collection = (function () {
2234
2403
  return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) {
2235
2404
  return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange })
2236
2405
  .then(function (_a) {
2237
- var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures;
2406
+ var failures = _a.failures, numFailures = _a.numFailures;
2238
2407
  if (numFailures)
2239
2408
  throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures);
2240
2409
  return count - numFailures;
@@ -2836,6 +3005,13 @@ var Transaction = (function () {
2836
3005
  function createTransactionConstructor(db) {
2837
3006
  return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) {
2838
3007
  var _this = this;
3008
+ if (mode !== 'readonly')
3009
+ storeNames.forEach(function (storeName) {
3010
+ var _a;
3011
+ var yProps = (_a = dbschema[storeName]) === null || _a === void 0 ? void 0 : _a.yProps;
3012
+ if (yProps)
3013
+ storeNames = storeNames.concat(yProps.map(function (p) { return p.updatesTable; }));
3014
+ });
2839
3015
  this.db = db;
2840
3016
  this.mode = mode;
2841
3017
  this.storeNames = storeNames;
@@ -2871,7 +3047,7 @@ function createTransactionConstructor(db) {
2871
3047
  });
2872
3048
  }
2873
3049
 
2874
- function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) {
3050
+ function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey, type) {
2875
3051
  return {
2876
3052
  name: name,
2877
3053
  keyPath: keyPath,
@@ -2879,7 +3055,8 @@ function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey
2879
3055
  multi: multi,
2880
3056
  auto: auto,
2881
3057
  compound: compound,
2882
- src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath)
3058
+ src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath),
3059
+ type: type
2883
3060
  };
2884
3061
  }
2885
3062
  function nameFromKeyPath(keyPath) {
@@ -2888,13 +3065,17 @@ function nameFromKeyPath(keyPath) {
2888
3065
  keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : "";
2889
3066
  }
2890
3067
 
2891
- function createTableSchema(name, primKey, indexes) {
3068
+ function createTableSchema(name, primKey, indexes, yProps) {
2892
3069
  return {
2893
3070
  name: name,
2894
3071
  primKey: primKey,
2895
3072
  indexes: indexes,
2896
3073
  mappedClass: null,
2897
- idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; })
3074
+ yProps: yProps === null || yProps === void 0 ? void 0 : yProps.map(function (prop) { return ({
3075
+ prop: prop,
3076
+ updatesTable: "$".concat(name, ".").concat(prop, "_updates"),
3077
+ }); }),
3078
+ idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }),
2898
3079
  };
2899
3080
  }
2900
3081
 
@@ -3047,11 +3228,11 @@ function createDBCore(db, IdbKeyRange, tmpTrans) {
3047
3228
  reqs.push(req = store.delete(makeIDBKeyRange(range)));
3048
3229
  }
3049
3230
  else {
3050
- var _a = isAddOrPut ?
3231
+ var _a = __read(isAddOrPut ?
3051
3232
  outbound ?
3052
3233
  [values, keys] :
3053
3234
  [values, null] :
3054
- [keys, null], args1 = _a[0], args2 = _a[1];
3235
+ [keys, null], 2), args1 = _a[0], args2 = _a[1];
3055
3236
  if (isAddOrPut) {
3056
3237
  for (var i = 0; i < length; ++i) {
3057
3238
  reqs.push(req = (args2 && args2[i] !== undefined ?
@@ -3376,6 +3557,7 @@ function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) {
3376
3557
  });
3377
3558
  }
3378
3559
  function patchCurrentVersion(db, idbUpgradeTrans) {
3560
+ var e_1, _a;
3379
3561
  createMissingTables(db._dbSchema, idbUpgradeTrans);
3380
3562
  if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) {
3381
3563
  idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version');
@@ -3395,11 +3577,20 @@ function patchCurrentVersion(db, idbUpgradeTrans) {
3395
3577
  addIndex(store, idx);
3396
3578
  });
3397
3579
  };
3398
- for (var _i = 0, _a = diff.change; _i < _a.length; _i++) {
3399
- var tableChange = _a[_i];
3400
- var state_1 = _loop_1(tableChange);
3401
- if (typeof state_1 === "object")
3402
- return state_1.value;
3580
+ try {
3581
+ for (var _b = __values(diff.change), _c = _b.next(); !_c.done; _c = _b.next()) {
3582
+ var tableChange = _c.value;
3583
+ var state_1 = _loop_1(tableChange);
3584
+ if (typeof state_1 === "object")
3585
+ return state_1.value;
3586
+ }
3587
+ }
3588
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3589
+ finally {
3590
+ try {
3591
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3592
+ }
3593
+ finally { if (e_1) throw e_1.error; }
3403
3594
  }
3404
3595
  }
3405
3596
  function getExistingVersion(db, trans, oldVersion) {
@@ -3638,10 +3829,15 @@ function adjustToExistingIndexNames(db, schema, idbtrans) {
3638
3829
  }
3639
3830
  function parseIndexSyntax(primKeyAndIndexes) {
3640
3831
  return primKeyAndIndexes.split(',').map(function (index, indexNum) {
3641
- index = index.trim();
3832
+ var _a;
3833
+ var typeSplit = index.split(':');
3834
+ var type = (_a = typeSplit[1]) === null || _a === void 0 ? void 0 : _a.trim();
3835
+ index = typeSplit[0].trim();
3836
+ if (type && type !== 'Y')
3837
+ throw new exceptions.Schema("Unsupported type '".concat(type, "'"));
3642
3838
  var name = index.replace(/([&*]|\+\+)/g, "");
3643
3839
  var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name;
3644
- return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0);
3840
+ return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0, type);
3645
3841
  });
3646
3842
  }
3647
3843
 
@@ -3649,40 +3845,66 @@ var Version = (function () {
3649
3845
  function Version() {
3650
3846
  }
3651
3847
  Version.prototype._parseStoresSpec = function (stores, outSchema) {
3848
+ var _this = this;
3652
3849
  keys(stores).forEach(function (tableName) {
3850
+ var e_1, _a, _b;
3653
3851
  if (stores[tableName] !== null) {
3654
3852
  var indexes = parseIndexSyntax(stores[tableName]);
3853
+ var yProps = indexes.filter(function (idx) { return idx.type === 'Y'; }).map(function (idx) { return idx.name; });
3854
+ indexes = indexes.filter(function (idx) { return idx.type !== 'Y'; });
3655
3855
  var primKey = indexes.shift();
3856
+ if (!primKey) {
3857
+ throw new exceptions.Schema('Invalid schema for table ' + tableName + ': ' + stores[tableName]);
3858
+ }
3656
3859
  primKey.unique = true;
3657
3860
  if (primKey.multi)
3658
- throw new exceptions.Schema("Primary key cannot be multi-valued");
3861
+ throw new exceptions.Schema('Primary key cannot be multiEntry*');
3659
3862
  indexes.forEach(function (idx) {
3660
3863
  if (idx.auto)
3661
- throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)");
3864
+ throw new exceptions.Schema('Only primary key can be marked as autoIncrement (++)');
3662
3865
  if (!idx.keyPath)
3663
- throw new exceptions.Schema("Index must have a name and cannot be an empty string");
3866
+ throw new exceptions.Schema('Index must have a name and cannot be an empty string');
3664
3867
  });
3665
- outSchema[tableName] = createTableSchema(tableName, primKey, indexes);
3868
+ var tblSchema = createTableSchema(tableName, primKey, indexes, yProps.length ? yProps : undefined);
3869
+ outSchema[tableName] = tblSchema;
3870
+ try {
3871
+ for (var _c = __values(tblSchema.yProps || []), _d = _c.next(); !_d.done; _d = _c.next()) {
3872
+ var yProp = _d.value;
3873
+ _this._parseStoresSpec((_b = {}, _b[yProp.updatesTable] = '++i,k', _b), outSchema);
3874
+ }
3875
+ }
3876
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3877
+ finally {
3878
+ try {
3879
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
3880
+ }
3881
+ finally { if (e_1) throw e_1.error; }
3882
+ }
3666
3883
  }
3667
3884
  });
3668
3885
  };
3669
3886
  Version.prototype.stores = function (stores) {
3670
3887
  var db = this.db;
3671
- this._cfg.storesSource = this._cfg.storesSource ?
3672
- extend(this._cfg.storesSource, stores) :
3673
- stores;
3888
+ this._cfg.storesSource = this._cfg.storesSource
3889
+ ? extend(this._cfg.storesSource, stores)
3890
+ : stores;
3674
3891
  var versions = db._versions;
3675
3892
  var storesSpec = {};
3676
3893
  var dbschema = {};
3677
3894
  versions.forEach(function (version) {
3678
3895
  extend(storesSpec, version._cfg.storesSource);
3679
- dbschema = (version._cfg.dbschema = {});
3896
+ dbschema = version._cfg.dbschema = {};
3680
3897
  version._parseStoresSpec(storesSpec, dbschema);
3681
3898
  });
3682
3899
  db._dbSchema = dbschema;
3683
3900
  removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);
3684
3901
  setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);
3685
3902
  db._storeNames = keys(dbschema);
3903
+ db._storeNames.forEach(function (tableName) {
3904
+ if (dbschema[tableName].yProps) {
3905
+ db.table(tableName).mapToClass(dbschema[tableName].mappedClass || Object);
3906
+ }
3907
+ });
3686
3908
  return this;
3687
3909
  };
3688
3910
  Version.prototype.upgrade = function (upgradeFunction) {
@@ -3961,19 +4183,29 @@ function signalSubscribersLazily(part, optimistic) {
3961
4183
  }
3962
4184
  }
3963
4185
  function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) {
4186
+ var e_1, _a;
3964
4187
  if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; }
3965
4188
  var queriesToSignal = new Set();
3966
4189
  if (updatedParts.all) {
3967
- for (var _i = 0, _a = Object.values(cache); _i < _a.length; _i++) {
3968
- var tblCache = _a[_i];
3969
- collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
4190
+ try {
4191
+ for (var _b = __values(Object.values(cache)), _c = _b.next(); !_c.done; _c = _b.next()) {
4192
+ var tblCache = _c.value;
4193
+ collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
4194
+ }
4195
+ }
4196
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4197
+ finally {
4198
+ try {
4199
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4200
+ }
4201
+ finally { if (e_1) throw e_1.error; }
3970
4202
  }
3971
4203
  }
3972
4204
  else {
3973
4205
  for (var key in updatedParts) {
3974
4206
  var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key);
3975
4207
  if (parts) {
3976
- var dbName = parts[1], tableName = parts[2];
4208
+ var _d = __read(parts, 3), dbName = _d[1], tableName = _d[2];
3977
4209
  var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)];
3978
4210
  if (tblCache)
3979
4211
  collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
@@ -3983,26 +4215,54 @@ function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) {
3983
4215
  queriesToSignal.forEach(function (requery) { return requery(); });
3984
4216
  }
3985
4217
  function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) {
4218
+ var e_2, _a, e_3, _b, e_4, _c;
3986
4219
  var updatedEntryLists = [];
3987
- for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) {
3988
- var _b = _a[_i], indexName = _b[0], entries = _b[1];
3989
- var filteredEntries = [];
3990
- for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) {
3991
- var entry = entries_1[_c];
3992
- if (obsSetsOverlap(updatedParts, entry.obsSet)) {
3993
- entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });
4220
+ try {
4221
+ for (var _d = __values(Object.entries(tblCache.queries.query)), _e = _d.next(); !_e.done; _e = _d.next()) {
4222
+ var _f = __read(_e.value, 2), indexName = _f[0], entries = _f[1];
4223
+ var filteredEntries = [];
4224
+ try {
4225
+ 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()) {
4226
+ var entry = entries_1_1.value;
4227
+ if (obsSetsOverlap(updatedParts, entry.obsSet)) {
4228
+ entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });
4229
+ }
4230
+ else if (deleteAffectedCacheEntries) {
4231
+ filteredEntries.push(entry);
4232
+ }
4233
+ }
3994
4234
  }
3995
- else if (deleteAffectedCacheEntries) {
3996
- filteredEntries.push(entry);
4235
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
4236
+ finally {
4237
+ try {
4238
+ if (entries_1_1 && !entries_1_1.done && (_b = entries_1.return)) _b.call(entries_1);
4239
+ }
4240
+ finally { if (e_3) throw e_3.error; }
3997
4241
  }
4242
+ if (deleteAffectedCacheEntries)
4243
+ updatedEntryLists.push([indexName, filteredEntries]);
4244
+ }
4245
+ }
4246
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
4247
+ finally {
4248
+ try {
4249
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
3998
4250
  }
3999
- if (deleteAffectedCacheEntries)
4000
- updatedEntryLists.push([indexName, filteredEntries]);
4251
+ finally { if (e_2) throw e_2.error; }
4001
4252
  }
4002
4253
  if (deleteAffectedCacheEntries) {
4003
- for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) {
4004
- var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1];
4005
- tblCache.queries.query[indexName] = filteredEntries;
4254
+ try {
4255
+ for (var updatedEntryLists_1 = __values(updatedEntryLists), updatedEntryLists_1_1 = updatedEntryLists_1.next(); !updatedEntryLists_1_1.done; updatedEntryLists_1_1 = updatedEntryLists_1.next()) {
4256
+ var _g = __read(updatedEntryLists_1_1.value, 2), indexName = _g[0], filteredEntries = _g[1];
4257
+ tblCache.queries.query[indexName] = filteredEntries;
4258
+ }
4259
+ }
4260
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
4261
+ finally {
4262
+ try {
4263
+ if (updatedEntryLists_1_1 && !updatedEntryLists_1_1.done && (_c = updatedEntryLists_1.return)) _c.call(updatedEntryLists_1);
4264
+ }
4265
+ finally { if (e_4) throw e_4.error; }
4006
4266
  }
4007
4267
  }
4008
4268
  }
@@ -4253,6 +4513,7 @@ function pad(a, value, count) {
4253
4513
  }
4254
4514
  function createVirtualIndexMiddleware(down) {
4255
4515
  return __assign(__assign({}, down), { table: function (tableName) {
4516
+ var e_1, _a;
4256
4517
  var table = down.table(tableName);
4257
4518
  var schema = table.schema;
4258
4519
  var indexLookup = {};
@@ -4280,9 +4541,18 @@ function createVirtualIndexMiddleware(down) {
4280
4541
  }
4281
4542
  var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);
4282
4543
  indexLookup[":id"] = [primaryKey];
4283
- for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) {
4284
- var index = _a[_i];
4285
- addVirtualIndexes(index.keyPath, 0, index);
4544
+ try {
4545
+ for (var _b = __values(schema.indexes), _c = _b.next(); !_c.done; _c = _b.next()) {
4546
+ var index = _c.value;
4547
+ addVirtualIndexes(index.keyPath, 0, index);
4548
+ }
4549
+ }
4550
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4551
+ finally {
4552
+ try {
4553
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4554
+ }
4555
+ finally { if (e_1) throw e_1.error; }
4286
4556
  }
4287
4557
  function findBestIndex(keyPath) {
4288
4558
  var result = indexLookup[getKeyPathAlias(keyPath)];
@@ -4442,9 +4712,9 @@ var hooksMiddleware = {
4442
4712
  throw new Error("Keys missing");
4443
4713
  req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req);
4444
4714
  if (req.type !== 'delete')
4445
- req.values = __spreadArray([], req.values, true);
4715
+ req.values = __spreadArray([], __read(req.values), false);
4446
4716
  if (req.keys)
4447
- req.keys = __spreadArray([], req.keys, true);
4717
+ req.keys = __spreadArray([], __read(req.keys), false);
4448
4718
  return getExistingValues(downTable, req, keys).then(function (existingValues) {
4449
4719
  var contexts = keys.map(function (key, i) {
4450
4720
  var existingValue = existingValues[i];
@@ -4633,13 +4903,13 @@ var observabilityMiddleware = {
4633
4903
  var pkRangeSet = getRangeSet("");
4634
4904
  var delsRangeSet = getRangeSet(":dels");
4635
4905
  var type = req.type;
4636
- var _a = req.type === "deleteRange"
4906
+ var _a = __read(req.type === "deleteRange"
4637
4907
  ? [req.range]
4638
4908
  : req.type === "delete"
4639
4909
  ? [req.keys]
4640
4910
  : req.values.length < 50
4641
4911
  ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values]
4642
- : [], keys = _a[0], newObjs = _a[1];
4912
+ : [], 2), keys = _a[0], newObjs = _a[1];
4643
4913
  var oldCache = req.trans["_cache"];
4644
4914
  if (isArray(keys)) {
4645
4915
  pkRangeSet.addKeys(keys);
@@ -4708,7 +4978,7 @@ var observabilityMiddleware = {
4708
4978
  };
4709
4979
  var pkRangeSet_1 = getRangeSet("");
4710
4980
  var delsRangeSet_1 = getRangeSet(":dels");
4711
- var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1];
4981
+ var _a = __read(readSubscribers[method](req), 2), queriedIndex = _a[0], queriedRanges = _a[1];
4712
4982
  if (method === 'query' && queriedIndex.isPrimaryKey && !req.values) {
4713
4983
  delsRangeSet_1.add(queriedRanges);
4714
4984
  }
@@ -5032,60 +5302,106 @@ var cacheMiddleware = {
5032
5302
  var ac_1 = new AbortController();
5033
5303
  var signal = ac_1.signal;
5034
5304
  var endTransaction = function (wasCommitted) { return function () {
5305
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e;
5035
5306
  ac_1.abort();
5036
5307
  if (mode === 'readwrite') {
5037
5308
  var affectedSubscribers_1 = new Set();
5038
- for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) {
5039
- var storeName = stores_1[_i];
5040
- var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)];
5041
- if (tblCache) {
5042
- var table = core.table(storeName);
5043
- var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });
5044
- if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {
5045
- for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) {
5046
- var entries = _b[_a];
5047
- for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) {
5048
- var entry = _d[_c];
5049
- if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {
5050
- delArrayItem(entries, entry);
5051
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5309
+ try {
5310
+ for (var stores_1 = __values(stores), stores_1_1 = stores_1.next(); !stores_1_1.done; stores_1_1 = stores_1.next()) {
5311
+ var storeName = stores_1_1.value;
5312
+ var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)];
5313
+ if (tblCache) {
5314
+ var table = core.table(storeName);
5315
+ var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });
5316
+ if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {
5317
+ try {
5318
+ for (var _f = (e_2 = void 0, __values(Object.values(tblCache.queries.query))), _g = _f.next(); !_g.done; _g = _f.next()) {
5319
+ var entries = _g.value;
5320
+ try {
5321
+ for (var _h = (e_3 = void 0, __values(entries.slice())), _j = _h.next(); !_j.done; _j = _h.next()) {
5322
+ var entry = _j.value;
5323
+ if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {
5324
+ delArrayItem(entries, entry);
5325
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5326
+ }
5327
+ }
5328
+ }
5329
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
5330
+ finally {
5331
+ try {
5332
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
5333
+ }
5334
+ finally { if (e_3) throw e_3.error; }
5335
+ }
5052
5336
  }
5053
5337
  }
5338
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5339
+ finally {
5340
+ try {
5341
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
5342
+ }
5343
+ finally { if (e_2) throw e_2.error; }
5344
+ }
5054
5345
  }
5055
- }
5056
- else if (ops.length > 0) {
5057
- tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });
5058
- for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) {
5059
- var entries = _f[_e];
5060
- for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) {
5061
- var entry = _h[_g];
5062
- if (entry.res != null &&
5063
- idbtrans.mutatedParts
5346
+ else if (ops.length > 0) {
5347
+ tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });
5348
+ try {
5349
+ for (var _k = (e_4 = void 0, __values(Object.values(tblCache.queries.query))), _l = _k.next(); !_l.done; _l = _k.next()) {
5350
+ var entries = _l.value;
5351
+ try {
5352
+ for (var _m = (e_5 = void 0, __values(entries.slice())), _o = _m.next(); !_o.done; _o = _m.next()) {
5353
+ var entry = _o.value;
5354
+ if (entry.res != null &&
5355
+ idbtrans.mutatedParts
5064
5356
  ) {
5065
- if (wasCommitted && !entry.dirty) {
5066
- var freezeResults = Object.isFrozen(entry.res);
5067
- var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);
5068
- if (entry.dirty) {
5069
- delArrayItem(entries, entry);
5070
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5071
- }
5072
- else if (modRes !== entry.res) {
5073
- entry.res = modRes;
5074
- entry.promise = DexiePromise.resolve({ result: modRes });
5357
+ if (wasCommitted && !entry.dirty) {
5358
+ var freezeResults = Object.isFrozen(entry.res);
5359
+ var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);
5360
+ if (entry.dirty) {
5361
+ delArrayItem(entries, entry);
5362
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5363
+ }
5364
+ else if (modRes !== entry.res) {
5365
+ entry.res = modRes;
5366
+ entry.promise = DexiePromise.resolve({ result: modRes });
5367
+ }
5368
+ }
5369
+ else {
5370
+ if (entry.dirty) {
5371
+ delArrayItem(entries, entry);
5372
+ }
5373
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5374
+ }
5375
+ }
5075
5376
  }
5076
5377
  }
5077
- else {
5078
- if (entry.dirty) {
5079
- delArrayItem(entries, entry);
5378
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
5379
+ finally {
5380
+ try {
5381
+ if (_o && !_o.done && (_e = _m.return)) _e.call(_m);
5080
5382
  }
5081
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5383
+ finally { if (e_5) throw e_5.error; }
5082
5384
  }
5083
5385
  }
5084
5386
  }
5387
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
5388
+ finally {
5389
+ try {
5390
+ if (_l && !_l.done && (_d = _k.return)) _d.call(_k);
5391
+ }
5392
+ finally { if (e_4) throw e_4.error; }
5393
+ }
5085
5394
  }
5086
5395
  }
5087
5396
  }
5088
5397
  }
5398
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5399
+ finally {
5400
+ try {
5401
+ if (stores_1_1 && !stores_1_1.done && (_a = stores_1.return)) _a.call(stores_1);
5402
+ }
5403
+ finally { if (e_1) throw e_1.error; }
5404
+ }
5089
5405
  affectedSubscribers_1.forEach(function (requery) { return requery(); });
5090
5406
  }
5091
5407
  }; };
@@ -5155,7 +5471,7 @@ var cacheMiddleware = {
5155
5471
  return downTable.query(req);
5156
5472
  var freezeResults = ((_a = PSD.trans) === null || _a === void 0 ? void 0 : _a.db._options.cache) === 'immutable';
5157
5473
  var _b = PSD, requery = _b.requery, signal = _b.signal;
5158
- var _c = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];
5474
+ var _c = __read(findCompatibleQuery(dbName, tableName, 'query', req), 4), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];
5159
5475
  if (cacheEntry && exactMatch) {
5160
5476
  cacheEntry.obsSet = req.obsSet;
5161
5477
  }
@@ -5229,6 +5545,169 @@ function vipify(target, vipDb) {
5229
5545
  });
5230
5546
  }
5231
5547
 
5548
+ function compressYDocs(db, interval) {
5549
+ var e_1, _a, e_2, _b;
5550
+ var p = Promise.resolve();
5551
+ try {
5552
+ for (var _c = __values(db.tables), _d = _c.next(); !_d.done; _d = _c.next()) {
5553
+ var table = _d.value;
5554
+ var _loop_1 = function (yProp) {
5555
+ p = p.then(function () { return compressYDocsTable(db, yProp, interval); });
5556
+ };
5557
+ try {
5558
+ for (var _e = (e_2 = void 0, __values(table.schema.yProps || [])), _f = _e.next(); !_f.done; _f = _e.next()) {
5559
+ var yProp = _f.value;
5560
+ _loop_1(yProp);
5561
+ }
5562
+ }
5563
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5564
+ finally {
5565
+ try {
5566
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
5567
+ }
5568
+ finally { if (e_2) throw e_2.error; }
5569
+ }
5570
+ }
5571
+ }
5572
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5573
+ finally {
5574
+ try {
5575
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
5576
+ }
5577
+ finally { if (e_1) throw e_1.error; }
5578
+ }
5579
+ return p;
5580
+ }
5581
+ function compressYDocsTable(db, _a, skipIfRunnedSince
5582
+ ) {
5583
+ var updatesTable = _a.updatesTable;
5584
+ var updTbl = db.table(updatesTable);
5585
+ return Promise.all([
5586
+ updTbl
5587
+ .where('i')
5588
+ .startsWith('')
5589
+ .toArray(),
5590
+ db.transaction('rw', updatesTable, function () {
5591
+ return updTbl.get(0).then(function (lastCompressed) {
5592
+ if (lastCompressed &&
5593
+ skipIfRunnedSince &&
5594
+ lastCompressed.lastRun.getTime() > Date.now() - skipIfRunnedSince) {
5595
+ return null;
5596
+ }
5597
+ lastCompressed = lastCompressed || { i: 0, lastCompressed: 0 };
5598
+ return updTbl
5599
+ .put(__assign(__assign({}, lastCompressed), { lastRun: new Date() }))
5600
+ .then(function () { return lastCompressed; });
5601
+ });
5602
+ }),
5603
+ ]).then(function (_a) {
5604
+ var _b = __read(_a, 2), syncers = _b[0], stamp = _b[1];
5605
+ if (!stamp)
5606
+ return;
5607
+ var lastCompressedUpdate = stamp.lastCompressed;
5608
+ var unsyncedFrom = Math.min.apply(Math, __spreadArray([], __read(syncers.map(function (s) { return Math.min(s.unsentFrom || Infinity, s.receivedUntil != null ? s.receivedUntil + 1 : Infinity); })), false));
5609
+ return updTbl
5610
+ .where('i')
5611
+ .between(lastCompressedUpdate, Infinity, false)
5612
+ .toArray(function (addedUpdates) {
5613
+ var e_3, _a;
5614
+ if (addedUpdates.length <= 1)
5615
+ return;
5616
+ var docsToCompress = [];
5617
+ var lastUpdateToCompress = lastCompressedUpdate + 1;
5618
+ var _loop_2 = function (j) {
5619
+ var updateRow = addedUpdates[j];
5620
+ var i = updateRow.i, f = updateRow.f, k = updateRow.k;
5621
+ if (i >= unsyncedFrom && (f & 0x01))
5622
+ return "break";
5623
+ var entry = docsToCompress.find(function (entry) { return cmp(entry.docId, k) === 0; });
5624
+ if (entry)
5625
+ entry.updates.push(updateRow);
5626
+ else
5627
+ docsToCompress.push({ docId: k, updates: [updateRow] });
5628
+ lastUpdateToCompress = i;
5629
+ };
5630
+ for (var j = 0; j < addedUpdates.length; ++j) {
5631
+ var state_1 = _loop_2(j);
5632
+ if (state_1 === "break")
5633
+ break;
5634
+ }
5635
+ var p = Promise.resolve();
5636
+ var _loop_3 = function (docId, updates) {
5637
+ p = p.then(function () { return compressUpdatesForDoc(db, updatesTable, docId, updates); });
5638
+ };
5639
+ try {
5640
+ for (var docsToCompress_1 = __values(docsToCompress), docsToCompress_1_1 = docsToCompress_1.next(); !docsToCompress_1_1.done; docsToCompress_1_1 = docsToCompress_1.next()) {
5641
+ var _b = docsToCompress_1_1.value, docId = _b.docId, updates = _b.updates;
5642
+ _loop_3(docId, updates);
5643
+ }
5644
+ }
5645
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
5646
+ finally {
5647
+ try {
5648
+ if (docsToCompress_1_1 && !docsToCompress_1_1.done && (_a = docsToCompress_1.return)) _a.call(docsToCompress_1);
5649
+ }
5650
+ finally { if (e_3) throw e_3.error; }
5651
+ }
5652
+ return p.then(function () {
5653
+ return db.transaction('rw', updTbl, function () {
5654
+ return updTbl.get(0).then(function (current) {
5655
+ return updTbl.put(__assign(__assign({}, current), { lastCompressed: Math.max(lastUpdateToCompress, (current === null || current === void 0 ? void 0 : current.lastCompressed) || 0) }));
5656
+ });
5657
+ });
5658
+ });
5659
+ });
5660
+ });
5661
+ }
5662
+ function compressUpdatesForDoc(db, updatesTable, parentId, addedUpdatesToCompress) {
5663
+ if (addedUpdatesToCompress.length < 1)
5664
+ throw new Error('Invalid input');
5665
+ return db.transaction('rw', updatesTable, function (tx) {
5666
+ var updTbl = tx.table(updatesTable);
5667
+ return updTbl.where({ k: parentId }).first(function (mainUpdate) {
5668
+ var updates = [mainUpdate].concat(addedUpdatesToCompress);
5669
+ var Y = getYLibrary(db);
5670
+ var doc = new Y.Doc({ gc: true });
5671
+ updates.forEach(function (update) {
5672
+ Y.applyUpdateV2(doc, update.u);
5673
+ });
5674
+ var compressedUpdate = Y.encodeStateAsUpdateV2(doc);
5675
+ var lastUpdate = updates.pop();
5676
+ return updTbl
5677
+ .put({
5678
+ i: lastUpdate.i,
5679
+ k: parentId,
5680
+ u: compressedUpdate,
5681
+ })
5682
+ .then(function () { return updTbl.bulkDelete(updates.map(function (update) { return update.i; })); });
5683
+ });
5684
+ });
5685
+ }
5686
+
5687
+ var INTERVAL = 10000;
5688
+ function periodicGC(db) {
5689
+ var timer = null;
5690
+ db.on('ready', function (db) {
5691
+ if (db.tables.some(function (tbl) { return tbl.schema.yProps; })) {
5692
+ var gc_1 = function () {
5693
+ if (!db.isOpen())
5694
+ return;
5695
+ compressYDocs(db, INTERVAL).catch(function (err) {
5696
+ console.debug('Error during periodic GC', err);
5697
+ }).then(function () {
5698
+ timer = setTimeout(gc_1, INTERVAL);
5699
+ });
5700
+ };
5701
+ timer = setTimeout(gc_1, INTERVAL);
5702
+ }
5703
+ }, true);
5704
+ db.on('close', function () {
5705
+ if (timer)
5706
+ clearTimeout(timer);
5707
+ timer = null;
5708
+ });
5709
+ }
5710
+
5232
5711
  var Dexie$1 = (function () {
5233
5712
  function Dexie(name, options) {
5234
5713
  var _this = this;
@@ -5270,7 +5749,18 @@ var Dexie$1 = (function () {
5270
5749
  });
5271
5750
  this._state = state;
5272
5751
  this.name = name;
5273
- this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] });
5752
+ this.on = Events(this, "populate", "blocked", "versionchange", "close", "y", { ready: [promisableChain, nop] });
5753
+ this.once = function (event, callback) {
5754
+ var fn = function () {
5755
+ var args = [];
5756
+ for (var _i = 0; _i < arguments.length; _i++) {
5757
+ args[_i] = arguments[_i];
5758
+ }
5759
+ _this.on(event).unsubscribe(fn);
5760
+ callback.apply(_this, args);
5761
+ };
5762
+ return _this.on(event, fn);
5763
+ };
5274
5764
  this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {
5275
5765
  return function (subscriber, bSticky) {
5276
5766
  Dexie.vip(function () {
@@ -5349,6 +5839,8 @@ var Dexie$1 = (function () {
5349
5839
  }
5350
5840
  });
5351
5841
  this.vip = vipDB;
5842
+ if (options === null || options === void 0 ? void 0 : options.Y)
5843
+ periodicGC(this);
5352
5844
  addons.forEach(function (addon) { return addon(_this); });
5353
5845
  }
5354
5846
  Dexie.prototype.version = function (versionNumber) {
@@ -5411,6 +5903,7 @@ var Dexie$1 = (function () {
5411
5903
  function () { return dexieOpen(_this); });
5412
5904
  };
5413
5905
  Dexie.prototype._close = function () {
5906
+ this.on.close.fire(new CustomEvent('close'));
5414
5907
  var state = this._state;
5415
5908
  var idx = connections.indexOf(this);
5416
5909
  if (idx >= 0)
@@ -5568,6 +6061,9 @@ var Dexie$1 = (function () {
5568
6061
  }
5569
6062
  return this._allTables[tableName];
5570
6063
  };
6064
+ Dexie.prototype.gc = function () {
6065
+ return compressYDocs(this);
6066
+ };
5571
6067
  return Dexie;
5572
6068
  }());
5573
6069
 
@@ -5868,8 +6364,176 @@ function replacePrefix(a, b) {
5868
6364
  return new PropModification({ replacePrefix: [a, b] });
5869
6365
  }
5870
6366
 
6367
+ function observeYDocUpdates(provider, doc, db, parentTableName, updatesTableName, parentId, Y) {
6368
+ var lastUpdateId = 0;
6369
+ var initial = true;
6370
+ var subscription = liveQuery(function () {
6371
+ throwIfDestroyed(doc);
6372
+ var updatesTable = db.table(updatesTableName);
6373
+ return Promise.all([
6374
+ (lastUpdateId > 0
6375
+ ? updatesTable
6376
+ .where('i')
6377
+ .between(lastUpdateId, Infinity, false)
6378
+ .toArray()
6379
+ .then(function (updates) {
6380
+ return updates.filter(function (update) { return cmp(update.k, parentId) === 0; });
6381
+ })
6382
+ : updatesTable.where({ k: parentId }).toArray()).then(function (updates) {
6383
+ if (updates.length > 0)
6384
+ lastUpdateId = updates[updates.length - 1].i;
6385
+ return updates;
6386
+ }),
6387
+ db.table(parentTableName).where(':id').equals(parentId).toArray(),
6388
+ ]);
6389
+ }).subscribe(function (_a) {
6390
+ var _b = __read(_a, 2), updates = _b[0], parentRow = _b[1];
6391
+ if (parentRow.length === 0) {
6392
+ doc.destroy();
6393
+ return;
6394
+ }
6395
+ throwIfDestroyed(doc);
6396
+ if (updates.length > 0) {
6397
+ Y.transact(doc, function () {
6398
+ updates.forEach(function (update) {
6399
+ try {
6400
+ DexieYProvider.currentUpdateRow = update;
6401
+ Y.applyUpdateV2(doc, update.u);
6402
+ }
6403
+ finally {
6404
+ DexieYProvider.currentUpdateRow = null;
6405
+ }
6406
+ });
6407
+ }, provider, false);
6408
+ }
6409
+ if (initial) {
6410
+ initial = false;
6411
+ doc.emit('load', [doc]);
6412
+ }
6413
+ }, function (error) {
6414
+ provider.on('error').fire(error);
6415
+ });
6416
+ var onUpdate = function (update, origin) {
6417
+ if (origin === provider)
6418
+ return;
6419
+ db.table(updatesTableName)
6420
+ .add({
6421
+ k: parentId,
6422
+ u: update,
6423
+ f: 1,
6424
+ })
6425
+ .then(function (i) {
6426
+ if (i === lastUpdateId - 1)
6427
+ ++lastUpdateId;
6428
+ })
6429
+ .catch(function (error) {
6430
+ provider.on('error').fire(error);
6431
+ });
6432
+ };
6433
+ var stopObserving = function () {
6434
+ subscription.unsubscribe();
6435
+ doc.off('updateV2', onUpdate);
6436
+ doc.off('destroy', stopObserving);
6437
+ };
6438
+ doc.on('updateV2', onUpdate);
6439
+ doc.on('destroy', stopObserving);
6440
+ return stopObserving;
6441
+ }
6442
+
6443
+ var wm = new WeakMap();
6444
+ function createEvents() {
6445
+ return Events(null, 'load', 'sync', 'error');
6446
+ }
6447
+ var DexieYProvider = (function () {
6448
+ function DexieYProvider(doc) {
6449
+ var _this = this;
6450
+ this.refCount = 1;
6451
+ this.cleanupHandlers = [];
6452
+ this.destroyed = false;
6453
+ var _a = (doc || {}).meta, db = _a.db, parentTable = _a.parentTable, parentId = _a.parentId, updatesTable = _a.updatesTable;
6454
+ if (!db || !parentTable || !updatesTable)
6455
+ throw new Error('Y.Doc not generated by Dexie');
6456
+ if (!db.table(parentTable) || !db.table(updatesTable)) {
6457
+ throw new Error("Table ".concat(parentTable, " or ").concat(updatesTable, " not found in db"));
6458
+ }
6459
+ throwIfDestroyed(doc);
6460
+ var Y = getYLibrary(db);
6461
+ this.on = createEvents();
6462
+ this.doc = doc;
6463
+ this.off = function (name, f) { var _a; return (_a = _this.on[name]) === null || _a === void 0 ? void 0 : _a.unsubscribe(f); };
6464
+ this.whenLoaded = new Promise(function (resolve, reject) {
6465
+ _this.on('load', resolve);
6466
+ _this.on('error', reject);
6467
+ });
6468
+ this.whenSynced = new Promise(function (resolve, reject) {
6469
+ _this.on('sync', resolve);
6470
+ _this.on('error', reject);
6471
+ });
6472
+ if ('dispose' in Symbol) {
6473
+ this[Symbol.dispose] = this.dispose;
6474
+ }
6475
+ this.stopObserving = observeYDocUpdates(this, doc, db, parentTable, updatesTable, parentId, Y);
6476
+ doc.on('load', function () { return _this.on('load').fire(); });
6477
+ doc.on('sync', function (sync) { return sync !== false && _this.on('sync').fire(); });
6478
+ doc.on('destroy', this.destroy.bind(this));
6479
+ db.on.y.fire(this, Y);
6480
+ }
6481
+ DexieYProvider.load = function (doc) {
6482
+ var p = wm.get(doc);
6483
+ if (p) {
6484
+ ++p.refCount;
6485
+ }
6486
+ else {
6487
+ p = new DexieYProvider(doc);
6488
+ wm.set(doc, p);
6489
+ }
6490
+ return p;
6491
+ };
6492
+ DexieYProvider.release = function (doc, options) {
6493
+ if (destroyedDocs.has(doc))
6494
+ return;
6495
+ var p = wm.get(doc);
6496
+ if (!p) {
6497
+ if (--p.refCount === 0) {
6498
+ if (isNaN(options === null || options === void 0 ? void 0 : options.gracePeriod)) {
6499
+ doc.destroy();
6500
+ }
6501
+ else {
6502
+ setTimeout(function () { return p.refCount || doc.destroy(); },
6503
+ options.gracePeriod
6504
+ );
6505
+ }
6506
+ }
6507
+ }
6508
+ else {
6509
+ doc.destroy();
6510
+ }
6511
+ };
6512
+ DexieYProvider.for = function (doc) {
6513
+ return wm.get(doc);
6514
+ };
6515
+ DexieYProvider.prototype.destroy = function () {
6516
+ var _a;
6517
+ wm.delete(this.doc);
6518
+ this.doc = null;
6519
+ this.destroyed = true;
6520
+ this.refCount = 0;
6521
+ (_a = this.stopObserving) === null || _a === void 0 ? void 0 : _a.call(this);
6522
+ this.on = createEvents();
6523
+ this.cleanupHandlers.forEach(function (cleanup) { return cleanup(); });
6524
+ };
6525
+ DexieYProvider.prototype.addCleanupHandler = function (cleanupHandler) {
6526
+ this.cleanupHandlers.push(typeof cleanupHandler === 'function'
6527
+ ? cleanupHandler
6528
+ : function () { return cleanupHandler.unsubscribe(); });
6529
+ };
6530
+ DexieYProvider.getDocCache = getDocCache;
6531
+ DexieYProvider.currentUpdateRow = null;
6532
+ return DexieYProvider;
6533
+ }());
6534
+
5871
6535
  DexiePromise.rejectionMapper = mapError;
5872
6536
  setDebug(debug);
5873
6537
 
5874
- export { Dexie$1 as Dexie, Entity, PropModSymbol, PropModification, RangeSet, add, cmp, Dexie$1 as default, liveQuery, mergeRanges, rangesOverlap, remove, replacePrefix };
6538
+ export { Dexie$1 as Dexie, DexieYProvider, Entity, PropModSymbol, PropModification, RangeSet, add, cmp, Dexie$1 as default, liveQuery, mergeRanges, rangesOverlap, remove, replacePrefix };
5875
6539
  //# sourceMappingURL=dexie.mjs.map