@epam/uui-db 4.2.5 → 4.4.0

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/index.js CHANGED
@@ -349,10 +349,10 @@ function __classPrivateFieldSet(receiver, privateMap, value) {
349
349
  /***/ (function(module, exports, __webpack_require__) {
350
350
 
351
351
  "use strict";
352
-
353
- Object.defineProperty(exports, "__esModule", { value: true });
354
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
355
- tslib_1.__exportStar(__webpack_require__(/*! ./src */ "./src/index.ts"), exports);
352
+
353
+ Object.defineProperty(exports, "__esModule", { value: true });
354
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
355
+ tslib_1.__exportStar(__webpack_require__(/*! ./src */ "./src/index.ts"), exports);
356
356
 
357
357
 
358
358
  /***/ }),
@@ -365,80 +365,80 @@ tslib_1.__exportStar(__webpack_require__(/*! ./src */ "./src/index.ts"), exports
365
365
  /***/ (function(module, exports, __webpack_require__) {
366
366
 
367
367
  "use strict";
368
-
369
- Object.defineProperty(exports, "__esModule", { value: true });
370
- exports.Db = void 0;
371
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
372
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
373
- var lodash_isequal_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
374
- var Db = /** @class */ (function () {
375
- function Db(tables, reusedCache) {
376
- this.tables = tables;
377
- this.viewCache = new Map();
378
- /* Views (cached db projections) */
379
- this.valueAbsent = Symbol("ValueAbsent");
380
- if (reusedCache) {
381
- this.viewCache = new Map(reusedCache);
382
- }
383
- else {
384
- this.viewCache = new Map();
385
- }
386
- }
387
- Db.prototype.update = function (mutate) {
388
- var clone = new this.constructor(tslib_1.__assign({}, this.tables), this.viewCache);
389
- mutate(clone);
390
- return clone;
391
- };
392
- Db.prototype.with = function (patch) {
393
- return this.update(function (db) {
394
- utils_1.objectKeys(db.tables).forEach(function (entityName) {
395
- if (patch[entityName]) {
396
- db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
397
- }
398
- });
399
- });
400
- };
401
- Db.prototype.runView = function (view, params) {
402
- var cache = this.viewCache.get(view);
403
- if (!cache) {
404
- cache = new Map();
405
- this.viewCache.set(view, cache);
406
- }
407
- var key = view.getKey ? view.getKey(params) : JSON.stringify(params);
408
- var cacheItem = cache.get(key);
409
- if (!cacheItem) {
410
- cacheItem = {
411
- dependencies: this.valueAbsent,
412
- currentValue: this.valueAbsent,
413
- computedOnDb: this.valueAbsent,
414
- };
415
- cache.set(key, cacheItem);
416
- }
417
- var shouldUpdate = this !== cacheItem.computedOnDb;
418
- var dependencies = this.valueAbsent;
419
- if (view.getDependencies) {
420
- var compare = view.compareDependencies || utils_1.defaultCompareViewDependencies;
421
- dependencies = view.getDependencies(this, params);
422
- shouldUpdate = !compare(cacheItem.dependencies, dependencies);
423
- }
424
- var previousValue = cacheItem.currentValue;
425
- if (shouldUpdate) {
426
- cacheItem.dependencies = dependencies;
427
- var newValue = view.compute(this, params, dependencies);
428
- cacheItem.computedOnDb = this;
429
- var compareResults = view.compareResults || lodash_isequal_1.default;
430
- if (!compareResults(previousValue, newValue)) {
431
- if (view.traceDiff) {
432
- console.debug(utils_1.difference(previousValue, newValue));
433
- }
434
- cacheItem.currentValue = newValue;
435
- }
436
- }
437
- return cacheItem.currentValue;
438
- };
439
- return Db;
440
- }());
441
- exports.Db = Db;
368
+
369
+ Object.defineProperty(exports, "__esModule", { value: true });
370
+ exports.Db = void 0;
371
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
372
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
373
+ var lodash_isequal_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
374
+ var Db = /** @class */ (function () {
375
+ function Db(tables, reusedCache) {
376
+ this.tables = tables;
377
+ this.viewCache = new Map();
378
+ /* Views (cached db projections) */
379
+ this.valueAbsent = Symbol("ValueAbsent");
380
+ if (reusedCache) {
381
+ this.viewCache = new Map(reusedCache);
382
+ }
383
+ else {
384
+ this.viewCache = new Map();
385
+ }
386
+ }
387
+ Db.prototype.update = function (mutate) {
388
+ var clone = new this.constructor(tslib_1.__assign({}, this.tables), this.viewCache);
389
+ mutate(clone);
390
+ return clone;
391
+ };
392
+ Db.prototype.with = function (patch) {
393
+ return this.update(function (db) {
394
+ utils_1.objectKeys(db.tables).forEach(function (entityName) {
395
+ if (patch[entityName]) {
396
+ db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
397
+ }
398
+ });
399
+ });
400
+ };
401
+ Db.prototype.runView = function (view, params) {
402
+ var cache = this.viewCache.get(view);
403
+ if (!cache) {
404
+ cache = new Map();
405
+ this.viewCache.set(view, cache);
406
+ }
407
+ var key = view.getKey ? view.getKey(params) : JSON.stringify(params);
408
+ var cacheItem = cache.get(key);
409
+ if (!cacheItem) {
410
+ cacheItem = {
411
+ dependencies: this.valueAbsent,
412
+ currentValue: this.valueAbsent,
413
+ computedOnDb: this.valueAbsent,
414
+ };
415
+ cache.set(key, cacheItem);
416
+ }
417
+ var shouldUpdate = this !== cacheItem.computedOnDb;
418
+ var dependencies = this.valueAbsent;
419
+ if (view.getDependencies) {
420
+ var compare = view.compareDependencies || utils_1.defaultCompareViewDependencies;
421
+ dependencies = view.getDependencies(this, params);
422
+ shouldUpdate = !compare(cacheItem.dependencies, dependencies);
423
+ }
424
+ var previousValue = cacheItem.currentValue;
425
+ if (shouldUpdate) {
426
+ cacheItem.dependencies = dependencies;
427
+ var newValue = view.compute(this, params, dependencies);
428
+ cacheItem.computedOnDb = this;
429
+ var compareResults = view.compareResults || lodash_isequal_1.default;
430
+ if (!compareResults(previousValue, newValue)) {
431
+ if (view.traceDiff) {
432
+ console.debug(utils_1.difference(previousValue, newValue));
433
+ }
434
+ cacheItem.currentValue = newValue;
435
+ }
436
+ }
437
+ return cacheItem.currentValue;
438
+ };
439
+ return Db;
440
+ }());
441
+ exports.Db = Db;
442
442
 
443
443
 
444
444
  /***/ }),
@@ -451,230 +451,230 @@ exports.Db = Db;
451
451
  /***/ (function(module, exports, __webpack_require__) {
452
452
 
453
453
  "use strict";
454
-
455
- Object.defineProperty(exports, "__esModule", { value: true });
456
- exports.DbRef = void 0;
457
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
458
- var patchHelpers_1 = __webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts");
459
- var tempIds_1 = __webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx");
460
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
461
- var lodash_isempty_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isempty */ "lodash.isempty"));
462
- var Loader_1 = __webpack_require__(/*! ./Loader */ "./src/Loader.ts");
463
- var SimpleLoadingTracker_1 = __webpack_require__(/*! ./SimpleLoadingTracker */ "./src/SimpleLoadingTracker.ts");
464
- var ListLoadingTracker_1 = __webpack_require__(/*! ./ListLoadingTracker */ "./src/ListLoadingTracker.ts");
465
- var DbRef = /** @class */ (function () {
466
- function DbRef(blank) {
467
- var _this = this;
468
- this.blank = blank;
469
- this.log = [];
470
- this.autoSave = true;
471
- this.savedPoint = 0;
472
- this.errors = [];
473
- this.throttleSaveMs = 1000;
474
- /* Update subscriptions (aka live views) */
475
- this.lastSubscriptionId = 1;
476
- this.subscriptions = new Map();
477
- this.updateHandlers = [];
478
- /* Error Subscriptions */
479
- this.saveErrorHandlers = [];
480
- /* Save scheduling */
481
- this.isSaveInProgress = false;
482
- this.isSaveThrottled = false;
483
- this.handleBeforeUnload = function (e) {
484
- if (_this.isSaveInProgress || _this.isSaveThrottled) {
485
- e.returnValue = false;
486
- return false;
487
- }
488
- };
489
- this.loaders = [];
490
- this.db = blank;
491
- this.base = blank;
492
- this.tempIdMap = new tempIds_1.TempIdMap(blank);
493
- this.idMap = this.tempIdMap;
494
- window.addEventListener('beforeunload', this.handleBeforeUnload);
495
- }
496
- /** Saves all committed patches. Useful only if autoSave is off. */
497
- DbRef.prototype.save = function () {
498
- this.enqueueSave();
499
- this.update();
500
- };
501
- DbRef.prototype.getAutoSave = function () {
502
- return this.autoSave;
503
- };
504
- DbRef.prototype.setAutoSave = function (val) {
505
- if (this.autoSave != val) {
506
- this.autoSave = val;
507
- this.enqueueSave();
508
- this.update();
509
- }
510
- };
511
- /** Concrete DbRef instances should override and implement their save logic in this method */
512
- DbRef.prototype.savePatch = function (patch) {
513
- return Promise.resolve({ submit: {} });
514
- };
515
- /* Db Update logic */
516
- DbRef.prototype.commit = function (patch) {
517
- try {
518
- var dbBeforeUpdate = this.db.with(patch);
519
- patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
520
- patch = patchHelpers_1.mergeEntityPatches(this.db.tables, patch);
521
- this.log.push({ patch: patch });
522
- this.db = this.db.with(patch);
523
- this.autoSave && this.enqueueSave();
524
- this.update();
525
- }
526
- catch (e) {
527
- this.saveError(patch, e);
528
- }
529
- };
530
- DbRef.prototype.beforeUpdate = function (patch, tables, prevTables) {
531
- var _this = this;
532
- var patchAndDependencies = {};
533
- utils_1.objectKeys(tables).filter(function (entityName) { return patch[entityName] && !tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
534
- patchAndDependencies[entityName] = patch[entityName];
535
- });
536
- utils_1.objectKeys(tables).filter(function (entityName) { return patch[entityName] && tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
537
- var _a;
538
- var schema = tables[entityName].schema;
539
- var beforeUpdate = schema.beforeUpdate;
540
- var context = {
541
- clientIdsMap: _this.tempIdMap,
542
- schema: schema,
543
- tables: tables,
544
- prevTables: prevTables,
545
- };
546
- var results = patch[entityName].map(function (e) { return beforeUpdate(e, context); });
547
- var updatedPatch = (_a = {}, _a[entityName] = results.map(function (result) { return result.entity; }), _a);
548
- var dependentEntityPatchesForUpdate = patchHelpers_1.unionPatches(results.filter(function (result) { return result.dependentEntities; }).map(function (result) { return result.dependentEntities; }));
549
- var dependentEntityPatches = _this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
550
- patchAndDependencies = patchHelpers_1.mergeEntityPatches(tables, patchHelpers_1.unionPatches([patchAndDependencies, updatedPatch, dependentEntityPatches]));
551
- });
552
- return patchAndDependencies;
553
- };
554
- DbRef.prototype.commitFetch = function (patch) {
555
- patch = this.tempIdMap.serverToClientPatch(patch);
556
- this.rebase(this.base.with(patch));
557
- this.update();
558
- };
559
- DbRef.prototype.rebase = function (newBase) {
560
- this.base = newBase;
561
- this.db = newBase;
562
- for (var n = this.savedPoint; n < this.log.length; n++) {
563
- this.db = this.db.with(this.log[n].patch);
564
- }
565
- };
566
- DbRef.prototype.makeCumulativePatch = function () {
567
- var lastLogEntry = this.log.length;
568
- var logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
569
- var cumulativePatch = patchHelpers_1.makeCumulativePatch(this.db, logEntriesToSave.map(function (t) { return t.patch; }), this.tempIdMap);
570
- cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
571
- return cumulativePatch;
572
- };
573
- DbRef.prototype.applyResponse = function (response, newSavedPoint) {
574
- var _this = this;
575
- if (this.errors.length == 0) {
576
- this.tempIdMap.appendServerMapping(response);
577
- var serverPatch = patchHelpers_1.flattenResponse(response.submit, this.db.tables);
578
- serverPatch = patchHelpers_1.mergeEntityPatches(this.db.tables, serverPatch);
579
- this.savedPoint = newSavedPoint;
580
- this.base = this.db;
581
- this.commitFetch(serverPatch);
582
- if (this.autoSave) {
583
- this.isSaveThrottled = true;
584
- setTimeout(function () {
585
- _this.isSaveThrottled = false;
586
- if (_this.savedPoint < _this.log.length) {
587
- _this.enqueueSave();
588
- }
589
- }, this.throttleSaveMs);
590
- }
591
- }
592
- };
593
- DbRef.prototype.subscribe = function (view, params, onUpdate) {
594
- var _this = this;
595
- var id = this.lastSubscriptionId++;
596
- var subscription = {
597
- update: function (params) {
598
- subscription.currentParams = params;
599
- subscription.currentValue = _this.db.runView(view, params);
600
- return subscription.currentValue;
601
- },
602
- currentParams: null,
603
- currentValue: null,
604
- onUpdate: onUpdate,
605
- unsubscribe: function () { _this.subscriptions.delete(id); },
606
- };
607
- subscription.update(params);
608
- this.subscriptions.set(id, subscription);
609
- return subscription;
610
- };
611
- DbRef.prototype.onUpdate = function (handler) {
612
- this.subscribe({
613
- compute: function (db) { return db; },
614
- compareResults: function (a, b) { return a === b; },
615
- }, null, handler);
616
- };
617
- DbRef.prototype.update = function () {
618
- this.subscriptions.forEach(function (subscription) {
619
- var previousValue = subscription.currentValue;
620
- subscription.update(subscription.currentParams);
621
- if (subscription.currentValue !== previousValue && subscription.onUpdate) {
622
- subscription.onUpdate(subscription.currentValue);
623
- }
624
- });
625
- };
626
- DbRef.prototype.onSaveError = function (handler) {
627
- this.saveErrorHandlers.push(handler);
628
- };
629
- DbRef.prototype.saveError = function (request, error) {
630
- this.saveErrorHandlers.forEach(function (handler) { return handler(request, error); });
631
- };
632
- DbRef.prototype.enqueueSave = function () {
633
- var _this = this;
634
- if (!this.isSaveInProgress && !this.isSaveThrottled) {
635
- try {
636
- this.isSaveInProgress = true;
637
- var lastLogEntry_1 = this.log.length;
638
- var cumulativePatch_1 = this.makeCumulativePatch();
639
- if (lodash_isempty_1.default(cumulativePatch_1)) {
640
- this.isSaveInProgress = false;
641
- return;
642
- }
643
- this.savePatch(cumulativePatch_1)
644
- .then(function (response) {
645
- _this.applyResponse(response, lastLogEntry_1);
646
- _this.isSaveInProgress = false;
647
- _this.update();
648
- })
649
- .catch(function (reason) {
650
- _this.saveError(cumulativePatch_1, reason);
651
- _this.isSaveInProgress = false;
652
- _this.update();
653
- });
654
- }
655
- catch (e) {
656
- this.isSaveInProgress = false;
657
- this.isSaveThrottled = false;
658
- throw e;
659
- }
660
- }
661
- };
662
- DbRef.prototype.makeLoader = function (options) {
663
- var loader = new Loader_1.Loader(this, function () { return new SimpleLoadingTracker_1.SimpleLoadingTracker(); }, options);
664
- this.loaders.push(loader);
665
- return loader;
666
- };
667
- DbRef.prototype.makeListLoader = function (options) {
668
- var loader = new Loader_1.Loader(this, function () { return new ListLoadingTracker_1.ListLoadingTracker(); }, options);
669
- this.loaders.push(loader);
670
- return loader;
671
- };
672
- DbRef.prototype.reload = function () {
673
- this.loaders = [];
674
- };
675
- return DbRef;
676
- }());
677
- exports.DbRef = DbRef;
454
+
455
+ Object.defineProperty(exports, "__esModule", { value: true });
456
+ exports.DbRef = void 0;
457
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
458
+ var patchHelpers_1 = __webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts");
459
+ var tempIds_1 = __webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx");
460
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
461
+ var lodash_isempty_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isempty */ "lodash.isempty"));
462
+ var Loader_1 = __webpack_require__(/*! ./Loader */ "./src/Loader.ts");
463
+ var SimpleLoadingTracker_1 = __webpack_require__(/*! ./SimpleLoadingTracker */ "./src/SimpleLoadingTracker.ts");
464
+ var ListLoadingTracker_1 = __webpack_require__(/*! ./ListLoadingTracker */ "./src/ListLoadingTracker.ts");
465
+ var DbRef = /** @class */ (function () {
466
+ function DbRef(blank) {
467
+ var _this = this;
468
+ this.blank = blank;
469
+ this.log = [];
470
+ this.autoSave = true;
471
+ this.savedPoint = 0;
472
+ this.errors = [];
473
+ this.throttleSaveMs = 1000;
474
+ /* Update subscriptions (aka live views) */
475
+ this.lastSubscriptionId = 1;
476
+ this.subscriptions = new Map();
477
+ this.updateHandlers = [];
478
+ /* Error Subscriptions */
479
+ this.saveErrorHandlers = [];
480
+ /* Save scheduling */
481
+ this.isSaveInProgress = false;
482
+ this.isSaveThrottled = false;
483
+ this.handleBeforeUnload = function (e) {
484
+ if (_this.isSaveInProgress || _this.isSaveThrottled) {
485
+ e.returnValue = false;
486
+ return false;
487
+ }
488
+ };
489
+ this.loaders = [];
490
+ this.db = blank;
491
+ this.base = blank;
492
+ this.tempIdMap = new tempIds_1.TempIdMap(blank);
493
+ this.idMap = this.tempIdMap;
494
+ window.addEventListener('beforeunload', this.handleBeforeUnload);
495
+ }
496
+ /** Saves all committed patches. Useful only if autoSave is off. */
497
+ DbRef.prototype.save = function () {
498
+ this.enqueueSave();
499
+ this.update();
500
+ };
501
+ DbRef.prototype.getAutoSave = function () {
502
+ return this.autoSave;
503
+ };
504
+ DbRef.prototype.setAutoSave = function (val) {
505
+ if (this.autoSave != val) {
506
+ this.autoSave = val;
507
+ this.enqueueSave();
508
+ this.update();
509
+ }
510
+ };
511
+ /** Concrete DbRef instances should override and implement their save logic in this method */
512
+ DbRef.prototype.savePatch = function (patch) {
513
+ return Promise.resolve({ submit: {} });
514
+ };
515
+ /* Db Update logic */
516
+ DbRef.prototype.commit = function (patch) {
517
+ try {
518
+ var dbBeforeUpdate = this.db.with(patch);
519
+ patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
520
+ patch = patchHelpers_1.mergeEntityPatches(this.db.tables, patch);
521
+ this.log.push({ patch: patch });
522
+ this.db = this.db.with(patch);
523
+ this.autoSave && this.enqueueSave();
524
+ this.update();
525
+ }
526
+ catch (e) {
527
+ this.saveError(patch, e);
528
+ }
529
+ };
530
+ DbRef.prototype.beforeUpdate = function (patch, tables, prevTables) {
531
+ var _this = this;
532
+ var patchAndDependencies = {};
533
+ utils_1.objectKeys(tables).filter(function (entityName) { return patch[entityName] && !tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
534
+ patchAndDependencies[entityName] = patch[entityName];
535
+ });
536
+ utils_1.objectKeys(tables).filter(function (entityName) { return patch[entityName] && tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
537
+ var _a;
538
+ var schema = tables[entityName].schema;
539
+ var beforeUpdate = schema.beforeUpdate;
540
+ var context = {
541
+ clientIdsMap: _this.tempIdMap,
542
+ schema: schema,
543
+ tables: tables,
544
+ prevTables: prevTables,
545
+ };
546
+ var results = patch[entityName].map(function (e) { return beforeUpdate(e, context); });
547
+ var updatedPatch = (_a = {}, _a[entityName] = results.map(function (result) { return result.entity; }), _a);
548
+ var dependentEntityPatchesForUpdate = patchHelpers_1.unionPatches(results.filter(function (result) { return result.dependentEntities; }).map(function (result) { return result.dependentEntities; }));
549
+ var dependentEntityPatches = _this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
550
+ patchAndDependencies = patchHelpers_1.mergeEntityPatches(tables, patchHelpers_1.unionPatches([patchAndDependencies, updatedPatch, dependentEntityPatches]));
551
+ });
552
+ return patchAndDependencies;
553
+ };
554
+ DbRef.prototype.commitFetch = function (patch) {
555
+ patch = this.tempIdMap.serverToClientPatch(patch);
556
+ this.rebase(this.base.with(patch));
557
+ this.update();
558
+ };
559
+ DbRef.prototype.rebase = function (newBase) {
560
+ this.base = newBase;
561
+ this.db = newBase;
562
+ for (var n = this.savedPoint; n < this.log.length; n++) {
563
+ this.db = this.db.with(this.log[n].patch);
564
+ }
565
+ };
566
+ DbRef.prototype.makeCumulativePatch = function () {
567
+ var lastLogEntry = this.log.length;
568
+ var logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
569
+ var cumulativePatch = patchHelpers_1.makeCumulativePatch(this.db, logEntriesToSave.map(function (t) { return t.patch; }), this.tempIdMap);
570
+ cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
571
+ return cumulativePatch;
572
+ };
573
+ DbRef.prototype.applyResponse = function (response, newSavedPoint) {
574
+ var _this = this;
575
+ if (this.errors.length == 0) {
576
+ this.tempIdMap.appendServerMapping(response);
577
+ var serverPatch = patchHelpers_1.flattenResponse(response.submit, this.db.tables);
578
+ serverPatch = patchHelpers_1.mergeEntityPatches(this.db.tables, serverPatch);
579
+ this.savedPoint = newSavedPoint;
580
+ this.base = this.db;
581
+ this.commitFetch(serverPatch);
582
+ if (this.autoSave) {
583
+ this.isSaveThrottled = true;
584
+ setTimeout(function () {
585
+ _this.isSaveThrottled = false;
586
+ if (_this.savedPoint < _this.log.length) {
587
+ _this.enqueueSave();
588
+ }
589
+ }, this.throttleSaveMs);
590
+ }
591
+ }
592
+ };
593
+ DbRef.prototype.subscribe = function (view, params, onUpdate) {
594
+ var _this = this;
595
+ var id = this.lastSubscriptionId++;
596
+ var subscription = {
597
+ update: function (params) {
598
+ subscription.currentParams = params;
599
+ subscription.currentValue = _this.db.runView(view, params);
600
+ return subscription.currentValue;
601
+ },
602
+ currentParams: null,
603
+ currentValue: null,
604
+ onUpdate: onUpdate,
605
+ unsubscribe: function () { _this.subscriptions.delete(id); },
606
+ };
607
+ subscription.update(params);
608
+ this.subscriptions.set(id, subscription);
609
+ return subscription;
610
+ };
611
+ DbRef.prototype.onUpdate = function (handler) {
612
+ this.subscribe({
613
+ compute: function (db) { return db; },
614
+ compareResults: function (a, b) { return a === b; },
615
+ }, null, handler);
616
+ };
617
+ DbRef.prototype.update = function () {
618
+ this.subscriptions.forEach(function (subscription) {
619
+ var previousValue = subscription.currentValue;
620
+ subscription.update(subscription.currentParams);
621
+ if (subscription.currentValue !== previousValue && subscription.onUpdate) {
622
+ subscription.onUpdate(subscription.currentValue);
623
+ }
624
+ });
625
+ };
626
+ DbRef.prototype.onSaveError = function (handler) {
627
+ this.saveErrorHandlers.push(handler);
628
+ };
629
+ DbRef.prototype.saveError = function (request, error) {
630
+ this.saveErrorHandlers.forEach(function (handler) { return handler(request, error); });
631
+ };
632
+ DbRef.prototype.enqueueSave = function () {
633
+ var _this = this;
634
+ if (!this.isSaveInProgress && !this.isSaveThrottled) {
635
+ try {
636
+ this.isSaveInProgress = true;
637
+ var lastLogEntry_1 = this.log.length;
638
+ var cumulativePatch_1 = this.makeCumulativePatch();
639
+ if (lodash_isempty_1.default(cumulativePatch_1)) {
640
+ this.isSaveInProgress = false;
641
+ return;
642
+ }
643
+ this.savePatch(cumulativePatch_1)
644
+ .then(function (response) {
645
+ _this.applyResponse(response, lastLogEntry_1);
646
+ _this.isSaveInProgress = false;
647
+ _this.update();
648
+ })
649
+ .catch(function (reason) {
650
+ _this.saveError(cumulativePatch_1, reason);
651
+ _this.isSaveInProgress = false;
652
+ _this.update();
653
+ });
654
+ }
655
+ catch (e) {
656
+ this.isSaveInProgress = false;
657
+ this.isSaveThrottled = false;
658
+ throw e;
659
+ }
660
+ }
661
+ };
662
+ DbRef.prototype.makeLoader = function (options) {
663
+ var loader = new Loader_1.Loader(this, function () { return new SimpleLoadingTracker_1.SimpleLoadingTracker(); }, options);
664
+ this.loaders.push(loader);
665
+ return loader;
666
+ };
667
+ DbRef.prototype.makeListLoader = function (options) {
668
+ var loader = new Loader_1.Loader(this, function () { return new ListLoadingTracker_1.ListLoadingTracker(); }, options);
669
+ this.loaders.push(loader);
670
+ return loader;
671
+ };
672
+ DbRef.prototype.reload = function () {
673
+ this.loaders = [];
674
+ };
675
+ return DbRef;
676
+ }());
677
+ exports.DbRef = DbRef;
678
678
 
