@epam/uui-db 4.11.0-alpha.1 → 5.0.0-alpha.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.esm.js ADDED
@@ -0,0 +1,1061 @@
1
+ import shallowEqual from 'shallowequal';
2
+ import zip from 'lodash.zip';
3
+ import transform from 'lodash.transform';
4
+ import isEqual from 'lodash.isequal';
5
+ import * as I from 'immutable';
6
+ import { Seq } from 'immutable';
7
+ import { getFilterPredicate, getSearchFilter, getOrderComparer, batch } from '@epam/uui-core';
8
+ import groupBy from 'lodash.groupby';
9
+ import map from 'lodash.map';
10
+ import merge from 'lodash.merge';
11
+ import countBy from 'lodash.countby';
12
+ import filter from 'lodash.filter';
13
+ import forEach from 'lodash.foreach';
14
+ import pick from 'lodash.pick';
15
+ import isEmpty from 'lodash.isempty';
16
+ import { createContext, useContext, useState, useMemo, useEffect } from 'react';
17
+
18
+ var DbRelationType;
19
+ (function (DbRelationType) {
20
+ DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
21
+ DbRelationType[DbRelationType["Association"] = 1] = "Association";
22
+ })(DbRelationType || (DbRelationType = {}));
23
+
24
+ // TBD: New typescript would contain better typing for this. Remove this hack after update.
25
+ let objectKeys = Object.keys;
26
+ function defaultCompareViewDependencies(prev, next) {
27
+ if (Array.isArray(prev) && Array.isArray(next)) {
28
+ if (prev.length === next.length) {
29
+ return zip(prev, next).every(([p, n]) => shallowEqual(p, n));
30
+ }
31
+ return false;
32
+ }
33
+ return shallowEqual(prev, next);
34
+ }
35
+ /**
36
+ * Deep diff between two object, using lodash
37
+ * @param {Object} object Object compared
38
+ * @param {Object} base Object to compare with
39
+ * @return {Object} Return a new object who represent the diff
40
+ */
41
+ function difference(object, base) {
42
+ function changes(object, base) {
43
+ return transform(object, function (result, value, key) {
44
+ if (!isEqual(value, base[key])) {
45
+ result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
46
+ }
47
+ });
48
+ }
49
+ return changes(object, base);
50
+ }
51
+
52
+ class Db {
53
+ constructor(tables, reusedCache) {
54
+ this.tables = tables;
55
+ this.viewCache = new Map();
56
+ /* Views (cached db projections) */
57
+ this.valueAbsent = Symbol("ValueAbsent");
58
+ if (reusedCache) {
59
+ this.viewCache = new Map(reusedCache);
60
+ }
61
+ else {
62
+ this.viewCache = new Map();
63
+ }
64
+ }
65
+ update(mutate) {
66
+ const clone = new this.constructor(this.tables, this.viewCache);
67
+ clone.tables = Object.assign({}, this.tables);
68
+ mutate(clone);
69
+ return clone;
70
+ }
71
+ with(patch) {
72
+ return this.update(db => {
73
+ objectKeys(db.tables).forEach(entityName => {
74
+ if (patch[entityName]) {
75
+ db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
76
+ }
77
+ });
78
+ });
79
+ }
80
+ runView(view, params) {
81
+ let cache = this.viewCache.get(view);
82
+ if (!cache) {
83
+ cache = new Map();
84
+ this.viewCache.set(view, cache);
85
+ }
86
+ const key = view.getKey ? view.getKey(params) : JSON.stringify(params);
87
+ let cacheItem = cache.get(key);
88
+ if (!cacheItem) {
89
+ cacheItem = {
90
+ dependencies: this.valueAbsent,
91
+ currentValue: this.valueAbsent,
92
+ computedOnDb: this.valueAbsent,
93
+ };
94
+ cache.set(key, cacheItem);
95
+ }
96
+ let shouldUpdate = this !== cacheItem.computedOnDb;
97
+ let dependencies = this.valueAbsent;
98
+ if (view.getDependencies) {
99
+ const compare = view.compareDependencies || defaultCompareViewDependencies;
100
+ dependencies = view.getDependencies(this, params);
101
+ shouldUpdate = !compare(cacheItem.dependencies, dependencies);
102
+ }
103
+ let previousValue = cacheItem.currentValue;
104
+ if (shouldUpdate) {
105
+ cacheItem.dependencies = dependencies;
106
+ let newValue = view.compute(this, params, dependencies);
107
+ cacheItem.computedOnDb = this;
108
+ let compareResults = view.compareResults || isEqual;
109
+ if (!compareResults(previousValue, newValue)) {
110
+ if (view.traceDiff) {
111
+ console.debug(difference(previousValue, newValue));
112
+ }
113
+ cacheItem.currentValue = newValue;
114
+ }
115
+ }
116
+ return cacheItem.currentValue;
117
+ }
118
+ }
119
+
120
+ /******************************************************************************
121
+ Copyright (c) Microsoft Corporation.
122
+
123
+ Permission to use, copy, modify, and/or distribute this software for any
124
+ purpose with or without fee is hereby granted.
125
+
126
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
127
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
128
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
129
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
130
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
131
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
132
+ PERFORMANCE OF THIS SOFTWARE.
133
+ ***************************************************************************** */
134
+
135
+ function __rest(s, e) {
136
+ var t = {};
137
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
138
+ t[p] = s[p];
139
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
140
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
141
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
142
+ t[p[i]] = s[p[i]];
143
+ }
144
+ return t;
145
+ }
146
+
147
+ function __awaiter(thisArg, _arguments, P, generator) {
148
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
149
+ return new (P || (P = Promise))(function (resolve, reject) {
150
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
151
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
152
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
153
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
154
+ });
155
+ }
156
+
157
+ class DbTable {
158
+ constructor(schema, state, q) {
159
+ this.schema = schema;
160
+ this.state = state;
161
+ this.q = q;
162
+ if (!state) {
163
+ const indexes = (schema.indexes || []).map(indexDef => {
164
+ return {
165
+ field: indexDef,
166
+ map: I.Map(),
167
+ };
168
+ });
169
+ this.state = { pk: I.Map(), indexes };
170
+ }
171
+ if (!q) {
172
+ this.q = {};
173
+ }
174
+ }
175
+ keyToImmutable(id) {
176
+ if (Array.isArray(id)) {
177
+ return I.List(id);
178
+ }
179
+ else {
180
+ return id;
181
+ }
182
+ }
183
+ byId(id) {
184
+ return this.state.pk.get(this.keyToImmutable(id));
185
+ }
186
+ getId(entity) {
187
+ if (Array.isArray(this.schema.primaryKey)) {
188
+ return this.schema.primaryKey.map((key) => entity[key]);
189
+ }
190
+ return entity[this.schema.primaryKey];
191
+ }
192
+ update(mutate) {
193
+ const clone = new this.constructor(this.schema, this.state, this.q);
194
+ mutate(clone);
195
+ return clone;
196
+ }
197
+ /* Mutation */
198
+ with(patch) {
199
+ const updates = patch.map(entityPatch => {
200
+ const id = this.getId(entityPatch);
201
+ const immId = this.keyToImmutable(id);
202
+ const existing = this.state.pk.get(immId);
203
+ let isDeleted = false;
204
+ let updated = entityPatch;
205
+ if (existing) {
206
+ updated = Object.assign(Object.assign({}, existing), entityPatch);
207
+ if (this.schema.deleteFlag) {
208
+ isDeleted = updated[this.schema.deleteFlag] === true;
209
+ }
210
+ }
211
+ return { id, immId, patch: entityPatch, existing, updated, isNew: !existing, isDeleted };
212
+ });
213
+ const idVal = Seq.Keyed(updates.map(entity => [entity.immId, entity.updated]));
214
+ let newPk = this.state.pk.merge(idVal);
215
+ // TBD: replace with deleteAll after migrating to immutable 4
216
+ updates.filter(u => u.isDeleted).forEach(u => {
217
+ newPk = newPk.delete(u.immId);
218
+ });
219
+ const newIndexes = this.state.indexes.map(index => {
220
+ let newMap = index.map;
221
+ for (let n = 0; n < updates.length; n++) {
222
+ let update = updates[n];
223
+ const newKey = update.updated[index.field];
224
+ if (update.existing) {
225
+ const oldKey = update.existing[index.field];
226
+ if (oldKey !== newKey || update.isDeleted) {
227
+ newMap = newMap.update(oldKey, set => set.remove(update.immId));
228
+ }
229
+ }
230
+ if (!update.isDeleted) {
231
+ newMap = newMap.update(newKey, I.Set(), set => set.add(update.immId));
232
+ }
233
+ }
234
+ return Object.assign(Object.assign({}, index), { map: newMap });
235
+ });
236
+ const newState = { pk: newPk, indexes: newIndexes };
237
+ return this.update(t => t.state = newState);
238
+ }
239
+ /* Query */
240
+ find(filter) {
241
+ return this.update(t => t.q = Object.assign(Object.assign({}, t.q), { filter: Object.assign(Object.assign({}, this.q.filter), filter) }));
242
+ }
243
+ order(order) {
244
+ return this.update(t => t.q = Object.assign(Object.assign({}, t.q), { sorting: order }));
245
+ }
246
+ orderBy(field, direction = 'asc') {
247
+ return this.update(t => t.q = Object.assign(Object.assign({}, t.q), { sorting: [{ field, direction }] }));
248
+ }
249
+ thenBy(field, direction) {
250
+ return this.update(t => t.q = Object.assign(Object.assign({}, t.q), { sorting: [...t.q.sorting, { field, direction }] }));
251
+ }
252
+ search(text) {
253
+ if (!this.schema.searchBy) {
254
+ throw new Error(`Can't search in the ${this.schema.typeName} table - searchBy is not defined in the schema.`);
255
+ }
256
+ return this.update(t => t.q = Object.assign(Object.assign({}, t.q), { search: text }));
257
+ }
258
+ /* Materializing */
259
+ range(from, count) {
260
+ return this.runQuery(Object.assign(Object.assign({}, this.q), { range: { from, count } }));
261
+ }
262
+ count() {
263
+ return this.runQuery(this.q).length;
264
+ }
265
+ one() {
266
+ return this.runQuery(this.q)[0] || null;
267
+ }
268
+ toArray() {
269
+ return this.runQuery(this.q);
270
+ }
271
+ map(fn) {
272
+ return this.toArray().map(fn);
273
+ }
274
+ /* Query implementation */
275
+ runQuery(q) {
276
+ let result = null;
277
+ let filter = q.filter;
278
+ if (filter) {
279
+ let indexes = this.state.indexes;
280
+ // Try to use indexes to fulfill filter conditions
281
+ for (let n = 0; n < indexes.length; n++) {
282
+ const index = indexes[n];
283
+ if (index.field in filter) {
284
+ const _a = filter, _b = index.field, condition = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
285
+ let conditionValues = null;
286
+ if (condition != null && typeof condition === "object") {
287
+ // Attempt to use index for 'in' and 'isNull' criteria.
288
+ // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
289
+ // - it's better to leave corner cases to getPatternPredicate
290
+ const _c = condition, { in: inCriteria, isNull: nullCriteria } = _c, restCriteria = __rest(_c, ["in", "isNull"]);
291
+ if (inCriteria && Array.isArray(inCriteria)) {
292
+ conditionValues = inCriteria;
293
+ }
294
+ else {
295
+ restCriteria.in = inCriteria;
296
+ }
297
+ // Conditions in getPatternPredicate are composed with 'and' logic,
298
+ // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
299
+ // - just leave this to getPatternPredicate.
300
+ // Let's just handle the a most common case { isNull: true } - find all null and undefined
301
+ if (nullCriteria === true && !conditionValues) {
302
+ conditionValues = [null, undefined];
303
+ }
304
+ else {
305
+ restCriteria.in = inCriteria;
306
+ }
307
+ // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
308
+ if (Object.keys(restCriteria).length > 0) {
309
+ rest[index.field] = restCriteria;
310
+ }
311
+ }
312
+ else {
313
+ conditionValues = [condition];
314
+ }
315
+ if (conditionValues) {
316
+ result = [];
317
+ for (let i = 0; i < conditionValues.length; i++) {
318
+ const idsSet = index.map.get(conditionValues[i]);
319
+ if (idsSet) {
320
+ const idsArray = idsSet.toArray();
321
+ for (let j = 0; j < idsArray.length; j++) {
322
+ const item = this.state.pk.get(idsArray[j]);
323
+ result.push(item);
324
+ }
325
+ }
326
+ }
327
+ filter = Object.keys(rest).length > 0 ? rest : null;
328
+ break;
329
+ }
330
+ }
331
+ }
332
+ }
333
+ if (!result) {
334
+ result = this.state.pk.toArray();
335
+ }
336
+ if (filter) {
337
+ let predicate = getFilterPredicate(q.filter);
338
+ result = result.filter(predicate);
339
+ }
340
+ if (q.search) {
341
+ let searchFilter = getSearchFilter(q.search);
342
+ result = result.filter(item => searchFilter(this.schema.searchBy.map(field => item[field])));
343
+ }
344
+ if (q.sorting) {
345
+ let comparer = getOrderComparer(q.sorting);
346
+ result = result.sort(comparer);
347
+ }
348
+ if (q.range) {
349
+ result = result.slice(q.range.from, q.range.from + q.range.count);
350
+ }
351
+ return result;
352
+ }
353
+ }
354
+
355
+ function unionPatches(patches) {
356
+ const result = {};
357
+ patches.forEach(patch => {
358
+ objectKeys(patch).forEach(tableName => {
359
+ result[tableName] = result[tableName] ? [...result[tableName], ...patch[tableName]] : patch[tableName];
360
+ });
361
+ });
362
+ return result;
363
+ }
364
+ function mergeEntityPatches(tables, patch) {
365
+ const result = {};
366
+ objectKeys(patch).forEach(key => {
367
+ const table = tables[key];
368
+ const groupedEntities = groupBy(patch[key], item => table.getId(item));
369
+ const tablePatch = map(groupedEntities, entities => {
370
+ const result = merge({}, ...entities);
371
+ if (process.env.NODE_ENV !== 'production') {
372
+ const props = objectKeys(result).filter(prop => Object.keys(countBy(entities.filter(entity => entity[prop] !== undefined), entity => entity[prop])).length > 1);
373
+ if (props.length) {
374
+ console.warn('mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n', ...entities);
375
+ }
376
+ }
377
+ return result;
378
+ });
379
+ result[key] = tablePatch;
380
+ });
381
+ return result;
382
+ }
383
+ function flattenResponseHelper(result, object, tablesByTypeName) {
384
+ if (Array.isArray(object)) {
385
+ object.forEach(item => flattenResponseHelper(result, item, tablesByTypeName));
386
+ }
387
+ else if (typeof object === 'object') {
388
+ const clone = {};
389
+ let tableKey;
390
+ let fields = {};
391
+ if ('__typename' in object) {
392
+ const table = tablesByTypeName[object.__typename];
393
+ if (table) {
394
+ tableKey = table.schema.tableName;
395
+ fields = table.schema.fields;
396
+ }
397
+ }
398
+ for (let key in object) {
399
+ const value = object[key];
400
+ const field = fields[key];
401
+ if ((field && !!field.disableFlatten)
402
+ || typeof value !== 'object'
403
+ || value === null
404
+ || (Array.isArray(value) && value.every(item => typeof item !== 'object'))) {
405
+ clone[key] = value;
406
+ }
407
+ else {
408
+ flattenResponseHelper(result, value, tablesByTypeName);
409
+ }
410
+ }
411
+ if (tableKey) {
412
+ result[tableKey].push(clone);
413
+ }
414
+ }
415
+ }
416
+ function flattenResponse(response, tables) {
417
+ const result = {};
418
+ let tablesByTypeName = {};
419
+ Object.values(tables).forEach(table => tablesByTypeName[table.schema.typeName] = table);
420
+ objectKeys(tables).forEach(tableName => tablesByTypeName);
421
+ objectKeys(tables).forEach(key => result[key] = []);
422
+ flattenResponseHelper(result, response, tablesByTypeName);
423
+ return result;
424
+ }
425
+ function isPatchBlank(patch) {
426
+ return !objectKeys(patch).some(key => patch[key].length > 0);
427
+ }
428
+ /**
429
+ * Given several patches, creates a new single patch with all fields from all entities in all patches.
430
+ */
431
+ function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
432
+ const result = {};
433
+ objectKeys(updatedDb.tables).forEach(entityName => {
434
+ const table = updatedDb.tables[entityName];
435
+ const schema = table.schema;
436
+ let ids = I.Set();
437
+ patches.forEach(patch => {
438
+ let filteredPatch = (patch[entityName] || []).filter(entity => hasServerFields(entity, schema, clientIdsMap, updatedDb.tables));
439
+ ids = ids.union(filteredPatch.map(e => table.getId(e)));
440
+ });
441
+ const entities = ids
442
+ .map(id => table.byId(id))
443
+ .filter(e => !isClientOnly(e, schema))
444
+ .toArray();
445
+ if (entities.length > 0) {
446
+ result[entityName] = entities;
447
+ }
448
+ });
449
+ return result;
450
+ }
451
+ function isClientOnly(entity, schema) {
452
+ if (typeof schema.isClientOnly === 'function') {
453
+ return schema.isClientOnly(entity);
454
+ }
455
+ return !!schema.isClientOnly;
456
+ }
457
+ function getId(entity, schema) {
458
+ if (typeof schema.primaryKey == 'string') {
459
+ return entity[schema.primaryKey];
460
+ }
461
+ const result = [];
462
+ forEach(pick(entity, schema.primaryKey), (value) => {
463
+ result.push(value);
464
+ });
465
+ return result;
466
+ }
467
+ function isNew(entity, schema, clientIdsMap) {
468
+ const id = getId(entity, schema);
469
+ return !clientIdsMap.clientToServer(id);
470
+ }
471
+ function hasServerFields(entity, schema, clientIdsMap, tables) {
472
+ const fullEntity = Object.assign(Object.assign({}, tables[schema.tableName].byId(entity.id) || {}), entity);
473
+ if (isClientOnly(fullEntity, schema)) {
474
+ return false;
475
+ }
476
+ return objectKeys(entity).some(fieldName => {
477
+ const fieldSchema = schema.fields[fieldName];
478
+ return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
479
+ });
480
+ }
481
+ function getParentEntities(patch, tables) {
482
+ const dependenciesPatch = {};
483
+ objectKeys(patch).forEach(key => {
484
+ const table = tables[key];
485
+ const tableSchema = table.schema;
486
+ const fields = filter(map(tableSchema.fields, (field, name) => (Object.assign(Object.assign({}, field), { name }))), field => field.fk && field.fk.relationType == DbRelationType.Aggregation);
487
+ const tablePatch = patch[key];
488
+ fields.forEach(field => {
489
+ const { fk: { tableName }, name } = field;
490
+ tablePatch.forEach(entity => {
491
+ const actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
492
+ const dbEntity = table.byId(table.getId(entity));
493
+ const parentEntity = tables[actualTableName].byId(dbEntity[name]);
494
+ const idFields = pick(parentEntity, tables[actualTableName].schema.primaryKey);
495
+ if (parentEntity) {
496
+ dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
497
+ dependenciesPatch[actualTableName].push(idFields);
498
+ }
499
+ });
500
+ });
501
+ });
502
+ return dependenciesPatch;
503
+ }
504
+ function getEntityParentDependencies(entity, entityName, tables) {
505
+ let patch = { [entityName]: [entity] };
506
+ const resultPatches = [];
507
+ while (true) {
508
+ let parents = getParentEntities(patch, tables);
509
+ if (isPatchBlank(parents)) {
510
+ break;
511
+ }
512
+ resultPatches.push(parents);
513
+ patch = parents;
514
+ }
515
+ let result = unionPatches([patch, ...resultPatches]);
516
+ result = mergeEntityPatches(tables, result);
517
+ return result;
518
+ }
519
+
520
+ let lastTempId = -1;
521
+ function getTempId() {
522
+ return --lastTempId;
523
+ }
524
+ function isTempId(val) {
525
+ return typeof val === 'number' && val < 0;
526
+ }
527
+ class TempIdMap {
528
+ constructor(db) {
529
+ this.db = db;
530
+ this.serverToClientIds = new Map();
531
+ this.clientToServerIds = new Map();
532
+ this.clientToServer = (id) => this.clientToServerIds.get(id);
533
+ this.serverToClient = (tableName, id) => this.getServerToClientMap(tableName).get(id);
534
+ this.clientToServerRequest = (request) => {
535
+ request = Object.assign({}, request);
536
+ if (request.filter) {
537
+ request.filter = this.clientToServerDataFilter(request.filter);
538
+ }
539
+ return request;
540
+ };
541
+ this.clientToServerDataFilter = (filter) => {
542
+ filter = Object.assign({}, filter);
543
+ const keys = Object.keys(filter);
544
+ // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
545
+ // We need to invent better heuristics or a schema otherwise.
546
+ const clientToServer = (id) => {
547
+ const found = this.clientToServer(id);
548
+ if (found) {
549
+ return found;
550
+ }
551
+ else {
552
+ return id;
553
+ }
554
+ };
555
+ for (let n = 0; n < keys.length; n++) {
556
+ const key = keys[n];
557
+ let condition = filter[key];
558
+ if (condition != null && typeof condition === "object") {
559
+ condition = Object.assign({}, condition);
560
+ if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
561
+ condition.in = condition.in.map(clientToServer);
562
+ }
563
+ }
564
+ else {
565
+ condition = clientToServer(condition);
566
+ }
567
+ filter[key] = condition;
568
+ }
569
+ return filter;
570
+ };
571
+ }
572
+ copyPatch(patch) {
573
+ const newPatch = Object.assign({}, patch);
574
+ objectKeys(patch).forEach(tableName => {
575
+ let tablePatch = patch[tableName].map(entityPatch => (Object.assign({}, entityPatch)));
576
+ newPatch[tableName] = tablePatch;
577
+ });
578
+ return newPatch;
579
+ }
580
+ // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
581
+ mapFields(patch, filter, callback) {
582
+ objectKeys(patch).forEach(tableName => {
583
+ const schema = this.db.tables[tableName].schema;
584
+ const fields = objectKeys(schema.fields || [])
585
+ .map(fieldName => {
586
+ const fieldSchema = schema.fields[fieldName];
587
+ if (filter(fieldSchema, fieldName)) {
588
+ return { name: fieldName, schema: fieldSchema };
589
+ }
590
+ })
591
+ .filter(f => !!f);
592
+ if (!fields.length) {
593
+ return;
594
+ }
595
+ patch[tableName].forEach(entityPatch => {
596
+ for (let n = 0; n < fields.length; n++) {
597
+ const field = fields[n];
598
+ const fieldValue = entityPatch[field.name];
599
+ callback(field.name, field.schema, fieldValue, entityPatch, tableName);
600
+ }
601
+ });
602
+ });
603
+ }
604
+ getServerToClientMap(tableName) {
605
+ const existing = this.serverToClientIds.get(tableName);
606
+ if (existing) {
607
+ return existing;
608
+ }
609
+ else {
610
+ const newMap = new Map();
611
+ this.serverToClientIds.set(tableName, newMap);
612
+ return newMap;
613
+ }
614
+ }
615
+ serverToClientPatch(patch) {
616
+ patch = this.copyPatch(patch);
617
+ // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
618
+ this.mapFields(patch, f => f.isGenerated, (fieldName, fieldSchema, fieldValue, entityPatch, tableName) => {
619
+ let clientId = this.getServerToClientMap(tableName).get(fieldValue);
620
+ if (!clientId) {
621
+ clientId = getTempId();
622
+ this.clientToServerIds.set(clientId, fieldValue);
623
+ this.getServerToClientMap(tableName).set(fieldValue, clientId);
624
+ }
625
+ entityPatch[fieldName] = clientId;
626
+ });
627
+ this.mapFields(patch, f => !!(f.fk || (f.default != null) || f.toClient), (fieldName, fieldSchema, fieldValue, entityPatch, tableName) => {
628
+ let isUndefined = typeof (fieldValue) === 'undefined';
629
+ if (fieldSchema.default != null && fieldValue == null) {
630
+ fieldValue = fieldSchema.default;
631
+ isUndefined = false;
632
+ }
633
+ if (fieldSchema.fk && fieldValue != null) {
634
+ const fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
635
+ let clientId = this.getServerToClientMap(fkTableName).get(fieldValue);
636
+ if (!clientId) {
637
+ clientId = getTempId();
638
+ this.clientToServerIds.set(clientId, fieldValue);
639
+ this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
640
+ }
641
+ fieldValue = clientId;
642
+ }
643
+ if (!isUndefined && fieldSchema.toClient) {
644
+ fieldValue = fieldSchema.toClient(fieldValue);
645
+ }
646
+ if (!isUndefined) {
647
+ entityPatch[fieldName] = fieldValue;
648
+ }
649
+ });
650
+ return patch;
651
+ }
652
+ clientToServerPatch(patch) {
653
+ patch = this.copyPatch(patch);
654
+ this.mapFields(patch, f => f.isGenerated || !!f.fk, (fieldName, fieldSchema, fieldValue, entityPatch, tableName) => {
655
+ if (fieldValue != null) {
656
+ const existingId = this.clientToServerIds.get(fieldValue);
657
+ if (existingId) {
658
+ entityPatch[fieldName] = existingId;
659
+ }
660
+ }
661
+ });
662
+ this.mapFields(patch, f => !(f.isClientOnly || f.isReadOnly) && !!f.toServer, (fieldName, fieldSchema, fieldValue, entityPatch, tableName) => {
663
+ entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
664
+ });
665
+ this.mapFields(patch, meta => meta.isClientOnly || meta.isReadOnly, (fieldName, fieldSchema, fieldValue, entityPatch, tableName) => {
666
+ delete entityPatch[fieldName];
667
+ });
668
+ return patch;
669
+ }
670
+ appendServerMapping(response) {
671
+ objectKeys(response.submit).forEach(tableName => {
672
+ if (this.db.tables[tableName]) {
673
+ const tablePatch = response.submit[tableName];
674
+ if (tablePatch) {
675
+ const serverToClientIds = this.getServerToClientMap(tableName);
676
+ const table = this.db.tables[tableName];
677
+ tablePatch.forEach(patch => {
678
+ if (isTempId(patch.id)) {
679
+ const clientId = patch.id;
680
+ const serverId = table.getId(patch.payload);
681
+ serverToClientIds.set(serverId, clientId);
682
+ this.clientToServerIds.set(clientId, serverId);
683
+ }
684
+ });
685
+ }
686
+ }
687
+ });
688
+ }
689
+ }
690
+
691
+ class Loader {
692
+ constructor(dbRef, getTracker, options) {
693
+ this.dbRef = dbRef;
694
+ this.getTracker = getTracker;
695
+ this.options = options;
696
+ this.currentRequests = new Set();
697
+ this.load = (inputRequest) => {
698
+ const result = {
699
+ isComplete: this.loaded.diff(inputRequest) == null,
700
+ isLoading: false,
701
+ request: inputRequest,
702
+ missing: this.loadedAndLoading.diff(inputRequest),
703
+ promise: null,
704
+ reload: null,
705
+ };
706
+ result.reload = () => {
707
+ result.missing = inputRequest;
708
+ this.loadImpl(result);
709
+ };
710
+ if (result.isComplete) {
711
+ // Everything requested is already loaded
712
+ result.isComplete = true;
713
+ result.isLoading = false;
714
+ result.promise = Promise.resolve();
715
+ return result;
716
+ }
717
+ else {
718
+ if (result.missing == null) {
719
+ // Everything requested is either loaded already, or being loaded
720
+ result.isComplete = false;
721
+ result.isLoading = true;
722
+ // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
723
+ // So we track all running requests, and await all of them in such case.
724
+ result.promise = Promise.all(this.currentRequests.entries()).then(() => { });
725
+ return result;
726
+ }
727
+ else {
728
+ // Something requested is not loaded, nor being loaded. Need to perform a new request.
729
+ this.loadImpl(result);
730
+ return result;
731
+ }
732
+ }
733
+ };
734
+ this.loaded = getTracker();
735
+ this.loadedAndLoading = getTracker();
736
+ }
737
+ loadImpl(state) {
738
+ this.loadedAndLoading.append(state.missing);
739
+ state.isLoading = true;
740
+ let serverRequest = state.missing;
741
+ if (this.options.clientToServerRequest) {
742
+ serverRequest = this.options.clientToServerRequest(serverRequest);
743
+ }
744
+ state.promise = this.options.api(serverRequest).then(result => {
745
+ this.loaded.append(state.missing, result);
746
+ this.loadedAndLoading.append(state.missing, result);
747
+ state.missing = null;
748
+ state.isLoading = false;
749
+ state.isComplete = true;
750
+ state.promise = Promise.resolve();
751
+ const flatten = this.options.convertToPatch(result);
752
+ this.options.postProcess && this.options.postProcess(flatten);
753
+ this.dbRef.commitFetch(flatten);
754
+ });
755
+ this.currentRequests.add(state.promise);
756
+ state.promise.finally(() => {
757
+ this.currentRequests.delete(state.promise);
758
+ });
759
+ return state.promise;
760
+ }
761
+ }
762
+
763
+ class SimpleLoadingTracker {
764
+ constructor() {
765
+ this.set = new Set();
766
+ }
767
+ getKey(request) {
768
+ return JSON.stringify(request);
769
+ }
770
+ diff(request) {
771
+ return this.set.has(this.getKey(request)) ? null : request;
772
+ }
773
+ append(request, result) {
774
+ this.set.add(this.getKey(request));
775
+ }
776
+ }
777
+
778
+ class ListLoadingTracker {
779
+ constructor(options) {
780
+ this.options = options;
781
+ this.cache = new Map();
782
+ this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || ((r) => r);
783
+ }
784
+ prepare(request) {
785
+ const { filter, sorting, search, range } = request, unknownFields = __rest(request, ["filter", "sorting", "search", "range"]);
786
+ const options = {};
787
+ if (filter) {
788
+ options.filter = filter;
789
+ }
790
+ if (sorting) {
791
+ options.sorting = sorting;
792
+ }
793
+ if (search) {
794
+ options.search = search;
795
+ }
796
+ let keyObject = Object.assign(Object.assign({}, options), unknownFields);
797
+ const key = JSON.stringify(keyObject);
798
+ let entry = this.cache.get(key);
799
+ if (!entry) {
800
+ entry = { options, count: 0, maxCount: null, isComplete: false };
801
+ this.cache.set(key, entry);
802
+ }
803
+ return { options, range, unknownFields, entry };
804
+ }
805
+ diff(request) {
806
+ const { options, range, unknownFields, entry } = this.prepare(request);
807
+ if (entry.isComplete) {
808
+ return null;
809
+ }
810
+ if (!request.range) {
811
+ return request;
812
+ }
813
+ else {
814
+ const requestedMax = request.range.from + request.range.count;
815
+ let missingCount = requestedMax - entry.count;
816
+ if (entry.maxCount) {
817
+ missingCount = Math.min(missingCount, entry.maxCount);
818
+ }
819
+ if (missingCount > 0) {
820
+ return Object.assign(Object.assign(Object.assign({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
821
+ }
822
+ else {
823
+ return null;
824
+ }
825
+ }
826
+ }
827
+ count(request) {
828
+ const { entry } = this.prepare(request);
829
+ return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
830
+ }
831
+ append(request, response) {
832
+ const { options, range, unknownFields, entry } = this.prepare(request);
833
+ if (response) {
834
+ const list = this.extractList(response);
835
+ if (list.count) {
836
+ entry.maxCount = list.count;
837
+ }
838
+ if (!range) {
839
+ entry.count = list.items.length;
840
+ entry.maxCount = list.items.length;
841
+ entry.isComplete = true;
842
+ }
843
+ else {
844
+ const from = (list.from == null) ? range.from : list.from;
845
+ if (list.items.length > 0) {
846
+ entry.count = Math.max(entry.count, from + list.items.length);
847
+ }
848
+ if (list.items.length < range.count) {
849
+ entry.maxCount = from + list.items.length;
850
+ entry.count = entry.maxCount;
851
+ entry.isComplete = true;
852
+ }
853
+ }
854
+ }
855
+ else {
856
+ if (range) {
857
+ entry.count = Math.max(entry.count, request.range.from + request.range.count);
858
+ }
859
+ else {
860
+ entry.isComplete = true;
861
+ }
862
+ }
863
+ }
864
+ }
865
+
866
+ class DbRef {
867
+ constructor(blank) {
868
+ this.blank = blank;
869
+ this.log = [];
870
+ this.autoSave = true;
871
+ this.savedPoint = 0;
872
+ this.throttleSaveMs = 1000;
873
+ /* Update subscriptions (aka live views) */
874
+ this.lastSubscriptionId = 1;
875
+ this.subscriptions = new Map();
876
+ this.updateHandlers = [];
877
+ /* Error Subscriptions */
878
+ this.saveErrorHandlers = [];
879
+ /* Save scheduling */
880
+ this.enqueueSave = batch(() => __awaiter(this, void 0, void 0, function* () {
881
+ const cumulativePatch = this.makeCumulativePatch();
882
+ const lastLogEntry = this.log.length;
883
+ if (isEmpty(cumulativePatch)) {
884
+ return;
885
+ }
886
+ try {
887
+ const response = yield this.savePatch(cumulativePatch);
888
+ this.applyResponse(response, lastLogEntry);
889
+ this.update();
890
+ }
891
+ catch (error) {
892
+ this.saveError(cumulativePatch, error);
893
+ this.update();
894
+ throw error;
895
+ }
896
+ }));
897
+ this.handleBeforeUnload = (e) => {
898
+ if (this.enqueueSave.isBusy) {
899
+ e.returnValue = false;
900
+ return false;
901
+ }
902
+ };
903
+ this.loaders = [];
904
+ this.db = blank;
905
+ this.base = blank;
906
+ this.tempIdMap = new TempIdMap(blank);
907
+ this.idMap = this.tempIdMap;
908
+ window.addEventListener('beforeunload', this.handleBeforeUnload);
909
+ }
910
+ /** Saves all committed patches. Useful only if autoSave is off. */
911
+ save() {
912
+ return this.enqueueSave();
913
+ }
914
+ getAutoSave() {
915
+ return this.autoSave;
916
+ }
917
+ setAutoSave(val) {
918
+ if (this.autoSave != val) {
919
+ this.autoSave = val;
920
+ this.autoSave && this.enqueueSave();
921
+ this.update();
922
+ }
923
+ }
924
+ revert() {
925
+ this.db = this.base;
926
+ this.log = this.log.slice(0, this.savedPoint);
927
+ this.update();
928
+ }
929
+ /** Concrete DbRef instances should override and implement their save logic in this method */
930
+ savePatch(patch) {
931
+ return Promise.resolve({ submit: {} });
932
+ }
933
+ /* Db Update logic */
934
+ commit(patch) {
935
+ const dbBeforeUpdate = this.db.with(patch);
936
+ patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
937
+ patch = mergeEntityPatches(this.db.tables, patch);
938
+ this.log.push({ patch });
939
+ this.db = this.db.with(patch);
940
+ this.autoSave && this.enqueueSave(null, { throttleMs: this.throttleSaveMs });
941
+ this.update();
942
+ }
943
+ beforeUpdate(patch, tables, prevTables) {
944
+ let patchAndDependencies = {};
945
+ objectKeys(tables).filter(entityName => patch[entityName] && !tables[entityName].schema.beforeUpdate).forEach(entityName => {
946
+ patchAndDependencies[entityName] = patch[entityName];
947
+ });
948
+ objectKeys(tables).filter(entityName => patch[entityName] && tables[entityName].schema.beforeUpdate).forEach(entityName => {
949
+ const schema = tables[entityName].schema;
950
+ const { beforeUpdate } = schema;
951
+ let context = {
952
+ clientIdsMap: this.tempIdMap,
953
+ schema,
954
+ tables,
955
+ prevTables,
956
+ };
957
+ const results = patch[entityName].map(e => beforeUpdate(e, context));
958
+ const updatedPatch = { [entityName]: results.map(result => result.entity) };
959
+ const dependentEntityPatchesForUpdate = unionPatches(results.filter(result => result.dependentEntities).map(result => result.dependentEntities));
960
+ const dependentEntityPatches = this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
961
+ patchAndDependencies = mergeEntityPatches(tables, unionPatches([patchAndDependencies, updatedPatch, dependentEntityPatches]));
962
+ });
963
+ return patchAndDependencies;
964
+ }
965
+ commitFetch(patch) {
966
+ patch = this.tempIdMap.serverToClientPatch(patch);
967
+ this.rebase(this.base.with(patch));
968
+ this.update();
969
+ }
970
+ rebase(newBase) {
971
+ this.base = newBase;
972
+ this.db = newBase;
973
+ for (let n = this.savedPoint; n < this.log.length; n++) {
974
+ this.db = this.db.with(this.log[n].patch);
975
+ }
976
+ }
977
+ makeCumulativePatch() {
978
+ const lastLogEntry = this.log.length;
979
+ const logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
980
+ let cumulativePatch = makeCumulativePatch(this.db, logEntriesToSave.map(t => t.patch), this.tempIdMap);
981
+ cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
982
+ return cumulativePatch;
983
+ }
984
+ applyResponse(response, newSavedPoint) {
985
+ this.tempIdMap.appendServerMapping(response);
986
+ let serverPatch = flattenResponse(response.submit, this.db.tables);
987
+ serverPatch = mergeEntityPatches(this.db.tables, serverPatch);
988
+ this.savedPoint = newSavedPoint;
989
+ this.base = this.db;
990
+ this.commitFetch(serverPatch);
991
+ }
992
+ subscribe(view, params, onUpdate) {
993
+ const id = this.lastSubscriptionId++;
994
+ const subscription = {
995
+ update: (params) => {
996
+ subscription.currentParams = params;
997
+ subscription.currentValue = this.db.runView(view, params);
998
+ return subscription.currentValue;
999
+ },
1000
+ currentParams: null,
1001
+ currentValue: null,
1002
+ onUpdate,
1003
+ unsubscribe: () => { this.subscriptions.delete(id); },
1004
+ };
1005
+ subscription.update(params);
1006
+ this.subscriptions.set(id, subscription);
1007
+ return subscription;
1008
+ }
1009
+ onUpdate(handler) {
1010
+ this.subscribe({
1011
+ compute: db => db,
1012
+ compareResults: (a, b) => a === b,
1013
+ }, null, handler);
1014
+ }
1015
+ update() {
1016
+ this.subscriptions.forEach(subscription => {
1017
+ const previousValue = subscription.currentValue;
1018
+ subscription.update(subscription.currentParams);
1019
+ if (subscription.currentValue !== previousValue && subscription.onUpdate) {
1020
+ subscription.onUpdate(subscription.currentValue);
1021
+ }
1022
+ });
1023
+ }
1024
+ onSaveError(handler) {
1025
+ this.saveErrorHandlers.push(handler);
1026
+ }
1027
+ saveError(request, error) {
1028
+ this.saveErrorHandlers.forEach(handler => handler(request, error));
1029
+ }
1030
+ makeLoader(options) {
1031
+ const loader = new Loader(this, () => new SimpleLoadingTracker(), options);
1032
+ this.loaders.push(loader);
1033
+ return loader;
1034
+ }
1035
+ makeListLoader(options) {
1036
+ const loader = new Loader(this, () => new ListLoadingTracker(), options);
1037
+ this.loaders.push(loader);
1038
+ return loader;
1039
+ }
1040
+ reload() {
1041
+ this.loaders = [];
1042
+ }
1043
+ }
1044
+
1045
+ const DbContext = createContext(null);
1046
+ function useDbRef() {
1047
+ return useContext(DbContext);
1048
+ }
1049
+ function useDbView(fn, params, options) {
1050
+ const dbRef = useDbRef();
1051
+ const [state, setState] = useState();
1052
+ const subscription = useMemo(() => dbRef.subscribe(Object.assign({ compute: fn }, options), params, setState), []);
1053
+ subscription.update(params);
1054
+ useEffect(() => {
1055
+ return () => subscription.unsubscribe();
1056
+ }, []);
1057
+ return subscription.currentValue;
1058
+ }
1059
+
1060
+ export { Db, DbContext, DbRef, DbRelationType, DbTable, TempIdMap, defaultCompareViewDependencies, difference, flattenResponse, getEntityParentDependencies, getId, getParentEntities, getTempId, hasServerFields, isClientOnly, isNew, isPatchBlank, isTempId, makeCumulativePatch, mergeEntityPatches, objectKeys, unionPatches, useDbRef, useDbView };
1061
+ //# sourceMappingURL=index.esm.js.map