-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkinto-offline-client.js
2641 lines (2627 loc) · 102 KB
/
kinto-offline-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/*
* This file is generated from kinto.js - do not modify directly.
*/
// This is required because with Babel compiles ES2015 modules into a
// require() form that tries to keep its modules on "this", but
// doesn't specify "this", leaving it to default to the global
// object. However, in strict mode, "this" no longer defaults to the
// global object, so expose the global object explicitly. Babel's
// compiled output will use a variable called "global" if one is
// present.
//
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1394556#c3 for
// more details.
const global = this;
var EXPORTED_SYMBOLS = ["Kinto"];
/*
* Version 13.0.0 - 7fbf95d
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Kinto = factory());
}(this, (function () { 'use strict';
/**
* Base db adapter.
*
* @abstract
*/
class BaseAdapter {
/**
* Deletes every records present in the database.
*
* @abstract
* @return {Promise}
*/
clear() {
throw new Error("Not Implemented.");
}
/**
* Executes a batch of operations within a single transaction.
*
* @abstract
* @param {Function} callback The operation callback.
* @param {Object} options The options object.
* @return {Promise}
*/
execute(callback, options = { preload: [] }) {
throw new Error("Not Implemented.");
}
/**
* Retrieve a record by its primary key from the database.
*
* @abstract
* @param {String} id The record id.
* @return {Promise}
*/
get(id) {
throw new Error("Not Implemented.");
}
/**
* Lists all records from the database.
*
* @abstract
* @param {Object} params The filters and order to apply to the results.
* @return {Promise}
*/
list(params = { filters: {}, order: "" }) {
throw new Error("Not Implemented.");
}
/**
* Store the lastModified value.
*
* @abstract
* @param {Number} lastModified
* @return {Promise}
*/
saveLastModified(lastModified) {
throw new Error("Not Implemented.");
}
/**
* Retrieve saved lastModified value.
*
* @abstract
* @return {Promise}
*/
getLastModified() {
throw new Error("Not Implemented.");
}
/**
* Load records in bulk that were exported from a server.
*
* @abstract
* @param {Array} records The records to load.
* @return {Promise}
*/
importBulk(records) {
throw new Error("Not Implemented.");
}
/**
* Load a dump of records exported from a server.
*
* @deprecated Use {@link importBulk} instead.
* @abstract
* @param {Array} records The records to load.
* @return {Promise}
*/
loadDump(records) {
throw new Error("Not Implemented.");
}
saveMetadata(metadata) {
throw new Error("Not Implemented.");
}
getMetadata() {
throw new Error("Not Implemented.");
}
}
const RE_RECORD_ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
/**
* Checks if a value is undefined.
* @param {Any} value
* @return {Boolean}
*/
function _isUndefined(value) {
return typeof value === "undefined";
}
/**
* Sorts records in a list according to a given ordering.
*
* @param {String} order The ordering, eg. `-last_modified`.
* @param {Array} list The collection to order.
* @return {Array}
*/
function sortObjects(order, list) {
const hasDash = order[0] === "-";
const field = hasDash ? order.slice(1) : order;
const direction = hasDash ? -1 : 1;
return list.slice().sort((a, b) => {
if (a[field] && _isUndefined(b[field])) {
return direction;
}
if (b[field] && _isUndefined(a[field])) {
return -direction;
}
if (_isUndefined(a[field]) && _isUndefined(b[field])) {
return 0;
}
return a[field] > b[field] ? direction : -direction;
});
}
/**
* Test if a single object matches all given filters.
*
* @param {Object} filters The filters object.
* @param {Object} entry The object to filter.
* @return {Boolean}
*/
function filterObject(filters, entry) {
return Object.keys(filters).every(filter => {
const value = filters[filter];
if (Array.isArray(value)) {
return value.some(candidate => candidate === entry[filter]);
}
else if (typeof value === "object") {
return filterObject(value, entry[filter]);
}
else if (!Object.prototype.hasOwnProperty.call(entry, filter)) {
console.error(`The property ${filter} does not exist`);
return false;
}
return entry[filter] === value;
});
}
/**
* Resolves a list of functions sequentially, which can be sync or async; in
* case of async, functions must return a promise.
*
* @param {Array} fns The list of functions.
* @param {Any} init The initial value.
* @return {Promise}
*/
function waterfall(fns, init) {
if (!fns.length) {
return Promise.resolve(init);
}
return fns.reduce((promise, nextFn) => {
return promise.then(nextFn);
}, Promise.resolve(init));
}
/**
* Simple deep object comparison function. This only supports comparison of
* serializable JavaScript objects.
*
* @param {Object} a The source object.
* @param {Object} b The compared object.
* @return {Boolean}
*/
function deepEqual(a, b) {
if (a === b) {
return true;
}
if (typeof a !== typeof b) {
return false;
}
if (!(a && typeof a == "object") || !(b && typeof b == "object")) {
return false;
}
if (Object.keys(a).length !== Object.keys(b).length) {
return false;
}
for (const k in a) {
if (!deepEqual(a[k], b[k])) {
return false;
}
}
return true;
}
/**
* Return an object without the specified keys.
*
* @param {Object} obj The original object.
* @param {Array} keys The list of keys to exclude.
* @return {Object} A copy without the specified keys.
*/
function omitKeys(obj, keys = []) {
const result = Object.assign({}, obj);
for (const key of keys) {
delete result[key];
}
return result;
}
function arrayEqual(a, b) {
if (a.length !== b.length) {
return false;
}
for (let i = a.length; i--;) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function makeNestedObjectFromArr(arr, val, nestedFiltersObj) {
const last = arr.length - 1;
return arr.reduce((acc, cv, i) => {
if (i === last) {
return (acc[cv] = val);
}
else if (Object.prototype.hasOwnProperty.call(acc, cv)) {
return acc[cv];
}
else {
return (acc[cv] = {});
}
}, nestedFiltersObj);
}
function transformSubObjectFilters(filtersObj) {
const transformedFilters = {};
for (const key in filtersObj) {
const keysArr = key.split(".");
const val = filtersObj[key];
makeNestedObjectFromArr(keysArr, val, transformedFilters);
}
return transformedFilters;
}
const INDEXED_FIELDS = ["id", "_status", "last_modified"];
/**
* Small helper that wraps the opening of an IndexedDB into a Promise.
*
* @param dbname {String} The database name.
* @param version {Integer} Schema version
* @param onupgradeneeded {Function} The callback to execute if schema is
* missing or different.
* @return {Promise<IDBDatabase>}
*/
async function open(dbname, { version, onupgradeneeded }) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbname, version);
request.onupgradeneeded = event => {
const db = event.target.result;
db.onerror = event => reject(event.target.error);
// When an upgrade is needed, a transaction is started.
const transaction = event.target.transaction;
transaction.onabort = event => {
const error = event.target.error ||
transaction.error ||
new DOMException("The operation has been aborted", "AbortError");
reject(error);
};
// Callback for store creation etc.
return onupgradeneeded(event);
};
request.onerror = event => {
reject(event.target.error);
};
request.onsuccess = event => {
const db = event.target.result;
resolve(db);
};
});
}
/**
* Helper to run the specified callback in a single transaction on the
* specified store.
* The helper focuses on transaction wrapping into a promise.
*
* @param db {IDBDatabase} The database instance.
* @param name {String} The store name.
* @param callback {Function} The piece of code to execute in the transaction.
* @param options {Object} Options.
* @param options.mode {String} Transaction mode (default: read).
* @return {Promise} any value returned by the callback.
*/
async function execute(db, name, callback, options = {}) {
const { mode } = options;
return new Promise((resolve, reject) => {
// On Safari, calling IDBDatabase.transaction with mode == undefined raises
// a TypeError.
const transaction = mode
? db.transaction([name], mode)
: db.transaction([name]);
const store = transaction.objectStore(name);
// Let the callback abort this transaction.
const abort = e => {
transaction.abort();
reject(e);
};
// Execute the specified callback **synchronously**.
let result;
try {
result = callback(store, abort);
}
catch (e) {
abort(e);
}
transaction.onerror = event => reject(event.target.error);
transaction.oncomplete = event => resolve(result);
transaction.onabort = event => {
const error = event.target.error ||
transaction.error ||
new DOMException("The operation has been aborted", "AbortError");
reject(error);
};
});
}
/**
* Helper to wrap the deletion of an IndexedDB database into a promise.
*
* @param dbName {String} the database to delete
* @return {Promise}
*/
async function deleteDatabase(dbName) {
return new Promise((resolve, reject) => {
const request = indexedDB.deleteDatabase(dbName);
request.onsuccess = event => resolve(event.target);
request.onerror = event => reject(event.target.error);
});
}
/**
* IDB cursor handlers.
* @type {Object}
*/
const cursorHandlers = {
all(filters, done) {
const results = [];
return event => {
const cursor = event.target.result;
if (cursor) {
const { value } = cursor;
if (filterObject(filters, value)) {
results.push(value);
}
cursor.continue();
}
else {
done(results);
}
};
},
in(values, filters, done) {
const results = [];
let i = 0;
return function (event) {
const cursor = event.target.result;
if (!cursor) {
done(results);
return;
}
const { key, value } = cursor;
// `key` can be an array of two values (see `keyPath` in indices definitions).
// `values` can be an array of arrays if we filter using an index whose key path
// is an array (eg. `cursorHandlers.in([["bid/cid", 42], ["bid/cid", 43]], ...)`)
while (key > values[i]) {
// The cursor has passed beyond this key. Check next.
++i;
if (i === values.length) {
done(results); // There is no next. Stop searching.
return;
}
}
const isEqual = Array.isArray(key)
? arrayEqual(key, values[i])
: key === values[i];
if (isEqual) {
if (filterObject(filters, value)) {
results.push(value);
}
cursor.continue();
}
else {
cursor.continue(values[i]);
}
};
},
};
/**
* Creates an IDB request and attach it the appropriate cursor event handler to
* perform a list query.
*
* Multiple matching values are handled by passing an array.
*
* @param {String} cid The collection id (ie. `{bid}/{cid}`)
* @param {IDBStore} store The IDB store.
* @param {Object} filters Filter the records by field.
* @param {Function} done The operation completion handler.
* @return {IDBRequest}
*/
function createListRequest(cid, store, filters, done) {
const filterFields = Object.keys(filters);
// If no filters, get all results in one bulk.
if (filterFields.length == 0) {
const request = store.index("cid").getAll(IDBKeyRange.only(cid));
request.onsuccess = event => done(event.target.result);
return request;
}
// Introspect filters and check if they leverage an indexed field.
const indexField = filterFields.find(field => {
return INDEXED_FIELDS.includes(field);
});
if (!indexField) {
// Iterate on all records for this collection (ie. cid)
const isSubQuery = Object.keys(filters).some(key => key.includes(".")); // (ie. filters: {"article.title": "hello"})
if (isSubQuery) {
const newFilter = transformSubObjectFilters(filters);
const request = store.index("cid").openCursor(IDBKeyRange.only(cid));
request.onsuccess = cursorHandlers.all(newFilter, done);
return request;
}
const request = store.index("cid").openCursor(IDBKeyRange.only(cid));
request.onsuccess = cursorHandlers.all(filters, done);
return request;
}
// If `indexField` was used already, don't filter again.
const remainingFilters = omitKeys(filters, [indexField]);
// value specified in the filter (eg. `filters: { _status: ["created", "updated"] }`)
const value = filters[indexField];
// For the "id" field, use the primary key.
const indexStore = indexField == "id" ? store : store.index(indexField);
// WHERE IN equivalent clause
if (Array.isArray(value)) {
if (value.length === 0) {
return done([]);
}
const values = value.map(i => [cid, i]).sort();
const range = IDBKeyRange.bound(values[0], values[values.length - 1]);
const request = indexStore.openCursor(range);
request.onsuccess = cursorHandlers.in(values, remainingFilters, done);
return request;
}
// If no filters on custom attribute, get all results in one bulk.
if (remainingFilters.length == 0) {
const request = indexStore.getAll(IDBKeyRange.only([cid, value]));
request.onsuccess = event => done(event.target.result);
return request;
}
// WHERE field = value clause
const request = indexStore.openCursor(IDBKeyRange.only([cid, value]));
request.onsuccess = cursorHandlers.all(remainingFilters, done);
return request;
}
class IDBError extends Error {
constructor(method, err) {
super(`IndexedDB ${method}() ${err.message}`);
this.name = err.name;
this.stack = err.stack;
}
}
/**
* IndexedDB adapter.
*
* This adapter doesn't support any options.
*/
class IDB extends BaseAdapter {
/* Expose the IDBError class publicly */
static get IDBError() {
return IDBError;
}
/**
* Constructor.
*
* @param {String} cid The key base for this collection (eg. `bid/cid`)
* @param {Object} options
* @param {String} options.dbName The IndexedDB name (default: `"KintoDB"`)
* @param {String} options.migrateOldData Whether old database data should be migrated (default: `false`)
*/
constructor(cid, options = {}) {
super();
this.cid = cid;
this.dbName = options.dbName || "KintoDB";
this._options = options;
this._db = null;
}
_handleError(method, err) {
throw new IDBError(method, err);
}
/**
* Ensures a connection to the IndexedDB database has been opened.
*
* @override
* @return {Promise}
*/
async open() {
if (this._db) {
return this;
}
// In previous versions, we used to have a database with name `${bid}/${cid}`.
// Check if it exists, and migrate data once new schema is in place.
// Note: the built-in migrations from IndexedDB can only be used if the
// database name does not change.
const dataToMigrate = this._options.migrateOldData
? await migrationRequired(this.cid)
: null;
this._db = await open(this.dbName, {
version: 2,
onupgradeneeded: event => {
const db = event.target.result;
if (event.oldVersion < 1) {
// Records store
const recordsStore = db.createObjectStore("records", {
keyPath: ["_cid", "id"],
});
// An index to obtain all the records in a collection.
recordsStore.createIndex("cid", "_cid");
// Here we create indices for every known field in records by collection.
// Local record status ("synced", "created", "updated", "deleted")
recordsStore.createIndex("_status", ["_cid", "_status"]);
// Last modified field
recordsStore.createIndex("last_modified", ["_cid", "last_modified"]);
// Timestamps store
db.createObjectStore("timestamps", {
keyPath: "cid",
});
}
if (event.oldVersion < 2) {
// Collections store
db.createObjectStore("collections", {
keyPath: "cid",
});
}
},
});
if (dataToMigrate) {
const { records, timestamp } = dataToMigrate;
await this.importBulk(records);
await this.saveLastModified(timestamp);
console.log(`${this.cid}: data was migrated successfully.`);
// Delete the old database.
await deleteDatabase(this.cid);
console.warn(`${this.cid}: old database was deleted.`);
}
return this;
}
/**
* Closes current connection to the database.
*
* @override
* @return {Promise}
*/
close() {
if (this._db) {
this._db.close(); // indexedDB.close is synchronous
this._db = null;
}
return Promise.resolve();
}
/**
* Returns a transaction and an object store for a store name.
*
* To determine if a transaction has completed successfully, we should rather
* listen to the transaction’s complete event rather than the IDBObjectStore
* request’s success event, because the transaction may still fail after the
* success event fires.
*
* @param {String} name Store name
* @param {Function} callback to execute
* @param {Object} options Options
* @param {String} options.mode Transaction mode ("readwrite" or undefined)
* @return {Object}
*/
async prepare(name, callback, options) {
await this.open();
await execute(this._db, name, callback, options);
}
/**
* Deletes every records in the current collection.
*
* @override
* @return {Promise}
*/
async clear() {
try {
await this.prepare("records", store => {
const range = IDBKeyRange.only(this.cid);
const request = store.index("cid").openKeyCursor(range);
request.onsuccess = event => {
const cursor = event.target.result;
if (cursor) {
store.delete(cursor.primaryKey);
cursor.continue();
}
};
return request;
}, { mode: "readwrite" });
}
catch (e) {
this._handleError("clear", e);
}
}
/**
* Executes the set of synchronous CRUD operations described in the provided
* callback within an IndexedDB transaction, for current db store.
*
* The callback will be provided an object exposing the following synchronous
* CRUD operation methods: get, create, update, delete.
*
* Important note: because limitations in IndexedDB implementations, no
* asynchronous code should be performed within the provided callback; the
* promise will therefore be rejected if the callback returns a Promise.
*
* Options:
* - {Array} preload: The list of record IDs to fetch and make available to
* the transaction object get() method (default: [])
*
* @example
* const db = new IDB("example");
* const result = await db.execute(transaction => {
* transaction.create({id: 1, title: "foo"});
* transaction.update({id: 2, title: "bar"});
* transaction.delete(3);
* return "foo";
* });
*
* @override
* @param {Function} callback The operation description callback.
* @param {Object} options The options object.
* @return {Promise}
*/
async execute(callback, options = { preload: [] }) {
// Transactions in IndexedDB are autocommited when a callback does not
// perform any additional operation.
// The way Promises are implemented in Firefox (see https://bugzilla.mozilla.org/show_bug.cgi?id=1193394)
// prevents using within an opened transaction.
// To avoid managing asynchronocity in the specified `callback`, we preload
// a list of record in order to execute the `callback` synchronously.
// See also:
// - http://stackoverflow.com/a/28388805/330911
// - http://stackoverflow.com/a/10405196
// - https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
let result;
await this.prepare("records", (store, abort) => {
const runCallback = (preloaded = []) => {
// Expose a consistent API for every adapter instead of raw store methods.
const proxy = transactionProxy(this, store, preloaded);
// The callback is executed synchronously within the same transaction.
try {
const returned = callback(proxy);
if (returned instanceof Promise) {
// XXX: investigate how to provide documentation details in error.
throw new Error("execute() callback should not return a Promise.");
}
// Bring to scope that will be returned (once promise awaited).
result = returned;
}
catch (e) {
// The callback has thrown an error explicitly. Abort transaction cleanly.
abort(e);
}
};
// No option to preload records, go straight to `callback`.
if (!options.preload.length) {
return runCallback();
}
// Preload specified records using a list request.
const filters = { id: options.preload };
createListRequest(this.cid, store, filters, records => {
// Store obtained records by id.
const preloaded = {};
for (const record of records) {
delete record["_cid"];
preloaded[record.id] = record;
}
runCallback(preloaded);
});
}, { mode: "readwrite" });
return result;
}
/**
* Retrieve a record by its primary key from the IndexedDB database.
*
* @override
* @param {String} id The record id.
* @return {Promise}
*/
async get(id) {
try {
let record;
await this.prepare("records", store => {
store.get([this.cid, id]).onsuccess = e => (record = e.target.result);
});
return record;
}
catch (e) {
this._handleError("get", e);
}
}
/**
* Lists all records from the IndexedDB database.
*
* @override
* @param {Object} params The filters and order to apply to the results.
* @return {Promise}
*/
async list(params = { filters: {} }) {
const { filters } = params;
try {
let results = [];
await this.prepare("records", store => {
createListRequest(this.cid, store, filters, _results => {
// we have received all requested records that match the filters,
// we now park them within current scope and hide the `_cid` attribute.
for (const result of _results) {
delete result["_cid"];
}
results = _results;
});
});
// The resulting list of records is sorted.
// XXX: with some efforts, this could be fully implemented using IDB API.
return params.order ? sortObjects(params.order, results) : results;
}
catch (e) {
this._handleError("list", e);
}
}
/**
* Store the lastModified value into metadata store.
*
* @override
* @param {Number} lastModified
* @return {Promise}
*/
async saveLastModified(lastModified) {
const value = parseInt(lastModified, 10) || null;
try {
await this.prepare("timestamps", store => {
if (value === null) {
store.delete(this.cid);
}
else {
store.put({ cid: this.cid, value });
}
}, { mode: "readwrite" });
return value;
}
catch (e) {
this._handleError("saveLastModified", e);
}
}
/**
* Retrieve saved lastModified value.
*
* @override
* @return {Promise}
*/
async getLastModified() {
try {
let entry = null;
await this.prepare("timestamps", store => {
store.get(this.cid).onsuccess = e => (entry = e.target.result);
});
return entry ? entry.value : null;
}
catch (e) {
this._handleError("getLastModified", e);
}
}
/**
* Load a dump of records exported from a server.
*
* @deprecated Use {@link importBulk} instead.
* @abstract
* @param {Array} records The records to load.
* @return {Promise}
*/
async loadDump(records) {
return this.importBulk(records);
}
/**
* Load records in bulk that were exported from a server.
*
* @abstract
* @param {Array} records The records to load.
* @return {Promise}
*/
async importBulk(records) {
try {
await this.execute(transaction => {
// Since the put operations are asynchronous, we chain
// them together. The last one will be waited for the
// `transaction.oncomplete` callback. (see #execute())
let i = 0;
putNext();
function putNext() {
if (i == records.length) {
return;
}
// On error, `transaction.onerror` is called.
transaction.update(records[i]).onsuccess = putNext;
++i;
}
});
const previousLastModified = await this.getLastModified();
const lastModified = Math.max(...records.map(record => record.last_modified));
if (lastModified > previousLastModified) {
await this.saveLastModified(lastModified);
}
return records;
}
catch (e) {
this._handleError("importBulk", e);
}
}
async saveMetadata(metadata) {
try {
await this.prepare("collections", store => store.put({ cid: this.cid, metadata }), { mode: "readwrite" });
return metadata;
}
catch (e) {
this._handleError("saveMetadata", e);
}
}
async getMetadata() {
try {
let entry = null;
await this.prepare("collections", store => {
store.get(this.cid).onsuccess = e => (entry = e.target.result);
});
return entry ? entry.metadata : null;
}
catch (e) {
this._handleError("getMetadata", e);
}
}
}
/**
* IDB transaction proxy.
*
* @param {IDB} adapter The call IDB adapter
* @param {IDBStore} store The IndexedDB database store.
* @param {Array} preloaded The list of records to make available to
* get() (default: []).
* @return {Object}
*/
function transactionProxy(adapter, store, preloaded = []) {
const _cid = adapter.cid;
return {
create(record) {
store.add(Object.assign(Object.assign({}, record), { _cid }));
},
update(record) {
return store.put(Object.assign(Object.assign({}, record), { _cid }));
},
delete(id) {
store.delete([_cid, id]);
},
get(id) {
return preloaded[id];
},
};
}
/**
* Up to version 10.X of kinto.js, each collection had its own collection.
* The database name was `${bid}/${cid}` (eg. `"blocklists/certificates"`)
* and contained only one store with the same name.
*/
async function migrationRequired(dbName) {
let exists = true;
const db = await open(dbName, {
version: 1,
onupgradeneeded: event => {
exists = false;
},
});
// Check that the DB we're looking at is really a legacy one,
// and not some remainder of the open() operation above.
exists &=
db.objectStoreNames.contains("__meta__") &&
db.objectStoreNames.contains(dbName);
if (!exists) {
db.close();
// Testing the existence creates it, so delete it :)
await deleteDatabase(dbName);
return null;
}
console.warn(`${dbName}: old IndexedDB database found.`);
try {
// Scan all records.
let records;
await execute(db, dbName, store => {
store.openCursor().onsuccess = cursorHandlers.all({}, res => (records = res));
});
console.log(`${dbName}: found ${records.length} records.`);
// Check if there's a entry for this.
let timestamp = null;
await execute(db, "__meta__", store => {
store.get(`${dbName}-lastModified`).onsuccess = e => {
timestamp = e.target.result ? e.target.result.value : null;
};
});
// Some previous versions, also used to store the timestamps without prefix.
if (!timestamp) {
await execute(db, "__meta__", store => {
store.get("lastModified").onsuccess = e => {
timestamp = e.target.result ? e.target.result.value : null;
};
});
}
console.log(`${dbName}: ${timestamp ? "found" : "no"} timestamp.`);
// Those will be inserted in the new database/schema.
return { records, timestamp };
}
catch (e) {
console.error("Error occured during migration", e);
return null;
}
finally {
db.close();
}
}
var uuid4 = {};
const RECORD_FIELDS_TO_CLEAN = ["_status"];
const AVAILABLE_HOOKS = ["incoming-changes"];
const IMPORT_CHUNK_SIZE = 200;
/**
* Compare two records omitting local fields and synchronization
* attributes (like _status and last_modified)
* @param {Object} a A record to compare.
* @param {Object} b A record to compare.
* @param {Array} localFields Additional fields to ignore during the comparison
* @return {boolean}
*/
function recordsEqual(a, b, localFields = []) {
const fieldsToClean = RECORD_FIELDS_TO_CLEAN.concat(["last_modified"]).concat(localFields);
const cleanLocal = r => omitKeys(r, fieldsToClean);
return deepEqual(cleanLocal(a), cleanLocal(b));
}
/**
* Synchronization result object.
*/
class SyncResultObject {
/**
* Public constructor.
*/
constructor() {
/**
* Current synchronization result status; becomes `false` when conflicts or