679
679
 
680
680
  /***/ }),
@@ -687,209 +687,209 @@ exports.DbRef = DbRef;
687
687
  /***/ (function(module, exports, __webpack_require__) {
688
688
 
689
689
  "use strict";
690
-
691
- Object.defineProperty(exports, "__esModule", { value: true });
692
- exports.DbTable = void 0;
693
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
694
- var I = tslib_1.__importStar(__webpack_require__(/*! immutable */ "immutable"));
695
- var uui_1 = __webpack_require__(/*! @epam/uui */ "@epam/uui");
696
- var immutable_1 = __webpack_require__(/*! immutable */ "immutable");
697
- var DbTable = /** @class */ (function () {
698
- function DbTable(schema, state, q) {
699
- this.schema = schema;
700
- this.state = state;
701
- this.q = q;
702
- if (!state) {
703
- var indexes = (schema.indexes || []).map(function (indexDef) {
704
- return {
705
- field: indexDef,
706
- map: I.Map(),
707
- };
708
- });
709
- this.state = { pk: I.Map(), indexes: indexes };
710
- }
711
- if (!q) {
712
- this.q = {};
713
- }
714
- }
715
- DbTable.prototype.keyToImmutable = function (id) {
716
- if (Array.isArray(id)) {
717
- return I.List(id);
718
- }
719
- else {
720
- return id;
721
- }
722
- };
723
- DbTable.prototype.byId = function (id) {
724
- return this.state.pk.get(this.keyToImmutable(id));
725
- };
726
- DbTable.prototype.getId = function (entity) {
727
- if (Array.isArray(this.schema.primaryKey)) {
728
- return this.schema.primaryKey.map(function (key) { return entity[key]; });
729
- }
730
- return entity[this.schema.primaryKey];
731
- };
732
- DbTable.prototype.update = function (mutate) {
733
- var clone = new this.constructor(this.schema, this.state, this.q);
734
- mutate(clone);
735
- return clone;
736
- };
737
- /* Mutation */
738
- DbTable.prototype.with = function (patch) {
739
- var _this = this;
740
- var updates = patch.map(function (entityPatch) {
741
- var id = _this.getId(entityPatch);
742
- var immId = _this.keyToImmutable(id);
743
- var existing = _this.state.pk.get(immId);
744
- var updated = entityPatch;
745
- if (existing) {
746
- updated = tslib_1.__assign(tslib_1.__assign({}, existing), entityPatch);
747
- }
748
- return { id: id, immId: immId, patch: entityPatch, existing: existing, updated: updated, updatedFieldsisNew: !existing };
749
- });
750
- var idVal = immutable_1.Seq.Keyed(updates.map(function (entity) { return [entity.immId, entity.updated]; }));
751
- var newPk = this.state.pk.merge(idVal);
752
- var newIndexes = this.state.indexes.map(function (index) {
753
- var newMap = index.map;
754
- var _loop_1 = function (n) {
755
- var update = updates[n];
756
- var newKey = update.updated[index.field];
757
- if (update.existing) {
758
- var oldKey = update.existing[index.field];
759
- if (oldKey !== newKey) {
760
- newMap = newMap.update(oldKey, function (set) { return set.remove(update.immId); });
761
- }
762
- }
763
- newMap = newMap.update(newKey, I.Set(), function (set) { return set.add(update.immId); });
764
- };
765
- for (var n = 0; n < updates.length; n++) {
766
- _loop_1(n);
767
- }
768
- return tslib_1.__assign(tslib_1.__assign({}, index), { map: newMap });
769
- });
770
- var newState = { pk: newPk, indexes: newIndexes };
771
- return this.update(function (t) { return t.state = newState; });
772
- };
773
- /* Query */
774
- DbTable.prototype.find = function (filter) {
775
- var _this = this;
776
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { filter: tslib_1.__assign(tslib_1.__assign({}, _this.q.filter), filter) }); });
777
- };
778
- DbTable.prototype.order = function (order) {
779
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: order }); });
780
- };
781
- DbTable.prototype.orderBy = function (field, direction) {
782
- if (direction === void 0) { direction = 'asc'; }
783
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: [{ field: field, direction: direction }] }); });
784
- };
785
- DbTable.prototype.thenBy = function (field, direction) {
786
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: tslib_1.__spreadArrays(t.q.sorting, [{ field: field, direction: direction }]) }); });
787
- };
788
- DbTable.prototype.search = function (text) {
789
- if (!this.schema.searchBy) {
790
- throw new Error("Can't search in the " + this.schema.typeName + " table - searchBy is not defined in the schema.");
791
- }
792
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { search: text }); });
793
- };
794
- /* Materializing */
795
- DbTable.prototype.range = function (from, count) {
796
- return this.runQuery(tslib_1.__assign(tslib_1.__assign({}, this.q), { range: { from: from, count: count } }));
797
- };
798
- DbTable.prototype.count = function () {
799
- return this.runQuery(this.q).length;
800
- };
801
- DbTable.prototype.one = function () {
802
- return this.runQuery(this.q)[0] || null;
803
- };
804
- DbTable.prototype.toArray = function () {
805
- return this.runQuery(this.q);
806
- };
807
- DbTable.prototype.map = function (fn) {
808
- return this.toArray().map(fn);
809
- };
810
- /* Query implementation */
811
- DbTable.prototype.runQuery = function (q) {
812
- var _this = this;
813
- var result = null;
814
- var filter = q.filter;
815
- if (filter) {
816
- var indexes = this.state.indexes;
817
- // Try to use indexes to fulfill filter conditions
818
- for (var n = 0; n < indexes.length; n++) {
819
- var index = indexes[n];
820
- if (index.field in filter) {
821
- var _a = filter, _b = index.field, condition = _a[_b], rest = tslib_1.__rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
822
- var conditionValues = null;
823
- if (condition != null && typeof condition === "object") {
824
- // Attempt to use index for 'in' and 'isNull' criteria.
825
- // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
826
- // - it's better to leave corner cases to getPatternPredicate
827
- var _c = condition, inCriteria = _c.in, nullCriteria = _c.isNull, restCriteria = tslib_1.__rest(_c, ["in", "isNull"]);
828
- if (inCriteria && Array.isArray(inCriteria)) {
829
- conditionValues = inCriteria;
830
- }
831
- else {
832
- restCriteria.in = inCriteria;
833
- }
834
- // Conditions in getPatternPredicate are composed with 'and' logic,
835
- // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
836
- // - just leave this to getPatternPredicate.
837
- // Let's just handle the a most common case { isNull: true } - find all null and undefined
838
- if (nullCriteria === true && !conditionValues) {
839
- conditionValues = [null, undefined];
840
- }
841
- else {
842
- restCriteria.in = inCriteria;
843
- }
844
- // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
845
- if (Object.keys(restCriteria).length > 0) {
846
- rest[index.field] = restCriteria;
847
- }
848
- }
849
- else {
850
- conditionValues = [condition];
851
- }
852
- if (conditionValues) {
853
- result = [];
854
- for (var i = 0; i < conditionValues.length; i++) {
855
- var idsSet = index.map.get(conditionValues[i]);
856
- if (idsSet) {
857
- var idsArray = idsSet.toArray();
858
- for (var j = 0; j < idsArray.length; j++) {
859
- var item = this.state.pk.get(idsArray[j]);
860
- result.push(item);
861
- }
862
- }
863
- }
864
- filter = Object.keys(rest).length > 0 ? rest : null;
865
- break;
866
- }
867
- }
868
- }
869
- }
870
- if (!result) {
871
- result = this.state.pk.toArray();
872
- }
873
- if (filter) {
874
- var predicate = uui_1.getPatternPredicate(q.filter);
875
- result = result.filter(predicate);
876
- }
877
- if (q.search) {
878
- var searchFilter_1 = uui_1.getSearchFilter(q.search);
879
- result = result.filter(function (item) { return searchFilter_1(_this.schema.searchBy.map(function (field) { return item[field]; })); });
880
- }
881
- if (q.sorting) {
882
- var comparer = uui_1.getOrderComparer(q.sorting);
883
- result = result.sort(comparer);
884
- }
885
- if (q.range) {
886
- result = result.slice(q.range.from, q.range.from + q.range.count);
887
- }
888
- return result;
889
- };
890
- return DbTable;
891
- }());
892
- exports.DbTable = DbTable;
690
+
691
+ Object.defineProperty(exports, "__esModule", { value: true });
692
+ exports.DbTable = void 0;
693
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
694
+ var I = tslib_1.__importStar(__webpack_require__(/*! immutable */ "immutable"));
695
+ var uui_1 = __webpack_require__(/*! @epam/uui */ "@epam/uui");
696
+ var immutable_1 = __webpack_require__(/*! immutable */ "immutable");
697
+ var DbTable = /** @class */ (function () {
698
+ function DbTable(schema, state, q) {
699
+ this.schema = schema;
700
+ this.state = state;
701
+ this.q = q;
702
+ if (!state) {
703
+ var indexes = (schema.indexes || []).map(function (indexDef) {
704
+ return {
705
+ field: indexDef,
706
+ map: I.Map(),
707
+ };
708
+ });
709
+ this.state = { pk: I.Map(), indexes: indexes };
710
+ }
711
+ if (!q) {
712
+ this.q = {};
713
+ }
714
+ }
715
+ DbTable.prototype.keyToImmutable = function (id) {
716
+ if (Array.isArray(id)) {
717
+ return I.List(id);
718
+ }
719
+ else {
720
+ return id;
721
+ }
722
+ };
723
+ DbTable.prototype.byId = function (id) {
724
+ return this.state.pk.get(this.keyToImmutable(id));
725
+ };
726
+ DbTable.prototype.getId = function (entity) {
727
+ if (Array.isArray(this.schema.primaryKey)) {
728
+ return this.schema.primaryKey.map(function (key) { return entity[key]; });
729
+ }
730
+ return entity[this.schema.primaryKey];
731
+ };
732
+ DbTable.prototype.update = function (mutate) {
733
+ var clone = new this.constructor(this.schema, this.state, this.q);
734
+ mutate(clone);
735
+ return clone;
736
+ };
737
+ /* Mutation */
738
+ DbTable.prototype.with = function (patch) {
739
+ var _this = this;
740
+ var updates = patch.map(function (entityPatch) {
741
+ var id = _this.getId(entityPatch);
742
+ var immId = _this.keyToImmutable(id);
743
+ var existing = _this.state.pk.get(immId);
744
+ var updated = entityPatch;
745
+ if (existing) {
746
+ updated = tslib_1.__assign(tslib_1.__assign({}, existing), entityPatch);
747
+ }
748
+ return { id: id, immId: immId, patch: entityPatch, existing: existing, updated: updated, updatedFieldsisNew: !existing };
749
+ });
750
+ var idVal = immutable_1.Seq.Keyed(updates.map(function (entity) { return [entity.immId, entity.updated]; }));
751
+ var newPk = this.state.pk.merge(idVal);
752
+ var newIndexes = this.state.indexes.map(function (index) {
753
+ var newMap = index.map;
754
+ var _loop_1 = function (n) {
755
+ var update = updates[n];
756
+ var newKey = update.updated[index.field];
757
+ if (update.existing) {
758
+ var oldKey = update.existing[index.field];
759
+ if (oldKey !== newKey) {
760
+ newMap = newMap.update(oldKey, function (set) { return set.remove(update.immId); });
761
+ }
762
+ }
763
+ newMap = newMap.update(newKey, I.Set(), function (set) { return set.add(update.immId); });
764
+ };
765
+ for (var n = 0; n < updates.length; n++) {
766
+ _loop_1(n);
767
+ }
768
+ return tslib_1.__assign(tslib_1.__assign({}, index), { map: newMap });
769
+ });
770
+ var newState = { pk: newPk, indexes: newIndexes };
771
+ return this.update(function (t) { return t.state = newState; });
772
+ };
773
+ /* Query */
774
+ DbTable.prototype.find = function (filter) {
775
+ var _this = this;
776
+ return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { filter: tslib_1.__assign(tslib_1.__assign({}, _this.q.filter), filter) }); });
777
+ };
778
+ DbTable.prototype.order = function (order) {
779
+ return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: order }); });
780
+ };
781
+ DbTable.prototype.orderBy = function (field, direction) {
782
+ if (direction === void 0) { direction = 'asc'; }
783
+ return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: [{ field: field, direction: direction }] }); });
784
+ };
785
+ DbTable.prototype.thenBy = function (field, direction) {
786
+ return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: tslib_1.__spreadArrays(t.q.sorting, [{ field: field, direction: direction }]) }); });
787
+ };
788
+ DbTable.prototype.search = function (text) {
789
+ if (!this.schema.searchBy) {
790
+ throw new Error("Can't search in the " + this.schema.typeName + " table - searchBy is not defined in the schema.");
791
+ }
792
+ return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { search: text }); });
793
+ };
794
+ /* Materializing */
795
+ DbTable.prototype.range = function (from, count) {
796
+ return this.runQuery(tslib_1.__assign(tslib_1.__assign({}, this.q), { range: { from: from, count: count } }));
797
+ };
798
+ DbTable.prototype.count = function () {
799
+ return this.runQuery(this.q).length;
800
+ };
801
+ DbTable.prototype.one = function () {
802
+ return this.runQuery(this.q)[0] || null;
803
+ };
804
+ DbTable.prototype.toArray = function () {
805
+ return this.runQuery(this.q);
806
+ };
807
+ DbTable.prototype.map = function (fn) {
808
+ return this.toArray().map(fn);
809
+ };
810
+ /* Query implementation */
811
+ DbTable.prototype.runQuery = function (q) {
812
+ var _this = this;
813
+ var result = null;
814
+ var filter = q.filter;
815
+ if (filter) {
816
+ var indexes = this.state.indexes;
817
+ // Try to use indexes to fulfill filter conditions
818
+ for (var n = 0; n < indexes.length; n++) {
819
+ var index = indexes[n];
820
+ if (index.field in filter) {
821
+ var _a = filter, _b = index.field, condition = _a[_b], rest = tslib_1.__rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
822
+ var conditionValues = null;
823
+ if (condition != null && typeof condition === "object") {
824
+ // Attempt to use index for 'in' and 'isNull' criteria.
825
+ // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
826
+ // - it's better to leave corner cases to getPatternPredicate
827
+ var _c = condition, inCriteria = _c.in, nullCriteria = _c.isNull, restCriteria = tslib_1.__rest(_c, ["in", "isNull"]);
828
+ if (inCriteria && Array.isArray(inCriteria)) {
829
+ conditionValues = inCriteria;
830
+ }
831
+ else {
832
+ restCriteria.in = inCriteria;
833
+ }
834
+ // Conditions in getPatternPredicate are composed with 'and' logic,
835
+ // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
836
+ // - just leave this to getPatternPredicate.
837
+ // Let's just handle the a most common case { isNull: true } - find all null and undefined
838
+ if (nullCriteria === true && !conditionValues) {
839
+ conditionValues = [null, undefined];
840
+ }
841
+ else {
842
+ restCriteria.in = inCriteria;
843
+ }
844
+ // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
845
+ if (Object.keys(restCriteria).length > 0) {
846
+ rest[index.field] = restCriteria;
847
+ }
848
+ }
849
+ else {
850
+ conditionValues = [condition];
851
+ }
852
+ if (conditionValues) {
853
+ result = [];
854
+ for (var i = 0; i < conditionValues.length; i++) {
855
+ var idsSet = index.map.get(conditionValues[i]);
856
+ if (idsSet) {
857
+ var idsArray = idsSet.toArray();
858
+ for (var j = 0; j < idsArray.length; j++) {
859
+ var item = this.state.pk.get(idsArray[j]);
860
+ result.push(item);
861
+ }
862
+ }
863
+ }
864
+ filter = Object.keys(rest).length > 0 ? rest : null;
865
+ break;
866
+ }
867
+ }
868
+ }
869
+ }
870
+ if (!result) {
871
+ result = this.state.pk.toArray();
872
+ }
873
+ if (filter) {
874
+ var predicate = uui_1.getPatternPredicate(q.filter);
875
+ result = result.filter(predicate);
876
+ }
877
+ if (q.search) {
878
+ var searchFilter_1 = uui_1.getSearchFilter(q.search);
879
+ result = result.filter(function (item) { return searchFilter_1(_this.schema.searchBy.map(function (field) { return item[field]; })); });
880
+ }
881
+ if (q.sorting) {
882
+ var comparer = uui_1.getOrderComparer(q.sorting);
883
+ result = result.sort(comparer);
884
+ }
885
+ if (q.range) {
886
+ result = result.slice(q.range.from, q.range.from + q.range.count);
887
+ }
888
+ return result;
889
+ };
890
+ return DbTable;
891
+ }());
892
+ exports.DbTable = DbTable;
893
893
 
894
894
 
895
895
  /***/ }),
@@ -902,99 +902,99 @@ exports.DbTable = DbTable;
902
902
  /***/ (function(module, exports, __webpack_require__) {
903
903
 
904
904
  "use strict";
905
-
906
- Object.defineProperty(exports, "__esModule", { value: true });
907
- exports.ListLoadingTracker = void 0;
908
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
909
- var ListLoadingTracker = /** @class */ (function () {
910
- function ListLoadingTracker(options) {
911
- this.options = options;
912
- this.cache = new Map();
913
- this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || (function (r) { return r; });
914
- }
915
- ListLoadingTracker.prototype.prepare = function (request) {
916
- var filter = request.filter, sorting = request.sorting, search = request.search, range = request.range, unknownFields = tslib_1.__rest(request, ["filter", "sorting", "search", "range"]);
917
- var options = {};
918
- if (filter) {
919
- options.filter = filter;
920
- }
921
- if (sorting) {
922
- options.sorting = sorting;
923
- }
924
- if (search) {
925
- options.search = search;
926
- }
927
- var keyObject = tslib_1.__assign(tslib_1.__assign({}, options), unknownFields);
928
- var key = JSON.stringify(keyObject);
929
- var entry = this.cache.get(key);
930
- if (!entry) {
931
- entry = { options: options, count: 0, maxCount: null, isComplete: false };
932
- this.cache.set(key, entry);
933
- }
934
- return { options: options, range: range, unknownFields: unknownFields, entry: entry };
935
- };
936
- ListLoadingTracker.prototype.diff = function (request) {
937
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
938
- if (entry.isComplete) {
939
- return null;
940
- }
941
- if (!request.range) {
942
- return request;
943
- }
944
- else {
945
- var requestedMax = request.range.from + request.range.count;
946
- var missingCount = requestedMax - entry.count;
947
- if (entry.maxCount) {
948
- missingCount = Math.min(missingCount, entry.maxCount);
949
- }
950
- if (missingCount > 0) {
951
- return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
952
- }
953
- else {
954
- return null;
955
- }
956
- }
957
- };
958
- ListLoadingTracker.prototype.count = function (request) {
959
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
960
- return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
961
- };
962
- ListLoadingTracker.prototype.append = function (request, response) {
963
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
964
- if (response) {
965
- var list = this.extractList(response);
966
- if (list.count) {
967
- entry.maxCount = list.count;
968
- }
969
- if (!range) {
970
- entry.count = list.items.length;
971
- entry.maxCount = list.items.length;
972
- entry.isComplete = true;
973
- }
974
- else {
975
- var from = (list.from == null) ? range.from : list.from;
976
- if (list.items.length > 0) {
977
- entry.count = Math.max(entry.count, from + list.items.length);
978
- }
979
- if (list.items.length < range.count) {
980
- entry.maxCount = from + list.items.length;
981
- entry.count = entry.maxCount;
982
- entry.isComplete = true;
983
- }
984
- }
985
- }
986
- else {
987
- if (range) {
988
- entry.count = Math.max(entry.count, request.range.from + request.range.count);
989
- }
990
- else {
991
- entry.isComplete = true;
992
- }
993
- }
994
- };
995
- return ListLoadingTracker;
996
- }());
997
- exports.ListLoadingTracker = ListLoadingTracker;
905
+
906
+ Object.defineProperty(exports, "__esModule", { value: true });
907
+ exports.ListLoadingTracker = void 0;
908
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
909
+ var ListLoadingTracker = /** @class */ (function () {
910
+ function ListLoadingTracker(options) {
911
+ this.options = options;
912
+ this.cache = new Map();
913
+ this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || (function (r) { return r; });
914
+ }
915
+ ListLoadingTracker.prototype.prepare = function (request) {
916
+ var filter = request.filter, sorting = request.sorting, search = request.search, range = request.range, unknownFields = tslib_1.__rest(request, ["filter", "sorting", "search", "range"]);
917
+ var options = {};
918
+ if (filter) {
919
+ options.filter = filter;
920
+ }
921
+ if (sorting) {
922
+ options.sorting = sorting;
923
+ }
924
+ if (search) {
925
+ options.search = search;
926
+ }
927
+ var keyObject = tslib_1.__assign(tslib_1.__assign({}, options), unknownFields);
928
+ var key = JSON.stringify(keyObject);
929
+ var entry = this.cache.get(key);
930
+ if (!entry) {
931
+ entry = { options: options, count: 0, maxCount: null, isComplete: false };
932
+ this.cache.set(key, entry);
933
+ }
934
+ return { options: options, range: range, unknownFields: unknownFields, entry: entry };
935
+ };
936
+ ListLoadingTracker.prototype.diff = function (request) {
937
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
938
+ if (entry.isComplete) {
939
+ return null;
940
+ }
941
+ if (!request.range) {
942
+ return request;
943
+ }
944
+ else {
945
+ var requestedMax = request.range.from + request.range.count;
946
+ var missingCount = requestedMax - entry.count;
947
+ if (entry.maxCount) {
948
+ missingCount = Math.min(missingCount, entry.maxCount);
949
+ }
950
+ if (missingCount > 0) {
951
+ return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
952
+ }
953
+ else {
954
+ return null;
955
+ }
956
+ }
957
+ };
958
+ ListLoadingTracker.prototype.count = function (request) {
959
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
960
+ return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
961
+ };
962
+ ListLoadingTracker.prototype.append = function (request, response) {
963
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
964
+ if (response) {
965
+ var list = this.extractList(response);
966
+ if (list.count) {
967
+ entry.maxCount = list.count;
968
+ }
969
+ if (!range) {
970
+ entry.count = list.items.length;
971
+ entry.maxCount = list.items.length;
972
+ entry.isComplete = true;
973
+ }
974
+ else {
975
+ var from = (list.from == null) ? range.from : list.from;
976
+ if (list.items.length > 0) {
977
+ entry.count = Math.max(entry.count, from + list.items.length);
978
+ }
979
+ if (list.items.length < range.count) {
980
+ entry.maxCount = from + list.items.length;
981
+ entry.count = entry.maxCount;
982
+ entry.isComplete = true;
983
+ }
984
+ }
985
+ }
986
+ else {
987
+ if (range) {
988
+ entry.count = Math.max(entry.count, request.range.from + request.range.count);
989
+ }
990
+ else {
991
+ entry.isComplete = true;
992
+ }
993
+ }
994
+ };
995
+ return ListLoadingTracker;
996
+ }());
997
+ exports.ListLoadingTracker = ListLoadingTracker;
998
998
 
999
999
 
1000
1000
  /***/ }),
@@ -1007,84 +1007,84 @@ exports.ListLoadingTracker = ListLoadingTracker;
1007
1007
  /***/ (function(module, exports, __webpack_require__) {
1008
1008
 
1009
1009
  "use strict";
1010
-
1011
- Object.defineProperty(exports, "__esModule", { value: true });
1012
- exports.Loader = void 0;
1013
- var Loader = /** @class */ (function () {
1014
- function Loader(dbRef, getTracker, options) {
1015
- var _this = this;
1016
- this.dbRef = dbRef;
1017
- this.getTracker = getTracker;
1018
- this.options = options;
1019
- this.currentRequests = new Set();
1020
- this.load = function (inputRequest) {
1021
- var result = {
1022
- isComplete: _this.loaded.diff(inputRequest) == null,
1023
- isLoading: false,
1024
- request: inputRequest,
1025
- missing: _this.loadedAndLoading.diff(inputRequest),
1026
- promise: null,
1027
- reload: null,
1028
- };
1029
- result.reload = function () {
1030
- result.missing = inputRequest;
1031
- _this.loadImpl(result);
1032
- };
1033
- if (result.isComplete) {
1034
- // Everything requested is already loaded
1035
- result.isComplete = true;
1036
- result.isLoading = false;
1037
- result.promise = Promise.resolve();
1038
- return result;
1039
- }
1040
- else {
1041
- if (result.missing == null) {
1042
- // Everything requested is either loaded already, or being loaded
1043
- result.isComplete = false;
1044
- result.isLoading = true;
1045
- // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
1046
- // So we track all running requests, and await all of them in such case.
1047
- result.promise = Promise.all(_this.currentRequests.entries()).then(function () { });
1048
- return result;
1049
- }
1050
- else {
1051
- // Something requested is not loaded, nor being loaded. Need to perform a new request.
1052
- _this.loadImpl(result);
1053
- return result;
1054
- }
1055
- }
1056
- };
1057
- this.loaded = getTracker();
1058
- this.loadedAndLoading = getTracker();
1059
- }
1060
- Loader.prototype.loadImpl = function (state) {
1061
- var _this = this;
1062
- this.loadedAndLoading.append(state.missing);
1063
- state.isLoading = true;
1064
- var serverRequest = state.missing;
1065
- if (this.options.clientToServerRequest) {
1066
- serverRequest = this.options.clientToServerRequest(serverRequest);
1067
- }
1068
- state.promise = this.options.api(serverRequest).then(function (result) {
1069
- _this.loaded.append(state.missing, result);
1070
- _this.loadedAndLoading.append(state.missing, result);
1071
- state.missing = null;
1072
- state.isLoading = false;
1073
- state.isComplete = true;
1074
- state.promise = Promise.resolve();
1075
- var flatten = _this.options.convertToPatch(result);
1076
- _this.options.postProcess && _this.options.postProcess(flatten);
1077
- _this.dbRef.commitFetch(flatten);
1078
- });
1079
- this.currentRequests.add(state.promise);
1080
- state.promise.finally(function () {
1081
- _this.currentRequests.delete(state.promise);
1082
- });
1083
- return state.promise;
1084
- };
1085
- return Loader;
1086
- }());
1087
- exports.Loader = Loader;
1010
+
1011
+ Object.defineProperty(exports, "__esModule", { value: true });
1012
+ exports.Loader = void 0;
1013
+ var Loader = /** @class */ (function () {
1014
+ function Loader(dbRef, getTracker, options) {
1015
+ var _this = this;
1016
+ this.dbRef = dbRef;
1017
+ this.getTracker = getTracker;
1018
+ this.options = options;
1019
+ this.currentRequests = new Set();
1020
+ this.load = function (inputRequest) {
1021
+ var result = {
1022
+ isComplete: _this.loaded.diff(inputRequest) == null,
1023
+ isLoading: false,
1024
+ request: inputRequest,
1025
+ missing: _this.loadedAndLoading.diff(inputRequest),
1026
+ promise: null,
1027
+ reload: null,
1028
+ };
1029
+ result.reload = function () {
1030
+ result.missing = inputRequest;
1031
+ _this.loadImpl(result);
1032
+ };
1033
+ if (result.isComplete) {
1034
+ // Everything requested is already loaded
1035
+ result.isComplete = true;
1036
+ result.isLoading = false;
1037
+ result.promise = Promise.resolve();
1038
+ return result;
1039
+ }
1040
+ else {
1041
+ if (result.missing == null) {
1042
+ // Everything requested is either loaded already, or being loaded
1043
+ result.isComplete = false;
1044
+ result.isLoading = true;
1045
+ // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
1046
+ // So we track all running requests, and await all of them in such case.
1047
+ result.promise = Promise.all(_this.currentRequests.entries()).then(function () { });
1048
+ return result;
1049
+ }
1050
+ else {
1051
+ // Something requested is not loaded, nor being loaded. Need to perform a new request.
1052
+ _this.loadImpl(result);
1053
+ return result;
1054
+ }
1055
+ }
1056
+ };
1057
+ this.loaded = getTracker();
1058
+ this.loadedAndLoading = getTracker();
1059
+ }
1060
+ Loader.prototype.loadImpl = function (state) {
1061
+ var _this = this;
1062
+ this.loadedAndLoading.append(state.missing);
1063
+ state.isLoading = true;
1064
+ var serverRequest = state.missing;
1065
+ if (this.options.clientToServerRequest) {
1066
+ serverRequest = this.options.clientToServerRequest(serverRequest);
1067
+ }
1068
+ state.promise = this.options.api(serverRequest).then(function (result) {
1069
+ _this.loaded.append(state.missing, result);
1070
+ _this.loadedAndLoading.append(state.missing, result);
1071
+ state.missing = null;
1072
+ state.isLoading = false;
1073
+ state.isComplete = true;
1074
+ state.promise = Promise.resolve();
1075
+ var flatten = _this.options.convertToPatch(result);
1076
+ _this.options.postProcess && _this.options.postProcess(flatten);
1077
+ _this.dbRef.commitFetch(flatten);
1078
+ });
1079
+ this.currentRequests.add(state.promise);
1080
+ state.promise.finally(function () {
1081
+ _this.currentRequests.delete(state.promise);
1082
+ });
1083
+ return state.promise;
1084
+ };
1085
+ return Loader;
1086
+ }());
1087
+ exports.Loader = Loader;
1088
1088
 
1089
1089
 
1090
1090
  /***/ }),
@@ -1097,25 +1097,25 @@ exports.Loader = Loader;
1097
1097
  /***/ (function(module, exports, __webpack_require__) {
1098
1098
 
1099
1099
  "use strict";
1100
-
1101
- Object.defineProperty(exports, "__esModule", { value: true });
1102
- exports.SimpleLoadingTracker = void 0;
1103
- var SimpleLoadingTracker = /** @class */ (function () {
1104
- function SimpleLoadingTracker() {
1105
- this.set = new Set();
1106
- }
1107
- SimpleLoadingTracker.prototype.getKey = function (request) {
1108
- return JSON.stringify(request);
1109
- };
1110
- SimpleLoadingTracker.prototype.diff = function (request) {
1111
- return this.set.has(this.getKey(request)) ? null : request;
1112
- };
1113
- SimpleLoadingTracker.prototype.append = function (request, result) {
1114
- this.set.add(this.getKey(request));
1115
- };
1116
- return SimpleLoadingTracker;
1117
- }());
1118
- exports.SimpleLoadingTracker = SimpleLoadingTracker;
1100
+
1101
+ Object.defineProperty(exports, "__esModule", { value: true });
1102
+ exports.SimpleLoadingTracker = void 0;
1103
+ var SimpleLoadingTracker = /** @class */ (function () {
1104
+ function SimpleLoadingTracker() {
1105
+ this.set = new Set();
1106
+ }
1107
+ SimpleLoadingTracker.prototype.getKey = function (request) {
1108
+ return JSON.stringify(request);
1109
+ };
1110
+ SimpleLoadingTracker.prototype.diff = function (request) {
1111
+ return this.set.has(this.getKey(request)) ? null : request;
1112
+ };
1113
+ SimpleLoadingTracker.prototype.append = function (request, result) {
1114
+ this.set.add(this.getKey(request));
1115
+ };
1116
+ return SimpleLoadingTracker;
1117
+ }());
1118
+ exports.SimpleLoadingTracker = SimpleLoadingTracker;
1119
1119
 
1120
1120
 
1121
1121
  /***/ }),
@@ -1128,17 +1128,17 @@ exports.SimpleLoadingTracker = SimpleLoadingTracker;
1128
1128
  /***/ (function(module, exports, __webpack_require__) {
1129
1129
 
1130
1130
  "use strict";
1131
-
1132
- Object.defineProperty(exports, "__esModule", { value: true });
1133
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1134
- tslib_1.__exportStar(__webpack_require__(/*! ./types */ "./src/types.ts"), exports);
1135
- tslib_1.__exportStar(__webpack_require__(/*! ./Db */ "./src/Db.ts"), exports);
1136
- tslib_1.__exportStar(__webpack_require__(/*! ./DbTable */ "./src/DbTable.ts"), exports);
1137
- tslib_1.__exportStar(__webpack_require__(/*! ./DbRef */ "./src/DbRef.ts"), exports);
1138
- tslib_1.__exportStar(__webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx"), exports);
1139
- tslib_1.__exportStar(__webpack_require__(/*! ./utils */ "./src/utils.ts"), exports);
1140
- tslib_1.__exportStar(__webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts"), exports);
1141
- tslib_1.__exportStar(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.ts"), exports);
1131
+
1132
+ Object.defineProperty(exports, "__esModule", { value: true });
1133
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1134
+ tslib_1.__exportStar(__webpack_require__(/*! ./types */ "./src/types.ts"), exports);
1135
+ tslib_1.__exportStar(__webpack_require__(/*! ./Db */ "./src/Db.ts"), exports);
1136
+ tslib_1.__exportStar(__webpack_require__(/*! ./DbTable */ "./src/DbTable.ts"), exports);
1137
+ tslib_1.__exportStar(__webpack_require__(/*! ./DbRef */ "./src/DbRef.ts"), exports);
1138
+ tslib_1.__exportStar(__webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx"), exports);
1139
+ tslib_1.__exportStar(__webpack_require__(/*! ./utils */ "./src/utils.ts"), exports);
1140
+ tslib_1.__exportStar(__webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts"), exports);
1141
+ tslib_1.__exportStar(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.ts"), exports);
1142
1142
 
1143
1143
 
1144
1144
  /***/ }),
@@ -1151,200 +1151,200 @@ tslib_1.__exportStar(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.t
1151
1151
  /***/ (function(module, exports, __webpack_require__) {
1152
1152
 
1153
1153
  "use strict";
1154
-
1155
- Object.defineProperty(exports, "__esModule", { value: true });
1156
- exports.getEntityParentDependencies = exports.getParentEntities = exports.hasServerFields = exports.isNew = exports.getId = exports.isClientOnly = exports.makeCumulativePatch = exports.isPatchBlank = exports.flattenResponse = exports.mergeEntityPatches = exports.unionPatches = void 0;
1157
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1158
- var types_1 = __webpack_require__(/*! ./types */ "./src/types.ts");
1159
- var I = tslib_1.__importStar(__webpack_require__(/*! immutable */ "immutable"));
1160
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1161
- var lodash_groupby_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.groupby */ "lodash.groupby"));
1162
- var lodash_map_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.map */ "lodash.map"));
1163
- var lodash_merge_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.merge */ "lodash.merge"));
1164
- var lodash_countby_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.countby */ "lodash.countby"));
1165
- var lodash_filter_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.filter */ "lodash.filter"));
1166
- var lodash_foreach_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.foreach */ "lodash.foreach"));
1167
- var lodash_pick_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.pick */ "lodash.pick"));
1168
- function unionPatches(patches) {
1169
- var result = {};
1170
- patches.forEach(function (patch) {
1171
- utils_1.objectKeys(patch).forEach(function (tableName) {
1172
- result[tableName] = result[tableName] ? tslib_1.__spreadArrays(result[tableName], patch[tableName]) : patch[tableName];
1173
- });
1174
- });
1175
- return result;
1176
- }
1177
- exports.unionPatches = unionPatches;
1178
- function mergeEntityPatches(tables, patch) {
1179
- var result = {};
1180
- utils_1.objectKeys(patch).forEach(function (key) {
1181
- var table = tables[key];
1182
- var groupedEntities = lodash_groupby_1.default(patch[key], function (item) { return table.getId(item); });
1183
- var tablePatch = lodash_map_1.default(groupedEntities, function (entities) {
1184
- var result = lodash_merge_1.default.apply(void 0, tslib_1.__spreadArrays([{}], entities));
1185
- if (true) {
1186
- var props = utils_1.objectKeys(result).filter(function (prop) {
1187
- return Object.keys(lodash_countby_1.default(entities.filter(function (entity) {
1188
- return entity[prop] !== undefined;
1189
- }), function (entity) { return entity[prop]; })).length > 1;
1190
- });
1191
- if (props.length) {
1192
- console.warn.apply(console, tslib_1.__spreadArrays(['mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n'], entities));
1193
- }
1194
- }
1195
- return result;
1196
- });
1197
- result[key] = tablePatch;
1198
- });
1199
- return result;
1200
- }
1201
- exports.mergeEntityPatches = mergeEntityPatches;
1202
- function flattenResponseHelper(result, object, tablesByTypeName) {
1203
- if (Array.isArray(object)) {
1204
- object.forEach(function (item) { return flattenResponseHelper(result, item, tablesByTypeName); });
1205
- }
1206
- else if (typeof object === 'object') {
1207
- var clone = {};
1208
- var tableKey = void 0;
1209
- var fields = {};
1210
- if ('__typename' in object) {
1211
- var table = tablesByTypeName[object.__typename];
1212
- if (table) {
1213
- tableKey = table.schema.tableName;
1214
- fields = table.schema.fields;
1215
- }
1216
- }
1217
- for (var key in object) {
1218
- var value = object[key];
1219
- var field = fields[key];
1220
- if ((field && !!field.disableFlatten)
1221
- || typeof value !== 'object'
1222
- || value === null
1223
- || (Array.isArray(value) && value.every(function (item) { return typeof item !== 'object'; }))) {
1224
- clone[key] = value;
1225
- }
1226
- else {
1227
- flattenResponseHelper(result, value, tablesByTypeName);
1228
- }
1229
- }
1230
- if (tableKey) {
1231
- result[tableKey].push(clone);
1232
- }
1233
- }
1234
- }
1235
- function flattenResponse(response, tables) {
1236
- var result = {};
1237
- var tablesByTypeName = {};
1238
- Object.values(tables).forEach(function (table) { return tablesByTypeName[table.schema.typeName] = table; });
1239
- utils_1.objectKeys(tables).forEach(function (tableName) { return tablesByTypeName; });
1240
- utils_1.objectKeys(tables).forEach(function (key) { return result[key] = []; });
1241
- flattenResponseHelper(result, response, tablesByTypeName);
1242
- return result;
1243
- }
1244
- exports.flattenResponse = flattenResponse;
1245
- function isPatchBlank(patch) {
1246
- return !utils_1.objectKeys(patch).some(function (key) { return patch[key].length > 0; });
1247
- }
1248
- exports.isPatchBlank = isPatchBlank;
1249
- /**
1250
- * Given several patches, creates a new single patch with all fields from all entities in all patches.
1251
- */
1252
- function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
1253
- var result = {};
1254
- utils_1.objectKeys(updatedDb.tables).forEach(function (entityName) {
1255
- var table = updatedDb.tables[entityName];
1256
- var schema = table.schema;
1257
- var ids = I.Set();
1258
- patches.forEach(function (patch) {
1259
- var filteredPatch = (patch[entityName] || []).filter(function (entity) { return hasServerFields(entity, schema, clientIdsMap, updatedDb.tables); });
1260
- ids = ids.union(filteredPatch.map(function (e) { return table.getId(e); }));
1261
- });
1262
- var entities = ids
1263
- .map(function (id) { return table.byId(id); })
1264
- .filter(function (e) { return !isClientOnly(e, schema); })
1265
- .toArray();
1266
- if (entities.length > 0) {
1267
- result[entityName] = entities;
1268
- }
1269
- });
1270
- return result;
1271
- }
1272
- exports.makeCumulativePatch = makeCumulativePatch;
1273
- function isClientOnly(entity, schema) {
1274
- if (typeof schema.isClientOnly === 'function') {
1275
- return schema.isClientOnly(entity);
1276
- }
1277
- return !!schema.isClientOnly;
1278
- }
1279
- exports.isClientOnly = isClientOnly;
1280
- function getId(entity, schema) {
1281
- if (typeof schema.primaryKey == 'string') {
1282
- return entity[schema.primaryKey];
1283
- }
1284
- var result = [];
1285
- lodash_foreach_1.default(lodash_pick_1.default(entity, schema.primaryKey), function (value) {
1286
- result.push(value);
1287
- });
1288
- return result;
1289
- }
1290
- exports.getId = getId;
1291
- function isNew(entity, schema, clientIdsMap) {
1292
- var id = getId(entity, schema);
1293
- return !clientIdsMap.clientToServer(id);
1294
- }
1295
- exports.isNew = isNew;
1296
- function hasServerFields(entity, schema, clientIdsMap, tables) {
1297
- var fullEntity = tslib_1.__assign(tslib_1.__assign({}, tables[schema.tableName].byId(entity.id) || {}), entity);
1298
- if (isClientOnly(fullEntity, schema)) {
1299
- return false;
1300
- }
1301
- return utils_1.objectKeys(entity).some(function (fieldName) {
1302
- var fieldSchema = schema.fields[fieldName];
1303
- return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
1304
- });
1305
- }
1306
- exports.hasServerFields = hasServerFields;
1307
- function getParentEntities(patch, tables) {
1308
- var dependenciesPatch = {};
1309
- utils_1.objectKeys(patch).forEach(function (key) {
1310
- var table = tables[key];
1311
- var tableSchema = table.schema;
1312
- var fields = lodash_filter_1.default(lodash_map_1.default(tableSchema.fields, function (field, name) { return (tslib_1.__assign(tslib_1.__assign({}, field), { name: name })); }), function (field) { return field.fk && field.fk.relationType == types_1.DbRelationType.Aggregation; });
1313
- var tablePatch = patch[key];
1314
- fields.forEach(function (field) {
1315
- var tableName = field.fk.tableName, name = field.name;
1316
- tablePatch.forEach(function (entity) {
1317
- var actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
1318
- var dbEntity = table.byId(table.getId(entity));
1319
- var parentEntity = tables[actualTableName].byId(dbEntity[name]);
1320
- var idFields = lodash_pick_1.default(parentEntity, tables[actualTableName].schema.primaryKey);
1321
- if (parentEntity) {
1322
- dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
1323
- dependenciesPatch[actualTableName].push(idFields);
1324
- }
1325
- });
1326
- });
1327
- });
1328
- return dependenciesPatch;
1329
- }
1330
- exports.getParentEntities = getParentEntities;
1331
- function getEntityParentDependencies(entity, entityName, tables) {
1332
- var _a;
1333
- var patch = (_a = {}, _a[entityName] = [entity], _a);
1334
- var resultPatches = [];
1335
- while (true) {
1336
- var parents = getParentEntities(patch, tables);
1337
- if (isPatchBlank(parents)) {
1338
- break;
1339
- }
1340
- resultPatches.push(parents);
1341
- patch = parents;
1342
- }
1343
- var result = unionPatches(tslib_1.__spreadArrays([patch], resultPatches));
1344
- result = mergeEntityPatches(tables, result);
1345
- return result;
1346
- }
1347
- exports.getEntityParentDependencies = getEntityParentDependencies;
1154
+
1155
+ Object.defineProperty(exports, "__esModule", { value: true });
1156
+ exports.getEntityParentDependencies = exports.getParentEntities = exports.hasServerFields = exports.isNew = exports.getId = exports.isClientOnly = exports.makeCumulativePatch = exports.isPatchBlank = exports.flattenResponse = exports.mergeEntityPatches = exports.unionPatches = void 0;
1157
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1158
+ var types_1 = __webpack_require__(/*! ./types */ "./src/types.ts");
1159
+ var I = tslib_1.__importStar(__webpack_require__(/*! immutable */ "immutable"));
1160
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1161
+ var lodash_groupby_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.groupby */ "lodash.groupby"));
1162
+ var lodash_map_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.map */ "lodash.map"));
1163
+ var lodash_merge_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.merge */ "lodash.merge"));
1164
+ var lodash_countby_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.countby */ "lodash.countby"));
1165
+ var lodash_filter_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.filter */ "lodash.filter"));
1166
+ var lodash_foreach_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.foreach */ "lodash.foreach"));
1167
+ var lodash_pick_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.pick */ "lodash.pick"));
1168
+ function unionPatches(patches) {
1169
+ var result = {};
1170
+ patches.forEach(function (patch) {
1171
+ utils_1.objectKeys(patch).forEach(function (tableName) {
1172
+ result[tableName] = result[tableName] ? tslib_1.__spreadArrays(result[tableName], patch[tableName]) : patch[tableName];
1173
+ });
1174
+ });
1175
+ return result;
1176
+ }
1177
+ exports.unionPatches = unionPatches;
1178
+ function mergeEntityPatches(tables, patch) {
1179
+ var result = {};
1180
+ utils_1.objectKeys(patch).forEach(function (key) {
1181
+ var table = tables[key];
1182
+ var groupedEntities = lodash_groupby_1.default(patch[key], function (item) { return table.getId(item); });
1183
+ var tablePatch = lodash_map_1.default(groupedEntities, function (entities) {
1184
+ var result = lodash_merge_1.default.apply(void 0, tslib_1.__spreadArrays([{}], entities));
1185
+ if (true) {
1186
+ var props = utils_1.objectKeys(result).filter(function (prop) {
1187
+ return Object.keys(lodash_countby_1.default(entities.filter(function (entity) {
1188
+ return entity[prop] !== undefined;
1189
+ }), function (entity) { return entity[prop]; })).length > 1;
1190
+ });
1191
+ if (props.length) {
1192
+ console.warn.apply(console, tslib_1.__spreadArrays(['mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n'], entities));
1193
+ }
1194
+ }
1195
+ return result;
1196
+ });
1197
+ result[key] = tablePatch;
1198
+ });
1199
+ return result;
1200
+ }
1201
+ exports.mergeEntityPatches = mergeEntityPatches;
1202
+ function flattenResponseHelper(result, object, tablesByTypeName) {
1203
+ if (Array.isArray(object)) {
1204
+ object.forEach(function (item) { return flattenResponseHelper(result, item, tablesByTypeName); });
1205
+ }
1206
+ else if (typeof object === 'object') {
1207
+ var clone = {};
1208
+ var tableKey = void 0;
1209
+ var fields = {};
1210
+ if ('__typename' in object) {
1211
+ var table = tablesByTypeName[object.__typename];
1212
+ if (table) {
1213
+ tableKey = table.schema.tableName;
1214
+ fields = table.schema.fields;
1215
+ }
1216
+ }
1217
+ for (var key in object) {
1218
+ var value = object[key];
1219
+ var field = fields[key];
1220
+ if ((field && !!field.disableFlatten)
1221
+ || typeof value !== 'object'
1222
+ || value === null
1223
+ || (Array.isArray(value) && value.every(function (item) { return typeof item !== 'object'; }))) {
1224
+ clone[key] = value;
1225
+ }
1226
+ else {
1227
+ flattenResponseHelper(result, value, tablesByTypeName);
1228
+ }
1229
+ }
1230
+ if (tableKey) {
1231
+ result[tableKey].push(clone);
1232
+ }
1233
+ }
1234
+ }
1235
+ function flattenResponse(response, tables) {
1236
+ var result = {};
1237
+ var tablesByTypeName = {};
1238
+ Object.values(tables).forEach(function (table) { return tablesByTypeName[table.schema.typeName] = table; });
1239
+ utils_1.objectKeys(tables).forEach(function (tableName) { return tablesByTypeName; });
1240
+ utils_1.objectKeys(tables).forEach(function (key) { return result[key] = []; });
1241
+ flattenResponseHelper(result, response, tablesByTypeName);
1242
+ return result;
1243
+ }
1244
+ exports.flattenResponse = flattenResponse;
1245
+ function isPatchBlank(patch) {
1246
+ return !utils_1.objectKeys(patch).some(function (key) { return patch[key].length > 0; });
1247
+ }
1248
+ exports.isPatchBlank = isPatchBlank;
1249
+ /**
1250
+ * Given several patches, creates a new single patch with all fields from all entities in all patches.
1251
+ */
1252
+ function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
1253
+ var result = {};
1254
+ utils_1.objectKeys(updatedDb.tables).forEach(function (entityName) {
1255
+ var table = updatedDb.tables[entityName];
1256
+ var schema = table.schema;
1257
+ var ids = I.Set();
1258
+ patches.forEach(function (patch) {
1259
+ var filteredPatch = (patch[entityName] || []).filter(function (entity) { return hasServerFields(entity, schema, clientIdsMap, updatedDb.tables); });
1260
+ ids = ids.union(filteredPatch.map(function (e) { return table.getId(e); }));
1261
+ });
1262
+ var entities = ids
1263
+ .map(function (id) { return table.byId(id); })
1264
+ .filter(function (e) { return !isClientOnly(e, schema); })
1265
+ .toArray();
1266
+ if (entities.length > 0) {
1267
+ result[entityName] = entities;
1268
+ }
1269
+ });
1270
+ return result;
1271
+ }
1272
+ exports.makeCumulativePatch = makeCumulativePatch;
1273
+ function isClientOnly(entity, schema) {
1274
+ if (typeof schema.isClientOnly === 'function') {
1275
+ return schema.isClientOnly(entity);
1276
+ }
1277
+ return !!schema.isClientOnly;
1278
+ }
1279
+ exports.isClientOnly = isClientOnly;
1280
+ function getId(entity, schema) {
1281
+ if (typeof schema.primaryKey == 'string') {
1282
+ return entity[schema.primaryKey];
1283
+ }
1284
+ var result = [];
1285
+ lodash_foreach_1.default(lodash_pick_1.default(entity, schema.primaryKey), function (value) {
1286
+ result.push(value);
1287
+ });
1288
+ return result;
1289
+ }
1290
+ exports.getId = getId;
1291
+ function isNew(entity, schema, clientIdsMap) {
1292
+ var id = getId(entity, schema);
1293
+ return !clientIdsMap.clientToServer(id);
1294
+ }
1295
+ exports.isNew = isNew;
1296
+ function hasServerFields(entity, schema, clientIdsMap, tables) {
1297
+ var fullEntity = tslib_1.__assign(tslib_1.__assign({}, tables[schema.tableName].byId(entity.id) || {}), entity);
1298
+ if (isClientOnly(fullEntity, schema)) {
1299
+ return false;
1300
+ }
1301
+ return utils_1.objectKeys(entity).some(function (fieldName) {
1302
+ var fieldSchema = schema.fields[fieldName];
1303
+ return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
1304
+ });
1305
+ }
1306
+ exports.hasServerFields = hasServerFields;
1307
+ function getParentEntities(patch, tables) {
1308
+ var dependenciesPatch = {};
1309
+ utils_1.objectKeys(patch).forEach(function (key) {
1310
+ var table = tables[key];
1311
+ var tableSchema = table.schema;
1312
+ var fields = lodash_filter_1.default(lodash_map_1.default(tableSchema.fields, function (field, name) { return (tslib_1.__assign(tslib_1.__assign({}, field), { name: name })); }), function (field) { return field.fk && field.fk.relationType == types_1.DbRelationType.Aggregation; });
1313
+ var tablePatch = patch[key];
1314
+ fields.forEach(function (field) {
1315
+ var tableName = field.fk.tableName, name = field.name;
1316
+ tablePatch.forEach(function (entity) {
1317
+ var actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
1318
+ var dbEntity = table.byId(table.getId(entity));
1319
+ var parentEntity = tables[actualTableName].byId(dbEntity[name]);
1320
+ var idFields = lodash_pick_1.default(parentEntity, tables[actualTableName].schema.primaryKey);
1321
+ if (parentEntity) {
1322
+ dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
1323
+ dependenciesPatch[actualTableName].push(idFields);
1324
+ }
1325
+ });
1326
+ });
1327
+ });
1328
+ return dependenciesPatch;
1329
+ }
1330
+ exports.getParentEntities = getParentEntities;
1331
+ function getEntityParentDependencies(entity, entityName, tables) {
1332
+ var _a;
1333
+ var patch = (_a = {}, _a[entityName] = [entity], _a);
1334
+ var resultPatches = [];
1335
+ while (true) {
1336
+ var parents = getParentEntities(patch, tables);
1337
+ if (isPatchBlank(parents)) {
1338
+ break;
1339
+ }
1340
+ resultPatches.push(parents);
1341
+ patch = parents;
1342
+ }
1343
+ var result = unionPatches(tslib_1.__spreadArrays([patch], resultPatches));
1344
+ result = mergeEntityPatches(tables, result);
1345
+ return result;
1346
+ }
1347
+ exports.getEntityParentDependencies = getEntityParentDependencies;
1348
1348
 
1349
1349
 
1350
1350
  /***/ }),
@@ -1357,27 +1357,27 @@ exports.getEntityParentDependencies = getEntityParentDependencies;
1357
1357
  /***/ (function(module, exports, __webpack_require__) {
1358
1358
 
1359
1359
  "use strict";
1360
-
1361
- Object.defineProperty(exports, "__esModule", { value: true });
1362
- exports.useDbView = exports.useDbRef = exports.DbContext = void 0;
1363
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1364
- var react_1 = __webpack_require__(/*! react */ "react");
1365
- exports.DbContext = react_1.createContext(null);
1366
- function useDbRef() {
1367
- return react_1.useContext(exports.DbContext);
1368
- }
1369
- exports.useDbRef = useDbRef;
1370
- function useDbView(fn, params, options) {
1371
- var dbRef = useDbRef();
1372
- var _a = react_1.useState(), state = _a[0], setState = _a[1];
1373
- var subscription = react_1.useMemo(function () { return dbRef.subscribe(tslib_1.__assign({ compute: fn }, options), params, setState); }, []);
1374
- subscription.update(params);
1375
- react_1.useEffect(function () {
1376
- return function () { return subscription.unsubscribe(); };
1377
- }, []);
1378
- return subscription.currentValue;
1379
- }
1380
- exports.useDbView = useDbView;
1360
+
1361
+ Object.defineProperty(exports, "__esModule", { value: true });
1362
+ exports.useDbView = exports.useDbRef = exports.DbContext = void 0;
1363
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1364
+ var react_1 = __webpack_require__(/*! react */ "react");
1365
+ exports.DbContext = react_1.createContext(null);
1366
+ function useDbRef() {
1367
+ return react_1.useContext(exports.DbContext);
1368
+ }
1369
+ exports.useDbRef = useDbRef;
1370
+ function useDbView(fn, params, options) {
1371
+ var dbRef = useDbRef();
1372
+ var _a = react_1.useState(), state = _a[0], setState = _a[1];
1373
+ var subscription = react_1.useMemo(function () { return dbRef.subscribe(tslib_1.__assign({ compute: fn }, options), params, setState); }, []);
1374
+ subscription.update(params);
1375
+ react_1.useEffect(function () {
1376
+ return function () { return subscription.unsubscribe(); };
1377
+ }, []);
1378
+ return subscription.currentValue;
1379
+ }
1380
+ exports.useDbView = useDbView;
1381
1381
 
1382
1382
 
1383
1383
  /***/ }),
@@ -1390,190 +1390,190 @@ exports.useDbView = useDbView;
1390
1390
  /***/ (function(module, exports, __webpack_require__) {
1391
1391
 
1392
1392
  "use strict";
1393
-
1394
- Object.defineProperty(exports, "__esModule", { value: true });
1395
- exports.TempIdMap = exports.isTempId = exports.getTempId = void 0;
1396
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1397
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1398
- var lastTempId = -1;
1399
- function getTempId() {
1400
- return --lastTempId;
1401
- }
1402
- exports.getTempId = getTempId;
1403
- function isTempId(val) {
1404
- return typeof val === 'number' && val < 0;
1405
- }
1406
- exports.isTempId = isTempId;
1407
- var TempIdMap = /** @class */ (function () {
1408
- function TempIdMap(db) {
1409
- var _this = this;
1410
- this.db = db;
1411
- this.serverToClientIds = new Map();
1412
- this.clientToServerIds = new Map();
1413
- this.clientToServer = function (id) { return _this.clientToServerIds.get(id); };
1414
- this.serverToClient = function (tableName, id) { return _this.getServerToClientMap(tableName).get(id); };
1415
- this.clientToServerRequest = function (request) {
1416
- request = tslib_1.__assign({}, request);
1417
- if (request.filter) {
1418
- request.filter = _this.clientToServerDataFilter(request.filter);
1419
- }
1420
- return request;
1421
- };
1422
- this.clientToServerDataFilter = function (filter) {
1423
- filter = tslib_1.__assign({}, filter);
1424
- var keys = Object.keys(filter);
1425
- // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
1426
- // We need to invent better heuristics or a schema otherwise.
1427
- var clientToServer = function (id) {
1428
- var found = _this.clientToServer(id);
1429
- if (found) {
1430
- return found;
1431
- }
1432
- else {
1433
- return id;
1434
- }
1435
- };
1436
- for (var n = 0; n < keys.length; n++) {
1437
- var key = keys[n];
1438
- var condition = filter[key];
1439
- if (condition != null && typeof condition === "object") {
1440
- condition = tslib_1.__assign({}, condition);
1441
- if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
1442
- condition.in = condition.in.map(clientToServer);
1443
- }
1444
- }
1445
- else {
1446
- condition = clientToServer(condition);
1447
- }
1448
- filter[key] = condition;
1449
- }
1450
- return filter;
1451
- };
1452
- }
1453
- TempIdMap.prototype.copyPatch = function (patch) {
1454
- var newPatch = tslib_1.__assign({}, patch);
1455
- utils_1.objectKeys(patch).forEach(function (tableName) {
1456
- var tablePatch = patch[tableName].map(function (entityPatch) { return (tslib_1.__assign({}, entityPatch)); });
1457
- newPatch[tableName] = tablePatch;
1458
- });
1459
- return newPatch;
1460
- };
1461
- // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
1462
- TempIdMap.prototype.mapFields = function (patch, filter, callback) {
1463
- var _this = this;
1464
- utils_1.objectKeys(patch).forEach(function (tableName) {
1465
- var schema = _this.db.tables[tableName].schema;
1466
- var fields = utils_1.objectKeys(schema.fields || [])
1467
- .map(function (fieldName) {
1468
- var fieldSchema = schema.fields[fieldName];
1469
- if (filter(fieldSchema, fieldName)) {
1470
- return { name: fieldName, schema: fieldSchema };
1471
- }
1472
- })
1473
- .filter(function (f) { return !!f; });
1474
- if (!fields.length) {
1475
- return;
1476
- }
1477
- patch[tableName].forEach(function (entityPatch) {
1478
- for (var n = 0; n < fields.length; n++) {
1479
- var field = fields[n];
1480
- var fieldValue = entityPatch[field.name];
1481
- callback(field.name, field.schema, fieldValue, entityPatch, tableName);
1482
- }
1483
- });
1484
- });
1485
- };
1486
- TempIdMap.prototype.getServerToClientMap = function (tableName) {
1487
- var existing = this.serverToClientIds.get(tableName);
1488
- if (existing) {
1489
- return existing;
1490
- }
1491
- else {
1492
- var newMap = new Map();
1493
- this.serverToClientIds.set(tableName, newMap);
1494
- return newMap;
1495
- }
1496
- };
1497
- TempIdMap.prototype.serverToClientPatch = function (patch) {
1498
- var _this = this;
1499
- patch = this.copyPatch(patch);
1500
- // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
1501
- this.mapFields(patch, function (f) { return f.isGenerated; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1502
- var clientId = _this.getServerToClientMap(tableName).get(fieldValue);
1503
- if (!clientId) {
1504
- clientId = getTempId();
1505
- _this.clientToServerIds.set(clientId, fieldValue);
1506
- _this.getServerToClientMap(tableName).set(fieldValue, clientId);
1507
- }
1508
- entityPatch[fieldName] = clientId;
1509
- });
1510
- this.mapFields(patch, function (f) { return !!(f.fk || (f.default != null) || f.toClient); }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1511
- var isUndefined = typeof (fieldValue) === 'undefined';
1512
- if (fieldSchema.default != null && fieldValue == null) {
1513
- fieldValue = fieldSchema.default;
1514
- isUndefined = false;
1515
- }
1516
- if (fieldSchema.fk && fieldValue != null) {
1517
- var fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
1518
- var clientId = _this.getServerToClientMap(fkTableName).get(fieldValue);
1519
- if (!clientId) {
1520
- clientId = getTempId();
1521
- _this.clientToServerIds.set(clientId, fieldValue);
1522
- _this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
1523
- }
1524
- fieldValue = clientId;
1525
- }
1526
- if (!isUndefined && fieldSchema.toClient) {
1527
- fieldValue = fieldSchema.toClient(fieldValue);
1528
- }
1529
- if (!isUndefined) {
1530
- entityPatch[fieldName] = fieldValue;
1531
- }
1532
- });
1533
- return patch;
1534
- };
1535
- TempIdMap.prototype.clientToServerPatch = function (patch) {
1536
- var _this = this;
1537
- patch = this.copyPatch(patch);
1538
- this.mapFields(patch, function (f) { return f.isGenerated || !!f.fk; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1539
- if (fieldValue != null) {
1540
- var existingId = _this.clientToServerIds.get(fieldValue);
1541
- if (existingId) {
1542
- entityPatch[fieldName] = existingId;
1543
- }
1544
- }
1545
- });
1546
- this.mapFields(patch, function (f) { return !(f.isClientOnly || f.isReadOnly) && !!f.toServer; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1547
- entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
1548
- });
1549
- this.mapFields(patch, function (meta) { return meta.isClientOnly || meta.isReadOnly; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1550
- delete entityPatch[fieldName];
1551
- });
1552
- return patch;
1553
- };
1554
- TempIdMap.prototype.appendServerMapping = function (response) {
1555
- var _this = this;
1556
- utils_1.objectKeys(response.submit).forEach(function (tableName) {
1557
- if (_this.db.tables[tableName]) {
1558
- var tablePatch = response.submit[tableName];
1559
- if (tablePatch) {
1560
- var serverToClientIds_1 = _this.getServerToClientMap(tableName);
1561
- var table_1 = _this.db.tables[tableName];
1562
- tablePatch.forEach(function (patch) {
1563
- if (isTempId(patch.id)) {
1564
- var clientId = patch.id;
1565
- var serverId = table_1.getId(patch.payload);
1566
- serverToClientIds_1.set(serverId, clientId);
1567
- _this.clientToServerIds.set(clientId, serverId);
1568
- }
1569
- });
1570
- }
1571
- }
1572
- });
1573
- };
1574
- return TempIdMap;
1575
- }());
1576
- exports.TempIdMap = TempIdMap;
1393
+
1394
+ Object.defineProperty(exports, "__esModule", { value: true });
1395
+ exports.TempIdMap = exports.isTempId = exports.getTempId = void 0;
1396
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1397
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1398
+ var lastTempId = -1;
1399
+ function getTempId() {
1400
+ return --lastTempId;
1401
+ }
1402
+ exports.getTempId = getTempId;
1403
+ function isTempId(val) {
1404
+ return typeof val === 'number' && val < 0;
1405
+ }
1406
+ exports.isTempId = isTempId;
1407
+ var TempIdMap = /** @class */ (function () {
1408
+ function TempIdMap(db) {
1409
+ var _this = this;
1410
+ this.db = db;
1411
+ this.serverToClientIds = new Map();
1412
+ this.clientToServerIds = new Map();
1413
+ this.clientToServer = function (id) { return _this.clientToServerIds.get(id); };
1414
+ this.serverToClient = function (tableName, id) { return _this.getServerToClientMap(tableName).get(id); };
1415
+ this.clientToServerRequest = function (request) {
1416
+ request = tslib_1.__assign({}, request);
1417
+ if (request.filter) {
1418
+ request.filter = _this.clientToServerDataFilter(request.filter);
1419
+ }
1420
+ return request;
1421
+ };
1422
+ this.clientToServerDataFilter = function (filter) {
1423
+ filter = tslib_1.__assign({}, filter);
1424
+ var keys = Object.keys(filter);
1425
+ // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
1426
+ // We need to invent better heuristics or a schema otherwise.
1427
+ var clientToServer = function (id) {
1428
+ var found = _this.clientToServer(id);
1429
+ if (found) {
1430
+ return found;
1431
+ }
1432
+ else {
1433
+ return id;
1434
+ }
1435
+ };
1436
+ for (var n = 0; n < keys.length; n++) {
1437
+ var key = keys[n];
1438
+ var condition = filter[key];
1439
+ if (condition != null && typeof condition === "object") {
1440
+ condition = tslib_1.__assign({}, condition);
1441
+ if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
1442
+ condition.in = condition.in.map(clientToServer);
1443
+ }
1444
+ }
1445
+ else {
1446
+ condition = clientToServer(condition);
1447
+ }
1448
+ filter[key] = condition;
1449
+ }
1450
+ return filter;
1451
+ };
1452
+ }
1453
+ TempIdMap.prototype.copyPatch = function (patch) {
1454
+ var newPatch = tslib_1.__assign({}, patch);
1455
+ utils_1.objectKeys(patch).forEach(function (tableName) {
1456
+ var tablePatch = patch[tableName].map(function (entityPatch) { return (tslib_1.__assign({}, entityPatch)); });
1457
+ newPatch[tableName] = tablePatch;
1458
+ });
1459
+ return newPatch;
1460
+ };
1461
+ // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
1462
+ TempIdMap.prototype.mapFields = function (patch, filter, callback) {
1463
+ var _this = this;
1464
+ utils_1.objectKeys(patch).forEach(function (tableName) {
1465
+ var schema = _this.db.tables[tableName].schema;
1466
+ var fields = utils_1.objectKeys(schema.fields || [])
1467
+ .map(function (fieldName) {
1468
+ var fieldSchema = schema.fields[fieldName];
1469
+ if (filter(fieldSchema, fieldName)) {
1470
+ return { name: fieldName, schema: fieldSchema };
1471
+ }
1472
+ })
1473
+ .filter(function (f) { return !!f; });
1474
+ if (!fields.length) {
1475
+ return;
1476
+ }
1477
+ patch[tableName].forEach(function (entityPatch) {
1478
+ for (var n = 0; n < fields.length; n++) {
1479
+ var field = fields[n];
1480
+ var fieldValue = entityPatch[field.name];
1481
+ callback(field.name, field.schema, fieldValue, entityPatch, tableName);
1482
+ }
1483
+ });
1484
+ });
1485
+ };
1486
+ TempIdMap.prototype.getServerToClientMap = function (tableName) {
1487
+ var existing = this.serverToClientIds.get(tableName);
1488
+ if (existing) {
1489
+ return existing;
1490
+ }
1491
+ else {
1492
+ var newMap = new Map();
1493
+ this.serverToClientIds.set(tableName, newMap);
1494
+ return newMap;
1495
+ }
1496
+ };
1497
+ TempIdMap.prototype.serverToClientPatch = function (patch) {
1498
+ var _this = this;
1499
+ patch = this.copyPatch(patch);
1500
+ // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
1501
+ this.mapFields(patch, function (f) { return f.isGenerated; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1502
+ var clientId = _this.getServerToClientMap(tableName).get(fieldValue);
1503
+ if (!clientId) {
1504
+ clientId = getTempId();
1505
+ _this.clientToServerIds.set(clientId, fieldValue);
1506
+ _this.getServerToClientMap(tableName).set(fieldValue, clientId);
1507
+ }
1508
+ entityPatch[fieldName] = clientId;
1509
+ });
1510
+ this.mapFields(patch, function (f) { return !!(f.fk || (f.default != null) || f.toClient); }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1511
+ var isUndefined = typeof (fieldValue) === 'undefined';
1512
+ if (fieldSchema.default != null && fieldValue == null) {
1513
+ fieldValue = fieldSchema.default;
1514
+ isUndefined = false;
1515
+ }
1516
+ if (fieldSchema.fk && fieldValue != null) {
1517
+ var fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
1518
+ var clientId = _this.getServerToClientMap(fkTableName).get(fieldValue);
1519
+ if (!clientId) {
1520
+ clientId = getTempId();
1521
+ _this.clientToServerIds.set(clientId, fieldValue);
1522
+ _this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
1523
+ }
1524
+ fieldValue = clientId;
1525
+ }
1526
+ if (!isUndefined && fieldSchema.toClient) {
1527
+ fieldValue = fieldSchema.toClient(fieldValue);
1528
+ }
1529
+ if (!isUndefined) {
1530
+ entityPatch[fieldName] = fieldValue;
1531
+ }
1532
+ });
1533
+ return patch;
1534
+ };
1535
+ TempIdMap.prototype.clientToServerPatch = function (patch) {
1536
+ var _this = this;
1537
+ patch = this.copyPatch(patch);
1538
+ this.mapFields(patch, function (f) { return f.isGenerated || !!f.fk; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1539
+ if (fieldValue != null) {
1540
+ var existingId = _this.clientToServerIds.get(fieldValue);
1541
+ if (existingId) {
1542
+ entityPatch[fieldName] = existingId;
1543
+ }
1544
+ }
1545
+ });
1546
+ this.mapFields(patch, function (f) { return !(f.isClientOnly || f.isReadOnly) && !!f.toServer; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1547
+ entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
1548
+ });
1549
+ this.mapFields(patch, function (meta) { return meta.isClientOnly || meta.isReadOnly; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1550
+ delete entityPatch[fieldName];
1551
+ });
1552
+ return patch;
1553
+ };
1554
+ TempIdMap.prototype.appendServerMapping = function (response) {
1555
+ var _this = this;
1556
+ utils_1.objectKeys(response.submit).forEach(function (tableName) {
1557
+ if (_this.db.tables[tableName]) {
1558
+ var tablePatch = response.submit[tableName];
1559
+ if (tablePatch) {
1560
+ var serverToClientIds_1 = _this.getServerToClientMap(tableName);
1561
+ var table_1 = _this.db.tables[tableName];
1562
+ tablePatch.forEach(function (patch) {
1563
+ if (isTempId(patch.id)) {
1564
+ var clientId = patch.id;
1565
+ var serverId = table_1.getId(patch.payload);
1566
+ serverToClientIds_1.set(serverId, clientId);
1567
+ _this.clientToServerIds.set(clientId, serverId);
1568
+ }
1569
+ });
1570
+ }
1571
+ }
1572
+ });
1573
+ };
1574
+ return TempIdMap;
1575
+ }());
1576
+ exports.TempIdMap = TempIdMap;
1577
1577
 
1578
1578
 
1579
1579
  /***/ }),
@@ -1586,14 +1586,14 @@ exports.TempIdMap = TempIdMap;
1586
1586
  /***/ (function(module, exports, __webpack_require__) {
1587
1587
 
1588
1588
  "use strict";
1589
-
1590
- Object.defineProperty(exports, "__esModule", { value: true });
1591
- exports.DbRelationType = void 0;
1592
- var DbRelationType;
1593
- (function (DbRelationType) {
1594
- DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
1595
- DbRelationType[DbRelationType["Association"] = 1] = "Association";
1596
- })(DbRelationType = exports.DbRelationType || (exports.DbRelationType = {}));
1589
+
1590
+ Object.defineProperty(exports, "__esModule", { value: true });
1591
+ exports.DbRelationType = void 0;
1592
+ var DbRelationType;
1593
+ (function (DbRelationType) {
1594
+ DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
1595
+ DbRelationType[DbRelationType["Association"] = 1] = "Association";
1596
+ })(DbRelationType = exports.DbRelationType || (exports.DbRelationType = {}));
1597
1597
 
1598
1598
 
1599
1599
  /***/ }),
@@ -1606,46 +1606,46 @@ var DbRelationType;
1606
1606
  /***/ (function(module, exports, __webpack_require__) {
1607
1607
 
1608
1608
  "use strict";
1609
-
1610
- Object.defineProperty(exports, "__esModule", { value: true });
1611
- exports.difference = exports.defaultCompareViewDependencies = exports.objectKeys = void 0;
1612
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1613
- var shallowequal_1 = tslib_1.__importDefault(__webpack_require__(/*! shallowequal */ "shallowequal"));
1614
- var lodash_zip_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.zip */ "lodash.zip"));
1615
- var lodash_transform_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.transform */ "lodash.transform"));
1616
- var lodash_isequal_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
1617
- // TBD: New typescript would contain better typing for this. Remove this hack after update.
1618
- exports.objectKeys = Object.keys;
1619
- function defaultCompareViewDependencies(prev, next) {
1620
- if (Array.isArray(prev) && Array.isArray(next)) {
1621
- if (prev.length === next.length) {
1622
- return lodash_zip_1.default(prev, next).every(function (_a) {
1623
- var p = _a[0], n = _a[1];
1624
- return shallowequal_1.default(p, n);
1625
- });
1626
- }
1627
- return false;
1628
- }
1629
- return shallowequal_1.default(prev, next);
1630
- }
1631
- exports.defaultCompareViewDependencies = defaultCompareViewDependencies;
1632
- /**
1633
- * Deep diff between two object, using lodash
1634
- * @param {Object} object Object compared
1635
- * @param {Object} base Object to compare with
1636
- * @return {Object} Return a new object who represent the diff
1637
- */
1638
- function difference(object, base) {
1639
- function changes(object, base) {
1640
- return lodash_transform_1.default(object, function (result, value, key) {
1641
- if (!lodash_isequal_1.default(value, base[key])) {
1642
- result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
1643
- }
1644
- });
1645
- }
1646
- return changes(object, base);
1647
- }
1648
- exports.difference = difference;
1609
+
1610
+ Object.defineProperty(exports, "__esModule", { value: true });
1611
+ exports.difference = exports.defaultCompareViewDependencies = exports.objectKeys = void 0;
1612
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1613
+ var shallowequal_1 = tslib_1.__importDefault(__webpack_require__(/*! shallowequal */ "shallowequal"));
1614
+ var lodash_zip_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.zip */ "lodash.zip"));
1615
+ var lodash_transform_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.transform */ "lodash.transform"));
1616
+ var lodash_isequal_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
1617
+ // TBD: New typescript would contain better typing for this. Remove this hack after update.
1618
+ exports.objectKeys = Object.keys;
1619
+ function defaultCompareViewDependencies(prev, next) {
1620
+ if (Array.isArray(prev) && Array.isArray(next)) {
1621
+ if (prev.length === next.length) {
1622
+ return lodash_zip_1.default(prev, next).every(function (_a) {
1623
+ var p = _a[0], n = _a[1];
1624
+ return shallowequal_1.default(p, n);
1625
+ });
1626
+ }
1627
+ return false;
1628
+ }
1629
+ return shallowequal_1.default(prev, next);
1630
+ }
1631
+ exports.defaultCompareViewDependencies = defaultCompareViewDependencies;
1632
+ /**
1633
+ * Deep diff between two object, using lodash
1634
+ * @param {Object} object Object compared
1635
+ * @param {Object} base Object to compare with
1636
+ * @return {Object} Return a new object who represent the diff
1637
+ */
1638
+ function difference(object, base) {
1639
+ function changes(object, base) {
1640
+ return lodash_transform_1.default(object, function (result, value, key) {
1641
+ if (!lodash_isequal_1.default(value, base[key])) {
1642
+ result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
1643
+ }
1644
+ });
1645
+ }
1646
+ return changes(object, base);
1647
+ }
1648
+ exports.difference = difference;
1649
1649
 
1650
1650
 
1651
1651
  /***/ }),
@@ -1657,7 +1657,7 @@ exports.difference = difference;
1657
1657
  /*! no static exports found */
1658
1658
  /***/ (function(module, exports, __webpack_require__) {
1659
1659
 
1660
- module.exports = __webpack_require__(/*! /Users/aliaksei_manetau/work/UUI/uui-db/index.tsx */"./index.tsx");
1660
+ module.exports = __webpack_require__(/*! C:\work\UUI\uui-db\index.tsx */"./index.tsx");
1661
1661
 
1662
1662
 
1663
1663
  /***/ }),