diff --git a/addons/Dexie.Observable/dist/README.md b/addons/Dexie.Observable/dist/README.md deleted file mode 100644 index f54e59357..000000000 --- a/addons/Dexie.Observable/dist/README.md +++ /dev/null @@ -1,37 +0,0 @@ -## Can't find dexie-observable.js? -Transpiled code (dist version) IS ONLY checked in to -the [releases](https://github.com/dfahlander/Dexie.js/tree/releases/addons/Dexie.Observable/dist) -branch. - -## Download -[unpkg.com/dexie-observable/dist/dexie-observable.js](https://unpkg.com/dexie-observable/dist/dexie-observable.js) - -[unpkg.com/dexie-observable/dist/dexie-observable.min.js](https://unpkg.com/dexie-observable/dist/dexie-observable.min.js) - -[unpkg.com/dexie-observable/dist/dexie-observable.js.map](https://unpkg.com/dexie-observable/dist/dexie-observable.js.map) - -[unpkg.com/dexie-observable/dist/dexie-observable.min.js.map](https://unpkg.com/dexie-observable/dist/dexie-observable.min.js.map) - -## npm -``` -npm install dexie-observable --save -``` -## bower -Since Dexie v1.3.4, addons are included in the dexie bower package. -``` -$ bower install dexie --save -$ ls bower_components/dexie/addons/Dexie.Observable/dist -dexie-observable.js dexie-observable.js.map dexie-observable.min.js dexie-observable.min.js.map - -``` -## Or build them yourself... -Fork Dexie.js, then: -``` -git clone https://github.com/YOUR-USERNAME/Dexie.js.git -cd Dexie.js -npm install -cd addons/Dexie.Observable -npm run build # or npm run watch - -``` -If you're on windows, you need to use an elevated command prompt of some reason to get `npm install` to work. diff --git a/addons/Dexie.Observable/dist/dexie-observable.d.ts b/addons/Dexie.Observable/dist/dexie-observable.d.ts new file mode 100644 index 000000000..9eb99bf1c --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.d.ts @@ -0,0 +1,120 @@ +// Type definitions for dexie-observable v1.0.0-beta.4 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Observable +// Definitions by: David Fahlander + +import Dexie from 'dexie'; +import { IDatabaseChange } from '../api'; + +// +// Extend Dexie interface +// +declare module 'dexie' { + // Extend methods on db (db.sendMessage(), ...) + interface Dexie { + // Placeholder where to access the SyncNode class constructor. + // (makes it valid to do new db.observable.SyncNode()) + observable: { + SyncNode: Dexie.Observable.SyncNodeConstructor; + sendMessage( + type: string, // Don't use 'response' as it is used internally by the framework + message: any, // anything that can be saved by IndexedDB + destinationNode: number, + options: { + wantReply?: boolean; + } + ): Promise | void; // When wantReply is undefined or false return is void + + broadcastMessage( + type: string, + message: any, // anything that can be saved by IndexedDB + bIncludeSelf: boolean + ): void; + } + + readonly _localSyncNode: Dexie.Observable.SyncNode; + + _changes: Dexie.Table; + _syncNodes: Dexie.Table; + _intercomm: Dexie.Table; + } + + module Dexie { + // Extended events db.on('changes', subscriber), ... + interface DbEvents { + (eventName: 'changes', subscriber: (changes: IDatabaseChange[], partial: boolean)=>void): void; + (eventName: 'cleanup', subscriber: ()=>any): void; + (eventName: 'message', subscriber: (msg: Dexie.Observable.MessageEvent)=>any): void; + } + + // Extended IndexSpec with uuid boolean for primary key. + interface IndexSpec { + uuid: boolean; + } + + var Observable: { + (db: Dexie) : void; + + // + // + // + createUUID: () => string; + on: Observable.ObservableEventSet; + localStorageImpl: { + setItem(key: string, value: string): void, + getItem(key: string): string, + removeItem(key: string): void; + }; + _onStorage: (event: StorageEvent) => void; + } + + // + // Define Dexie.Observable + // + module Observable { + // + // Interfaces of Dexie.Observable + // + + interface SyncNodeConstructor { + new() : SyncNode; + } + + /** + * A SyncNode represents a local database instance that subscribes + * to changes made on the database. + * SyncNodes are stored in the _syncNodes table. + * + * Dexie.Syncable extends this interface and allows 'remote' nodes to be stored + * as well. + */ + interface SyncNode { + id?: number, + myRevision: number, + type: 'local' | 'remote', + lastHeartBeat: number, + deleteTimeStamp: number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted. + isMaster: number // 1 if true. Not using Boolean because it's not possible to index Booleans. + } + + interface ObservableEventSet extends Dexie.DexieEventSet { + (eventName: 'latestRevisionIncremented', subscriber: (dbName: string, latestRevision: number) => void): void; + (eventName: 'suicideNurseCall', subscriber: (dbName: string, nodeID: number) => void): void; + (eventName: 'intercomm', subscriber: (dbName: string) => void): void; + (eventName: 'beforeunload', subscriber: () => void): void; + } + + // Object received by on('message') after sendMessage() or broadcastMessage() + interface MessageEvent { + id: number; + type: string; + message: any; + destinationNode: number; + wantReply?: boolean; + resolve(result: any): void; + reject(error: any): void; + } + } + } +} + +export default Dexie.Observable; diff --git a/addons/Dexie.Observable/dist/dexie-observable.es.js b/addons/Dexie.Observable/dist/dexie-observable.es.js new file mode 100644 index 000000000..9c1ae7ee0 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js @@ -0,0 +1,990 @@ +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; + +function nop() { } +function promisableChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, args = arguments; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} +function createUUID() { + // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript + var d = Date.now(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); + }); + return uuid; +} + +function initOverrideCreateTransaction(db, wakeupObservers) { + return function overrideCreateTransaction(origFunc) { + return function (mode, storenames, dbschema, parent) { + if (db.dynamicallyOpened()) + return origFunc.apply(this, arguments); // Don't observe dynamically opened databases. + var addChanges = false; + if (mode === 'readwrite' && storenames.some(function (storeName) { + return dbschema[storeName] && dbschema[storeName].observable; + })) { + // At least one included store is a observable store. Make sure to also include the _changes store. + addChanges = true; + storenames = storenames.slice(0); // Clone + if (storenames.indexOf("_changes") === -1) + storenames.push("_changes"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla) + } + // Call original db._createTransaction() + var trans = origFunc.call(this, mode, storenames, dbschema, parent); + // If this transaction is bound to any observable table, make sure to add changes when transaction completes. + if (addChanges) { + trans._lastWrittenRevision = 0; + trans.on('complete', function () { + if (trans._lastWrittenRevision) { + // Changes were written in this transaction. + if (!parent) { + // This is root-level transaction, i.e. a physical commit has happened. + // Delay-trigger a wakeup call: + if (wakeupObservers.timeoutHandle) + clearTimeout(wakeupObservers.timeoutHandle); + wakeupObservers.timeoutHandle = setTimeout(function () { + delete wakeupObservers.timeoutHandle; + wakeupObservers(trans._lastWrittenRevision); + }, 25); + } + else { + // This is just a virtual commit of a sub transaction. + // Wait with waking up observers until root transaction has committed. + // Make sure to mark root transaction so that it will wakeup observers upon commit. + var rootTransaction = (function findRootTransaction(trans) { + return trans.parent ? findRootTransaction(trans.parent) : trans; + })(parent); + rootTransaction._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rootTransaction.lastWrittenRevision || 0); + } + } + }); + // Derive "source" property from parent transaction by default + if (trans.parent && trans.parent.source) + trans.source = trans.parent.source; + } + return trans; + }; + }; +} + +function initWakeupObservers(db, Observable, localStorage) { + return function wakeupObservers(lastWrittenRevision) { + // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too. + if (Observable.latestRevision[db.name] < lastWrittenRevision) { + // Set the static property lastRevision[db.name] to the revision of the last written change. + Observable.latestRevision[db.name] = lastWrittenRevision; + // Wakeup ourselves, and any other db instances on this window: + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision); + }); + // Observable.on.latestRevisionIncremented will only wakeup db's in current window. + // We need a storage event to wakeup other windwos. + // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for + // the purpose to wakeup db instances in other windows. + if (localStorage) + localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id. + } + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function initCreatingHook(db, table) { + return function creatingHook(primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = createUUID(); + if (table.schema.primKey.keyPath) { + Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey); + } + } + var change = { + source: trans.source || null, + table: table.name, + key: primKey === undefined ? null : primKey, + type: CREATE, + obj: obj + }; + var promise = db._changes.add(change).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }); + // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so. + this.onsuccess = function (resultKey) { + if (primKey != resultKey) + promise._then(function () { + change.key = resultKey; + db._changes.put(change); + }); + }; + this.onerror = function () { + // If the main operation fails, make sure to regret the change + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + return rv; + }; +} + +function initUpdatingHook(db, tableName) { + return function updatingHook(mods, primKey, oldObj, trans) { + /// + // mods may contain property paths with undefined as value if the property + // is being deleted. Since we cannot persist undefined we need to act + // like those changes is setting the value to null instead. + var modsWithoutUndefined = {}; + // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change. + // Therefore we may do that kind of optimization here - to not add change entries if + // there's nothing to change. + var anythingChanged = false; + var newObj = Dexie.deepClone(oldObj); + for (var propPath in mods) { + var mod = mods[propPath]; + if (typeof mod === 'undefined') { + Dexie.delByKeyPath(newObj, propPath); + modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined. + anythingChanged = true; + } + else { + var currentValue = Dexie.getByKeyPath(oldObj, propPath); + if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) { + Dexie.setByKeyPath(newObj, propPath, mod); + modsWithoutUndefined[propPath] = mod; + anythingChanged = true; + } + } + } + if (anythingChanged) { + var change = { + source: trans.source || null, + table: tableName, + key: primKey, + type: UPDATE, + mods: modsWithoutUndefined, + oldObj: oldObj, + obj: newObj + }; + var promise = db._changes.add(change); // Just so we get the correct revision order of the update... + this.onsuccess = function () { + promise._then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + }); + }; + this.onerror = function () { + // If the main operation fails, make sure to regret the change. + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + } + }; +} + +function initDeletingHook(db, tableName) { + return function deletingHook(primKey, obj, trans) { + /// + var promise = db._changes.add({ + source: trans.source || null, + table: tableName, + key: primKey, + type: DELETE, + oldObj: obj + }).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }) + .catch(function (e) { + console.log(obj); + console.log(e.stack); + }); + this.onerror = function () { + // If the main operation fails, make sure to regret the change. + // Using _then because if promise is already fullfilled, the standard then() would + // do setTimeout() and we would loose the transaction. + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + }; +} + +function initCrudMonitor(db) { + // + // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table + // + return function crudMonitor(table) { + /// + if (table.hook._observing) + return; + table.hook._observing = true; + var tableName = table.name; + table.hook('creating').subscribe(initCreatingHook(db, table)); + table.hook('updating').subscribe(initUpdatingHook(db, tableName)); + table.hook('deleting').subscribe(initDeletingHook(db, tableName)); + }; +} + +function initOnStorage(Observable) { + return function onStorage(event) { + // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well! + if (event.key.indexOf("Dexie.Observable/") === 0) { + var parts = event.key.split('/'); + var prop = parts[1]; + var dbname = parts[2]; + if (prop === 'latestRevision') { + var rev = parseInt(event.newValue, 10); + if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) { + Observable.latestRevision[dbname] = rev; + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(dbname, rev); + }); + } + } + else if (prop.indexOf("deadnode:") === 0) { + var nodeID = parseInt(prop.split(':')[1], 10); + if (event.newValue) { + Observable.on.suicideNurseCall.fire(dbname, nodeID); + } + } + else if (prop === 'intercomm') { + if (event.newValue) { + Observable.on.intercomm.fire(dbname); + } + } + } + }; +} + +function initOverrideOpen(db, SyncNode, crudMonitor) { + return function overrideOpen(origOpen) { + return function () { + // + // Make sure to subscribe to "creating", "updating" and "deleting" hooks for all observable tables that were created in the stores() method. + // + Object.keys(db._allTables).forEach(function (tableName) { + var table = db._allTables[tableName]; + if (table.schema.observable) { + crudMonitor(table); + } + if (table.name === "_syncNodes") { + table.mapToClass(SyncNode); + } + }); + return origOpen.apply(this, arguments); + }; + }; +} + +var Promise$1 = Dexie.Promise; +function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) { + // + // Intercommunication between nodes + // + // Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable) + var requestsWaitingForReply = {}; + /** + * @param {string} type Type of message + * @param message Message to send + * @param {number} destinationNode ID of destination node + * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + */ + db.observable.sendMessage = function (type, message, destinationNode, options) { + /// Type of message + /// Message to send + /// ID of destination node + /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + options = options || {}; + if (!mySyncNode.node) + return options.wantReply ? + Promise$1.reject(new Dexie.DatabaseClosedError()) : + Promise$1.resolve(); // If caller doesn't want a reply, it won't catch errors either. + var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type }; + Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + return Dexie.ignoreTransaction(function () { + var tables = ["_intercomm"]; + if (options.wantReply) + tables.push("_syncNodes"); // If caller wants a reply, include "_syncNodes" in transaction to check that there's a receiver there. Otherwise, new master will get it. + var promise = db.transaction('rw', tables, function () { + if (options.wantReply) { + // Check that there is a receiver there to take the request. + return db._syncNodes.where('id').equals(destinationNode).count(function (receiverAlive) { + if (receiverAlive) + return db._intercomm.add(msg); + else + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + msg.destinationNode = masterNode.id; + return db._intercomm.add(msg); + }); + }); + } + else { + // If caller doesn't need a response, we don't have to make sure that it gets one. + return db._intercomm.add(msg); + } + }).then(function (messageId) { + var rv = null; + if (options.wantReply) { + rv = new Promise$1(function (resolve, reject) { + requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject }; + }); + } + if (localStorage) { + localStorage.setItem("Dexie.Observable/intercomm/" + db.name, messageId.toString()); + } + Observable.on.intercomm.fire(db.name); + return rv; + }); + if (!options.wantReply) { + promise.catch(function () { + }); + return; + } + else { + // Forward rejection to caller if it waits for reply. + return promise; + } + }); + }; + // Send a message to all local _syncNodes + db.observable.broadcastMessage = function (type, message, bIncludeSelf) { + if (!mySyncNode.node) + return; + var mySyncNodeId = mySyncNode.node.id; + Dexie.ignoreTransaction(function () { + db._syncNodes.toArray(function (nodes) { + return Promise$1.all(nodes + .filter(function (node) { return node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId); }) + .map(function (node) { return db.observable.sendMessage(type, message, node.id); })); + }).catch(function () { + }); + }); + }; + function consumeIntercommMessages() { + // Check if we got messages: + if (!mySyncNode.node) + return Promise$1.reject(new Dexie.DatabaseClosedError()); + return Dexie.ignoreTransaction(function () { + return db.transaction('rw', '_intercomm', function () { + return db._intercomm.where({ destinationNode: mySyncNode.node.id }).toArray(function (messages) { + messages.forEach(function (msg) { return consumeMessage(msg); }); + return db._intercomm.where('id').anyOf(messages.map(function (msg) { return msg.id; })).delete(); + }); + }); + }); + } + function consumeMessage(msg) { + if (msg.type === 'response') { + // This is a response. Lookup pending request and fulfill its promise. + var request = requestsWaitingForReply[msg.requestId.toString()]; + if (request) { + if (msg.isFailure) { + request.reject(msg.message.error); + } + else { + request.resolve(msg.message.result); + } + delete requestsWaitingForReply[msg.requestId.toString()]; + } + } + else { + // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested + msg.resolve = function (result) { + db.observable.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id }); + }; + msg.reject = function (error) { + db.observable.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id }); + }; + db.on.message.fire(msg); + } + } + // Listener for 'intercomm' events + // Gets fired when we get a 'storage' event from local storage or when sendMessage is called + // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event) + // sendMessage is used to communicate in the same tab and to trigger a storage event + function onIntercomm(dbname) { + // When storage event trigger us to check + if (dbname === db.name) { + consumeIntercommMessages().catch('DatabaseClosedError', function () { }); + } + } + return { + onIntercomm: onIntercomm, + consumeIntercommMessages: consumeIntercommMessages + }; +} + +function overrideParseStoresSpec(origFunc) { + return function (stores, dbSchema) { + // Create the _changes and _syncNodes tables + stores["_changes"] = "++rev"; + stores["_syncNodes"] = "++id,myRevision,lastHeartBeat,&url,isMaster,type,status"; + stores["_intercomm"] = "++id,destinationNode"; + stores["_uncommittedChanges"] = "++id,node"; // For remote syncing when server returns a partial result. + // Call default implementation. Will populate the dbSchema structures. + origFunc.call(this, stores, dbSchema); + // Allow UUID primary keys using $$ prefix on primary key or indexes + Object.keys(dbSchema).forEach(function (tableName) { + var schema = dbSchema[tableName]; + if (schema.primKey.name.indexOf('$$') === 0) { + schema.primKey.uuid = true; + schema.primKey.name = schema.primKey.name.substr(2); + schema.primKey.keyPath = schema.primKey.keyPath.substr(2); + } + }); + // Now mark all observable tables + Object.keys(dbSchema).forEach(function (tableName) { + // Marked observable tables with "observable" in their TableSchema. + if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) { + dbSchema[tableName].observable = true; + } + }); + }; +} + +function deleteOldChanges(db) { + // This is a background job and should never be done within + // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that. + // We should not return the Promise but catch it ourselves instead. + // To prohibit starving the database we want to lock transactions as short as possible + // and since we're not in a hurry, we could do this job in chunks and reschedule a + // continuation every 500 ms. + var CHUNK_SIZE = 100; + Dexie.ignoreTransaction(function () { + return db._syncNodes.orderBy("myRevision").first(function (oldestNode) { + return db._changes + .where("rev").below(oldestNode.myRevision) + .limit(CHUNK_SIZE) + .primaryKeys(); + }).then(function (keysToDelete) { + if (keysToDelete.length === 0) + return; // Done. + return db._changes.bulkDelete(keysToDelete).then(function () { + // If not done garbage collecting, reschedule a continuation of it until done. + if (keysToDelete.length === CHUNK_SIZE) { + // Limit reached. Changes are there are more job to do. Schedule again: + setTimeout(function () { return db.isOpen() && deleteOldChanges(db); }, 500); + } + }); + }); + }).catch(function () { + // The operation is not crucial. A failure could almost only be due to that database has been closed. + // No need to log this. + }); +} + +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +var global = self; +/** class DatabaseChange + * + * Object contained by the _changes table. + */ +var DatabaseChange = Dexie.defineClass({ + rev: Number, + source: String, + table: String, + key: Object, + type: Number, + obj: Object, + mods: Object, + oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied. +}); +// Import some usable helper functions +var override = Dexie.override; +var Promise = Dexie.Promise; +var browserIsShuttingDown = false; +function Observable(db) { + /// + /// Extension to Dexie providing Syncronization capabilities to Dexie. + /// + /// + var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects. + HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds + // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. + // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process) + LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event. + HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000; + var localStorage = Observable.localStorageImpl; + /** class SyncNode + * + * Object contained in the _syncNodes table. + */ + var SyncNode = Dexie.defineClass({ + //id: Number, + myRevision: Number, + type: String, + lastHeartBeat: Number, + deleteTimeStamp: Number, + url: String, + isMaster: Number, + // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == "remote"): + syncProtocol: String, + syncContext: null, + syncOptions: Object, + connected: false, + status: Number, + appliedRemoteRevision: null, + remoteBaseRevisions: [{ local: Number, remote: null }], + dbUploadState: { + tablesToUpload: [String], + currentTable: String, + currentKey: null, + localBaseRevision: Number + } + }); + db.observable = {}; + db.observable.SyncNode = SyncNode; + var wakeupObservers = initWakeupObservers(db, Observable, localStorage); + var overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers); + var crudMonitor = initCrudMonitor(db); + var overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor); + var mySyncNode = { node: null }; + var intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage); + var onIntercomm = intercomm.onIntercomm; + var consumeIntercommMessages = intercomm.consumeIntercommMessages; + // Allow other addons to access the local sync node. May be needed by Dexie.Syncable. + Object.defineProperty(db, "_localSyncNode", { + get: function () { return mySyncNode.node; } + }); + var pollHandle = null, heartbeatHandle = null; + if (Dexie.fake) { + // This code will never run. + // It's here just to enable auto-complete in visual studio - helps a lot when writing code. + db.version(1).stores({ + _syncNodes: "++id,myRevision,lastHeartBeat", + _changes: "++rev", + _intercomm: "++id,destinationNode", + _uncommittedChanges: "++id,node" + }); + db._syncNodes.mapToClass(SyncNode); + db._changes.mapToClass(DatabaseChange); + mySyncNode.node = new SyncNode({ + myRevision: 0, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null + }); + } + // + // Override parsing the stores to add "_changes" and "_syncNodes" tables. + // It also adds UUID support for the primary key and sets tables as observable tables. + // + db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec); + // changes event on db: + db.on.addEventType({ + changes: 'asap', + cleanup: [promisableChain, nop], + message: 'asap' + }); + // + // Override transaction creation to always include the "_changes" store when any observable store is involved. + // + db._createTransaction = override(db._createTransaction, overrideCreateTransaction); + // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works. + // You might think that it will always be undefined before this call, but in case another Dexie instance in the same + // window with the same database name has been created already, this static property will already be set correctly. + Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0; + // + // Override open to setup hooks for db changes and map the _syncNodes table to class + // + db.open = override(db.open, overrideOpen); + db.close = override(db.close, function (origClose) { + return function () { + if (db.dynamicallyOpened()) + return origClose.apply(this, arguments); // Don't observe dynamically opened databases. + // Teardown our framework. + if (wakeupObservers.timeoutHandle) { + clearTimeout(wakeupObservers.timeoutHandle); + delete wakeupObservers.timeoutHandle; + } + Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented); + Observable.on('suicideNurseCall').unsubscribe(onSuicide); + Observable.on('intercomm').unsubscribe(onIntercomm); + Observable.on('beforeunload').unsubscribe(onBeforeUnload); + // Inform other db instances in same window that we are dying: + if (mySyncNode.node && mySyncNode.node.id) { + Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id); + // Inform other windows as well: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, "dead"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything. + } + mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now. + mySyncNode.node = null; + } + if (pollHandle) + clearTimeout(pollHandle); + pollHandle = null; + if (heartbeatHandle) + clearTimeout(heartbeatHandle); + heartbeatHandle = null; + return origClose.apply(this, arguments); + }; + }); + // Override Dexie.delete() in order to delete Observable.latestRevision[db.name]. + db.delete = override(db.delete, function (origDelete) { + return function () { + return origDelete.apply(this, arguments).then(function (result) { + // Reset Observable.latestRevision[db.name] + Observable.latestRevision[db.name] = 0; + return result; + }); + }; + }); + // When db opens, make sure to start monitor any changes before other db operations will start. + db.on("ready", function startObserving() { + if (db.dynamicallyOpened()) + return db; // Don't observe dynamically opened databases. + return db.table("_changes").orderBy("rev").last(function (lastChange) { + // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db. + // Therefore we know that the retrieved value will be This query will + var latestRevision = (lastChange ? lastChange.rev : 0); + mySyncNode.node = new SyncNode({ + myRevision: latestRevision, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null, + isMaster: 0 + }); + if (Observable.latestRevision[db.name] < latestRevision) { + // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased: + // There are other db instances in same window that hasnt yet been informed about a new revision + Observable.latestRevision[db.name] = latestRevision; + Dexie.ignoreTransaction(function () { + Observable.on.latestRevisionIncremented.fire(latestRevision); + }); + } + // Add new sync node or if this is a reopening of the database after a close() call, update it. + return db.transaction('rw', '_syncNodes', function () { + return db._syncNodes + .where('isMaster').equals(1) + .first(function (currentMaster) { + if (!currentMaster) { + // There's no master. We must be the master + mySyncNode.node.isMaster = 1; + } + else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Master have been inactive for too long + // Take over mastership + mySyncNode.node.isMaster = 1; + currentMaster.isMaster = 0; + return db._syncNodes.put(currentMaster); + } + }).then(function () { + // Add our node to DB and start subscribing to events + return db._syncNodes.add(mySyncNode.node).then(function () { + Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available. + Observable.on('beforeunload', onBeforeUnload); + Observable.on('suicideNurseCall', onSuicide); + Observable.on('intercomm', onIntercomm); + // Start polling for changes and do cleanups: + pollHandle = setTimeout(poll, LOCAL_POLL); + // Start heartbeat + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + }); + }); + }).then(function () { + cleanup(); + }); + }); + }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()). + var handledRevision = 0; + function onLatestRevisionIncremented(dbname, latestRevision) { + if (dbname === db.name) { + if (handledRevision >= latestRevision) + return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window) + handledRevision = latestRevision; + Dexie.vip(function () { + readChanges(latestRevision).catch('DatabaseClosedError', function () { + // Handle database closed error gracefully while reading changes. + // Don't trigger 'unhandledrejection'. + // Even though we intercept the close() method, it might be called when in the middle of + // reading changes and then that flow will cancel with DatabaseClosedError. + }); + }); + } + } + function readChanges(latestRevision, recursion, wasPartial) { + // Whenever changes are read, fire db.on("changes") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is + // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario + // should be handled in case database is totally empty we should fail if sync is not available) + if (!recursion && readChanges.ongoingOperation) { + // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event. + // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges(). + // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished. + return readChanges.ongoingOperation; + } + var partial = false; + var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened. + if (!ourSyncNode) { + return Promise.reject(new Dexie.DatabaseClosedError()); + } + var LIMIT = 1000; + var promise = db._changes.where("rev").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) { + if (changes.length > 0) { + var lastChange = changes[changes.length - 1]; + partial = (changes.length === LIMIT); + db.on('changes').fire(changes, partial); + ourSyncNode.myRevision = lastChange.rev; + } + else if (wasPartial) { + // No more changes, BUT since we have triggered on('changes') with partial = true, + // we HAVE TO trigger changes again with empty list and partial = false + db.on('changes').fire([], false); + } + var ourNodeStillExists = false; + return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(function (syncNode) { + ourNodeStillExists = true; + syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!) + syncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision); + }).then(function () { return ourNodeStillExists; }); + }).then(function (ourNodeStillExists) { + if (!ourNodeStillExists) { + // My node has been deleted. We must have been lazy and got removed by another node. + if (browserIsShuttingDown) { + throw new Error("Browser is shutting down"); + } + else { + db.close(); + console.error("Out of sync"); // TODO: What to do? Reload the page? + if (global.location) + global.location.reload(true); + throw new Error("Out of sync"); // Will make current promise reject + } + } + // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not + // resolve until all changes have been read. + if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) { + // Either there were more than 1000 changes or additional changes where added while we were reading these changes, + // In either case, call readChanges() again until we're done. + return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial); + } + }).finally(function () { + delete readChanges.ongoingOperation; + }); + if (!recursion) { + readChanges.ongoingOperation = promise; + } + return promise; + } + /** + * The reason we need heartbeat in parallell with poll() is due to the risk of long-running + * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will + * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on + * during that changes are being applied and update our lastHeartBeat property while poll() is waiting. + * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this + * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction. + * + * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT + * (20 seconds), another node waking up after the sync would kill the master node and take over because + * it would believe it was dead. + */ + function heartbeat() { + heartbeatHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + db.transaction('rw!', db._syncNodes, function () { + db._syncNodes.where({ id: currentInstance }).first(function (ourSyncNode) { + if (!ourSyncNode) { + // We do not exist anymore. Call db.close() to teardown polls etc. + if (db.isOpen()) + db.close(); + return; + } + ourSyncNode.lastHeartBeat = Date.now(); + ourSyncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + return db._syncNodes.put(ourSyncNode); + }); + }).catch('DatabaseClosedError', function () { + // Ignore silently + }).finally(function () { + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + } + }); + } + function poll() { + pollHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + Dexie.vip(function () { + readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages) + .catch('DatabaseClosedError', function () { + // Handle database closed error gracefully while reading changes. + // Don't trigger 'unhandledrejection'. + // Even though we intercept the close() method, it might be called when in the middle of + // reading changes and then that flow will cancel with DatabaseClosedError. + }) + .finally(function () { + // Poll again in given interval: + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + pollHandle = setTimeout(poll, LOCAL_POLL); + } + }); + }); + } + function cleanup() { + var ourSyncNode = mySyncNode.node; + if (!ourSyncNode) + return Promise.reject(new Dexie.DatabaseClosedError()); + return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function () { + // Cleanup dead local nodes that has no heartbeat for over a minute + // Dont do the following: + //nodes.where("lastHeartBeat").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == "local"; }).delete(); + // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes. + // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead. + var weBecameMaster = false; + db._syncNodes.where("lastHeartBeat").below(Date.now() - NODE_TIMEOUT).filter(function (node) { return node.type === 'local'; }).modify(function (node) { + if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) { + // Delete the node. + delete this.value; + // Cleanup localStorage "deadnode:" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.) + if (localStorage) { + localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name); + } + // Check if we are deleting a master node + if (node.isMaster) { + // The node we are deleting is master. We must take over that role. + // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction! + db._syncNodes.update(ourSyncNode, { isMaster: 1 }); + weBecameMaster = true; + } + // Cleanup intercomm messages destinated to the node being deleted. + // Those that waits for reply should be redirected to us. + db._intercomm.where({ destinationNode: node.id }).modify(function (msg) { + if (msg.wantReply) + msg.destinationNode = ourSyncNode.id; + else + // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request. + delete this.value; + }); + } + else if (!node.deleteTimeStamp) { + // Mark the node for deletion + node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD; + } + }).then(function () { + // Cleanup old revisions that no node is interested of. + Observable.deleteOldChanges(db); + return db.on("cleanup").fire(weBecameMaster); + }); + }); + } + function onBeforeUnload() { + // Mark our own sync node for deletion. + if (!mySyncNode.node) + return; + browserIsShuttingDown = true; + mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now. + Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff... + // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, "dead"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below. + } + } + function onSuicide(dbname, nodeID) { + if (dbname === db.name && !Observable.wereTheOneDying) { + // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies. + // It's own call to put() may have been cancelled. + // Note also that in IE, this event may be called twice, but that doesnt harm! + Dexie.vip(function () { + db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup); + }); + } + } +} +// +// Static properties and methods +// +Observable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37; +Observable.on = Dexie.Events(null, "latestRevisionIncremented", "suicideNurseCall", "intercomm", "beforeunload"); // fire(dbname, value); +Observable.createUUID = createUUID; +Observable.deleteOldChanges = deleteOldChanges; +Observable._onStorage = initOnStorage(Observable); +Observable._onBeforeUnload = function () { + Observable.on.beforeunload.fire(); +}; +try { + Observable.localStorageImpl = global.localStorage; +} +catch (ex) { } +// +// Map window events to static events in Dexie.Observable: +// +if (global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); +} +// Register addon: +Dexie.Observable = Observable; +Dexie.addons.push(Observable); + +export default Observable; +//# sourceMappingURL=dexie-observable.es.js.map diff --git a/addons/Dexie.Observable/dist/dexie-observable.es.js.map b/addons/Dexie.Observable/dist/dexie-observable.es.js.map new file mode 100644 index 000000000..e74c5b71c --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.es.js","sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/change_types.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/on-storage.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js"],"sourcesContent":["export function nop() {}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function() {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\n });\n return uuid;\n}\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1)\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = (function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n })(parent);\n rootTransaction._lastWrittenRevision = Math.max(\n trans._lastWrittenRevision,\n rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n if (localStorage) localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\nimport {createUUID} from '../utils';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: table.name,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n };\n}\n","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n };\n}\n","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n })\n .catch((e) => {\n console.log(obj)\n console.log(e.stack)\n })\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n };\n}\n","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n };\n}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(origFunc) {\n return function(stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function(tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function(tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\nexport default function Observable(db) {\n /// \n /// Extension to Dexie providing Syncronization capabilities to Dexie.\n /// \n /// \n\n var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode.node = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\n\n db.close = override(db.close, function(origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function(origDelete) {\n return function() {\n return origDelete.apply(this, arguments).then(function(result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n \n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = (lastChange ? lastChange.rev : 0);\n mySyncNode.node = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function() {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db.transaction('rw', '_syncNodes', () => {\n return db._syncNodes\n .where('isMaster').equals(1)\n .first(currentMaster => {\n if (!currentMaster) {\n // There's no master. We must be the master\n mySyncNode.node.isMaster = 1;\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Master have been inactive for too long\n // Take over mastership\n mySyncNode.node.isMaster = 1;\n currentMaster.isMaster = 0;\n return db._syncNodes.put(currentMaster);\n }\n }).then(()=>{\n // Add our node to DB and start subscribing to events\n return db._syncNodes.add(mySyncNode.node).then(function() {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n });\n });\n }).then(function () {\n cleanup();\n });\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function() {\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(new Dexie.DatabaseClosedError());\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = (changes.length === LIMIT);\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n Dexie.vip(function() { // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n })\n .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted.\n // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function() {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function() {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n}\n\n//\n// Static properties and methods\n// \n\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n// Register addon:\nDexie.Observable = Observable;\nDexie.addons.push(Observable);\n"],"names":["Promise"],"mappings":";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AgB,CAAC;AAE/C,UAAU,CAAC,UAAU,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;AAElD,UAAU,CAAC,eAAe,GAAG;IACzB,UAAU,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC;CACrC,CAAC;AAEF,IAAI;IACA,UAAU,CAAC,gBAAgB,GAAG,MAAM,CAAC,YAAY,CAAC;CACrD;AAAC,OAAO,EAAE,EAAC,GAAE;;;;AAKd,IAAI,MAAM,CAAC,gBAAgB,EAAE;IACzB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAC1D,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;CACvE;;AAED,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;AAC9B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;;"} \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.js b/addons/Dexie.Observable/dist/dexie-observable.js new file mode 100644 index 000000000..0fcd27ee2 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js @@ -0,0 +1,998 @@ +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.4, Thu Mar 01 2018 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('dexie')) : + typeof define === 'function' && define.amd ? define(['dexie'], factory) : + (global.Dexie = global.Dexie || {}, global.Dexie.Observable = factory(global.Dexie)); +}(this, (function (Dexie) { 'use strict'; + +Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + +function nop() { } +function promisableChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, args = arguments; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} +function createUUID() { + // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript + var d = Date.now(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); + }); + return uuid; +} + +function initOverrideCreateTransaction(db, wakeupObservers) { + return function overrideCreateTransaction(origFunc) { + return function (mode, storenames, dbschema, parent) { + if (db.dynamicallyOpened()) + return origFunc.apply(this, arguments); // Don't observe dynamically opened databases. + var addChanges = false; + if (mode === 'readwrite' && storenames.some(function (storeName) { + return dbschema[storeName] && dbschema[storeName].observable; + })) { + // At least one included store is a observable store. Make sure to also include the _changes store. + addChanges = true; + storenames = storenames.slice(0); // Clone + if (storenames.indexOf("_changes") === -1) + storenames.push("_changes"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla) + } + // Call original db._createTransaction() + var trans = origFunc.call(this, mode, storenames, dbschema, parent); + // If this transaction is bound to any observable table, make sure to add changes when transaction completes. + if (addChanges) { + trans._lastWrittenRevision = 0; + trans.on('complete', function () { + if (trans._lastWrittenRevision) { + // Changes were written in this transaction. + if (!parent) { + // This is root-level transaction, i.e. a physical commit has happened. + // Delay-trigger a wakeup call: + if (wakeupObservers.timeoutHandle) + clearTimeout(wakeupObservers.timeoutHandle); + wakeupObservers.timeoutHandle = setTimeout(function () { + delete wakeupObservers.timeoutHandle; + wakeupObservers(trans._lastWrittenRevision); + }, 25); + } + else { + // This is just a virtual commit of a sub transaction. + // Wait with waking up observers until root transaction has committed. + // Make sure to mark root transaction so that it will wakeup observers upon commit. + var rootTransaction = (function findRootTransaction(trans) { + return trans.parent ? findRootTransaction(trans.parent) : trans; + })(parent); + rootTransaction._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rootTransaction.lastWrittenRevision || 0); + } + } + }); + // Derive "source" property from parent transaction by default + if (trans.parent && trans.parent.source) + trans.source = trans.parent.source; + } + return trans; + }; + }; +} + +function initWakeupObservers(db, Observable, localStorage) { + return function wakeupObservers(lastWrittenRevision) { + // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too. + if (Observable.latestRevision[db.name] < lastWrittenRevision) { + // Set the static property lastRevision[db.name] to the revision of the last written change. + Observable.latestRevision[db.name] = lastWrittenRevision; + // Wakeup ourselves, and any other db instances on this window: + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision); + }); + // Observable.on.latestRevisionIncremented will only wakeup db's in current window. + // We need a storage event to wakeup other windwos. + // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for + // the purpose to wakeup db instances in other windows. + if (localStorage) + localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id. + } + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function initCreatingHook(db, table) { + return function creatingHook(primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = createUUID(); + if (table.schema.primKey.keyPath) { + Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey); + } + } + var change = { + source: trans.source || null, + table: table.name, + key: primKey === undefined ? null : primKey, + type: CREATE, + obj: obj + }; + var promise = db._changes.add(change).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }); + // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so. + this.onsuccess = function (resultKey) { + if (primKey != resultKey) + promise._then(function () { + change.key = resultKey; + db._changes.put(change); + }); + }; + this.onerror = function () { + // If the main operation fails, make sure to regret the change + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + return rv; + }; +} + +function initUpdatingHook(db, tableName) { + return function updatingHook(mods, primKey, oldObj, trans) { + /// + // mods may contain property paths with undefined as value if the property + // is being deleted. Since we cannot persist undefined we need to act + // like those changes is setting the value to null instead. + var modsWithoutUndefined = {}; + // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change. + // Therefore we may do that kind of optimization here - to not add change entries if + // there's nothing to change. + var anythingChanged = false; + var newObj = Dexie.deepClone(oldObj); + for (var propPath in mods) { + var mod = mods[propPath]; + if (typeof mod === 'undefined') { + Dexie.delByKeyPath(newObj, propPath); + modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined. + anythingChanged = true; + } + else { + var currentValue = Dexie.getByKeyPath(oldObj, propPath); + if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) { + Dexie.setByKeyPath(newObj, propPath, mod); + modsWithoutUndefined[propPath] = mod; + anythingChanged = true; + } + } + } + if (anythingChanged) { + var change = { + source: trans.source || null, + table: tableName, + key: primKey, + type: UPDATE, + mods: modsWithoutUndefined, + oldObj: oldObj, + obj: newObj + }; + var promise = db._changes.add(change); // Just so we get the correct revision order of the update... + this.onsuccess = function () { + promise._then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + }); + }; + this.onerror = function () { + // If the main operation fails, make sure to regret the change. + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + } + }; +} + +function initDeletingHook(db, tableName) { + return function deletingHook(primKey, obj, trans) { + /// + var promise = db._changes.add({ + source: trans.source || null, + table: tableName, + key: primKey, + type: DELETE, + oldObj: obj + }).then(function (rev) { + trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev); + return rev; + }) + .catch(function (e) { + console.log(obj); + console.log(e.stack); + }); + this.onerror = function () { + // If the main operation fails, make sure to regret the change. + // Using _then because if promise is already fullfilled, the standard then() would + // do setTimeout() and we would loose the transaction. + promise._then(function (rev) { + // Will only happen if app code catches the main operation error to prohibit transaction from aborting. + db._changes.delete(rev); + }); + }; + }; +} + +function initCrudMonitor(db) { + // + // The Creating/Updating/Deleting hook will make sure any change is stored to the changes table + // + return function crudMonitor(table) { + /// + if (table.hook._observing) + return; + table.hook._observing = true; + var tableName = table.name; + table.hook('creating').subscribe(initCreatingHook(db, table)); + table.hook('updating').subscribe(initUpdatingHook(db, tableName)); + table.hook('deleting').subscribe(initDeletingHook(db, tableName)); + }; +} + +function initOnStorage(Observable) { + return function onStorage(event) { + // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well! + if (event.key.indexOf("Dexie.Observable/") === 0) { + var parts = event.key.split('/'); + var prop = parts[1]; + var dbname = parts[2]; + if (prop === 'latestRevision') { + var rev = parseInt(event.newValue, 10); + if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) { + Observable.latestRevision[dbname] = rev; + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(dbname, rev); + }); + } + } + else if (prop.indexOf("deadnode:") === 0) { + var nodeID = parseInt(prop.split(':')[1], 10); + if (event.newValue) { + Observable.on.suicideNurseCall.fire(dbname, nodeID); + } + } + else if (prop === 'intercomm') { + if (event.newValue) { + Observable.on.intercomm.fire(dbname); + } + } + } + }; +} + +function initOverrideOpen(db, SyncNode, crudMonitor) { + return function overrideOpen(origOpen) { + return function () { + // + // Make sure to subscribe to "creating", "updating" and "deleting" hooks for all observable tables that were created in the stores() method. + // + Object.keys(db._allTables).forEach(function (tableName) { + var table = db._allTables[tableName]; + if (table.schema.observable) { + crudMonitor(table); + } + if (table.name === "_syncNodes") { + table.mapToClass(SyncNode); + } + }); + return origOpen.apply(this, arguments); + }; + }; +} + +var Promise$1 = Dexie.Promise; +function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) { + // + // Intercommunication between nodes + // + // Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable) + var requestsWaitingForReply = {}; + /** + * @param {string} type Type of message + * @param message Message to send + * @param {number} destinationNode ID of destination node + * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + */ + db.observable.sendMessage = function (type, message, destinationNode, options) { + /// Type of message + /// Message to send + /// ID of destination node + /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent. + options = options || {}; + if (!mySyncNode.node) + return options.wantReply ? + Promise$1.reject(new Dexie.DatabaseClosedError()) : + Promise$1.resolve(); // If caller doesn't want a reply, it won't catch errors either. + var msg = { message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type }; + Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + return Dexie.ignoreTransaction(function () { + var tables = ["_intercomm"]; + if (options.wantReply) + tables.push("_syncNodes"); // If caller wants a reply, include "_syncNodes" in transaction to check that there's a receiver there. Otherwise, new master will get it. + var promise = db.transaction('rw', tables, function () { + if (options.wantReply) { + // Check that there is a receiver there to take the request. + return db._syncNodes.where('id').equals(destinationNode).count(function (receiverAlive) { + if (receiverAlive) + return db._intercomm.add(msg); + else + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + msg.destinationNode = masterNode.id; + return db._intercomm.add(msg); + }); + }); + } + else { + // If caller doesn't need a response, we don't have to make sure that it gets one. + return db._intercomm.add(msg); + } + }).then(function (messageId) { + var rv = null; + if (options.wantReply) { + rv = new Promise$1(function (resolve, reject) { + requestsWaitingForReply[messageId.toString()] = { resolve: resolve, reject: reject }; + }); + } + if (localStorage) { + localStorage.setItem("Dexie.Observable/intercomm/" + db.name, messageId.toString()); + } + Observable.on.intercomm.fire(db.name); + return rv; + }); + if (!options.wantReply) { + promise.catch(function () { + }); + return; + } + else { + // Forward rejection to caller if it waits for reply. + return promise; + } + }); + }; + // Send a message to all local _syncNodes + db.observable.broadcastMessage = function (type, message, bIncludeSelf) { + if (!mySyncNode.node) + return; + var mySyncNodeId = mySyncNode.node.id; + Dexie.ignoreTransaction(function () { + db._syncNodes.toArray(function (nodes) { + return Promise$1.all(nodes + .filter(function (node) { return node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId); }) + .map(function (node) { return db.observable.sendMessage(type, message, node.id); })); + }).catch(function () { + }); + }); + }; + function consumeIntercommMessages() { + // Check if we got messages: + if (!mySyncNode.node) + return Promise$1.reject(new Dexie.DatabaseClosedError()); + return Dexie.ignoreTransaction(function () { + return db.transaction('rw', '_intercomm', function () { + return db._intercomm.where({ destinationNode: mySyncNode.node.id }).toArray(function (messages) { + messages.forEach(function (msg) { return consumeMessage(msg); }); + return db._intercomm.where('id').anyOf(messages.map(function (msg) { return msg.id; })).delete(); + }); + }); + }); + } + function consumeMessage(msg) { + if (msg.type === 'response') { + // This is a response. Lookup pending request and fulfill its promise. + var request = requestsWaitingForReply[msg.requestId.toString()]; + if (request) { + if (msg.isFailure) { + request.reject(msg.message.error); + } + else { + request.resolve(msg.message.result); + } + delete requestsWaitingForReply[msg.requestId.toString()]; + } + } + else { + // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested + msg.resolve = function (result) { + db.observable.sendMessage('response', { result: result }, msg.sender, { requestId: msg.id }); + }; + msg.reject = function (error) { + db.observable.sendMessage('response', { error: error.toString() }, msg.sender, { isFailure: true, requestId: msg.id }); + }; + db.on.message.fire(msg); + } + } + // Listener for 'intercomm' events + // Gets fired when we get a 'storage' event from local storage or when sendMessage is called + // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event) + // sendMessage is used to communicate in the same tab and to trigger a storage event + function onIntercomm(dbname) { + // When storage event trigger us to check + if (dbname === db.name) { + consumeIntercommMessages().catch('DatabaseClosedError', function () { }); + } + } + return { + onIntercomm: onIntercomm, + consumeIntercommMessages: consumeIntercommMessages + }; +} + +function overrideParseStoresSpec(origFunc) { + return function (stores, dbSchema) { + // Create the _changes and _syncNodes tables + stores["_changes"] = "++rev"; + stores["_syncNodes"] = "++id,myRevision,lastHeartBeat,&url,isMaster,type,status"; + stores["_intercomm"] = "++id,destinationNode"; + stores["_uncommittedChanges"] = "++id,node"; // For remote syncing when server returns a partial result. + // Call default implementation. Will populate the dbSchema structures. + origFunc.call(this, stores, dbSchema); + // Allow UUID primary keys using $$ prefix on primary key or indexes + Object.keys(dbSchema).forEach(function (tableName) { + var schema = dbSchema[tableName]; + if (schema.primKey.name.indexOf('$$') === 0) { + schema.primKey.uuid = true; + schema.primKey.name = schema.primKey.name.substr(2); + schema.primKey.keyPath = schema.primKey.keyPath.substr(2); + } + }); + // Now mark all observable tables + Object.keys(dbSchema).forEach(function (tableName) { + // Marked observable tables with "observable" in their TableSchema. + if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) { + dbSchema[tableName].observable = true; + } + }); + }; +} + +function deleteOldChanges(db) { + // This is a background job and should never be done within + // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that. + // We should not return the Promise but catch it ourselves instead. + // To prohibit starving the database we want to lock transactions as short as possible + // and since we're not in a hurry, we could do this job in chunks and reschedule a + // continuation every 500 ms. + var CHUNK_SIZE = 100; + Dexie.ignoreTransaction(function () { + return db._syncNodes.orderBy("myRevision").first(function (oldestNode) { + return db._changes + .where("rev").below(oldestNode.myRevision) + .limit(CHUNK_SIZE) + .primaryKeys(); + }).then(function (keysToDelete) { + if (keysToDelete.length === 0) + return; // Done. + return db._changes.bulkDelete(keysToDelete).then(function () { + // If not done garbage collecting, reschedule a continuation of it until done. + if (keysToDelete.length === CHUNK_SIZE) { + // Limit reached. Changes are there are more job to do. Schedule again: + setTimeout(function () { return db.isOpen() && deleteOldChanges(db); }, 500); + } + }); + }); + }).catch(function () { + // The operation is not crucial. A failure could almost only be due to that database has been closed. + // No need to log this. + }); +} + +/* ========================================================================== + * dexie-observable.js + * ========================================================================== + * + * Dexie addon for observing database changes not just on local db instance + * but also on other instances, tabs and windows. + * + * Comprises a base framework for dexie-syncable.js + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.4, Thu Mar 01 2018 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +var global = self; +/** class DatabaseChange + * + * Object contained by the _changes table. + */ +var DatabaseChange = Dexie.defineClass({ + rev: Number, + source: String, + table: String, + key: Object, + type: Number, + obj: Object, + mods: Object, + oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied. +}); +// Import some usable helper functions +var override = Dexie.override; +var Promise = Dexie.Promise; +var browserIsShuttingDown = false; +function Observable(db) { + /// + /// Extension to Dexie providing Syncronization capabilities to Dexie. + /// + /// + var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects. + HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds + // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. + // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process) + LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event. + HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000; + var localStorage = Observable.localStorageImpl; + /** class SyncNode + * + * Object contained in the _syncNodes table. + */ + var SyncNode = Dexie.defineClass({ + //id: Number, + myRevision: Number, + type: String, + lastHeartBeat: Number, + deleteTimeStamp: Number, + url: String, + isMaster: Number, + // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == "remote"): + syncProtocol: String, + syncContext: null, + syncOptions: Object, + connected: false, + status: Number, + appliedRemoteRevision: null, + remoteBaseRevisions: [{ local: Number, remote: null }], + dbUploadState: { + tablesToUpload: [String], + currentTable: String, + currentKey: null, + localBaseRevision: Number + } + }); + db.observable = {}; + db.observable.SyncNode = SyncNode; + var wakeupObservers = initWakeupObservers(db, Observable, localStorage); + var overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers); + var crudMonitor = initCrudMonitor(db); + var overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor); + var mySyncNode = { node: null }; + var intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage); + var onIntercomm = intercomm.onIntercomm; + var consumeIntercommMessages = intercomm.consumeIntercommMessages; + // Allow other addons to access the local sync node. May be needed by Dexie.Syncable. + Object.defineProperty(db, "_localSyncNode", { + get: function () { return mySyncNode.node; } + }); + var pollHandle = null, heartbeatHandle = null; + if (Dexie.fake) { + // This code will never run. + // It's here just to enable auto-complete in visual studio - helps a lot when writing code. + db.version(1).stores({ + _syncNodes: "++id,myRevision,lastHeartBeat", + _changes: "++rev", + _intercomm: "++id,destinationNode", + _uncommittedChanges: "++id,node" + }); + db._syncNodes.mapToClass(SyncNode); + db._changes.mapToClass(DatabaseChange); + mySyncNode.node = new SyncNode({ + myRevision: 0, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null + }); + } + // + // Override parsing the stores to add "_changes" and "_syncNodes" tables. + // It also adds UUID support for the primary key and sets tables as observable tables. + // + db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec); + // changes event on db: + db.on.addEventType({ + changes: 'asap', + cleanup: [promisableChain, nop], + message: 'asap' + }); + // + // Override transaction creation to always include the "_changes" store when any observable store is involved. + // + db._createTransaction = override(db._createTransaction, overrideCreateTransaction); + // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works. + // You might think that it will always be undefined before this call, but in case another Dexie instance in the same + // window with the same database name has been created already, this static property will already be set correctly. + Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0; + // + // Override open to setup hooks for db changes and map the _syncNodes table to class + // + db.open = override(db.open, overrideOpen); + db.close = override(db.close, function (origClose) { + return function () { + if (db.dynamicallyOpened()) + return origClose.apply(this, arguments); // Don't observe dynamically opened databases. + // Teardown our framework. + if (wakeupObservers.timeoutHandle) { + clearTimeout(wakeupObservers.timeoutHandle); + delete wakeupObservers.timeoutHandle; + } + Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented); + Observable.on('suicideNurseCall').unsubscribe(onSuicide); + Observable.on('intercomm').unsubscribe(onIntercomm); + Observable.on('beforeunload').unsubscribe(onBeforeUnload); + // Inform other db instances in same window that we are dying: + if (mySyncNode.node && mySyncNode.node.id) { + Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id); + // Inform other windows as well: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, "dead"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything. + } + mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now. + mySyncNode.node = null; + } + if (pollHandle) + clearTimeout(pollHandle); + pollHandle = null; + if (heartbeatHandle) + clearTimeout(heartbeatHandle); + heartbeatHandle = null; + return origClose.apply(this, arguments); + }; + }); + // Override Dexie.delete() in order to delete Observable.latestRevision[db.name]. + db.delete = override(db.delete, function (origDelete) { + return function () { + return origDelete.apply(this, arguments).then(function (result) { + // Reset Observable.latestRevision[db.name] + Observable.latestRevision[db.name] = 0; + return result; + }); + }; + }); + // When db opens, make sure to start monitor any changes before other db operations will start. + db.on("ready", function startObserving() { + if (db.dynamicallyOpened()) + return db; // Don't observe dynamically opened databases. + return db.table("_changes").orderBy("rev").last(function (lastChange) { + // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db. + // Therefore we know that the retrieved value will be This query will + var latestRevision = (lastChange ? lastChange.rev : 0); + mySyncNode.node = new SyncNode({ + myRevision: latestRevision, + type: "local", + lastHeartBeat: Date.now(), + deleteTimeStamp: null, + isMaster: 0 + }); + if (Observable.latestRevision[db.name] < latestRevision) { + // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased: + // There are other db instances in same window that hasnt yet been informed about a new revision + Observable.latestRevision[db.name] = latestRevision; + Dexie.ignoreTransaction(function () { + Observable.on.latestRevisionIncremented.fire(latestRevision); + }); + } + // Add new sync node or if this is a reopening of the database after a close() call, update it. + return db.transaction('rw', '_syncNodes', function () { + return db._syncNodes + .where('isMaster').equals(1) + .first(function (currentMaster) { + if (!currentMaster) { + // There's no master. We must be the master + mySyncNode.node.isMaster = 1; + } + else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Master have been inactive for too long + // Take over mastership + mySyncNode.node.isMaster = 1; + currentMaster.isMaster = 0; + return db._syncNodes.put(currentMaster); + } + }).then(function () { + // Add our node to DB and start subscribing to events + return db._syncNodes.add(mySyncNode.node).then(function () { + Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available. + Observable.on('beforeunload', onBeforeUnload); + Observable.on('suicideNurseCall', onSuicide); + Observable.on('intercomm', onIntercomm); + // Start polling for changes and do cleanups: + pollHandle = setTimeout(poll, LOCAL_POLL); + // Start heartbeat + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + }); + }); + }).then(function () { + cleanup(); + }); + }); + }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()). + var handledRevision = 0; + function onLatestRevisionIncremented(dbname, latestRevision) { + if (dbname === db.name) { + if (handledRevision >= latestRevision) + return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window) + handledRevision = latestRevision; + Dexie.vip(function () { + readChanges(latestRevision).catch('DatabaseClosedError', function () { + // Handle database closed error gracefully while reading changes. + // Don't trigger 'unhandledrejection'. + // Even though we intercept the close() method, it might be called when in the middle of + // reading changes and then that flow will cancel with DatabaseClosedError. + }); + }); + } + } + function readChanges(latestRevision, recursion, wasPartial) { + // Whenever changes are read, fire db.on("changes") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is + // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario + // should be handled in case database is totally empty we should fail if sync is not available) + if (!recursion && readChanges.ongoingOperation) { + // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event. + // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges(). + // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished. + return readChanges.ongoingOperation; + } + var partial = false; + var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened. + if (!ourSyncNode) { + return Promise.reject(new Dexie.DatabaseClosedError()); + } + var LIMIT = 1000; + var promise = db._changes.where("rev").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) { + if (changes.length > 0) { + var lastChange = changes[changes.length - 1]; + partial = (changes.length === LIMIT); + db.on('changes').fire(changes, partial); + ourSyncNode.myRevision = lastChange.rev; + } + else if (wasPartial) { + // No more changes, BUT since we have triggered on('changes') with partial = true, + // we HAVE TO trigger changes again with empty list and partial = false + db.on('changes').fire([], false); + } + var ourNodeStillExists = false; + return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(function (syncNode) { + ourNodeStillExists = true; + syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!) + syncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision); + }).then(function () { return ourNodeStillExists; }); + }).then(function (ourNodeStillExists) { + if (!ourNodeStillExists) { + // My node has been deleted. We must have been lazy and got removed by another node. + if (browserIsShuttingDown) { + throw new Error("Browser is shutting down"); + } + else { + db.close(); + console.error("Out of sync"); // TODO: What to do? Reload the page? + if (global.location) + global.location.reload(true); + throw new Error("Out of sync"); // Will make current promise reject + } + } + // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not + // resolve until all changes have been read. + if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) { + // Either there were more than 1000 changes or additional changes where added while we were reading these changes, + // In either case, call readChanges() again until we're done. + return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial); + } + }).finally(function () { + delete readChanges.ongoingOperation; + }); + if (!recursion) { + readChanges.ongoingOperation = promise; + } + return promise; + } + /** + * The reason we need heartbeat in parallell with poll() is due to the risk of long-running + * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will + * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on + * during that changes are being applied and update our lastHeartBeat property while poll() is waiting. + * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this + * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction. + * + * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT + * (20 seconds), another node waking up after the sync would kill the master node and take over because + * it would believe it was dead. + */ + function heartbeat() { + heartbeatHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + db.transaction('rw!', db._syncNodes, function () { + db._syncNodes.where({ id: currentInstance }).first(function (ourSyncNode) { + if (!ourSyncNode) { + // We do not exist anymore. Call db.close() to teardown polls etc. + if (db.isOpen()) + db.close(); + return; + } + ourSyncNode.lastHeartBeat = Date.now(); + ourSyncNode.deleteTimeStamp = null; // Reset "deleteTimeStamp" flag if it was there. + return db._syncNodes.put(ourSyncNode); + }); + }).catch('DatabaseClosedError', function () { + // Ignore silently + }).finally(function () { + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL); + } + }); + } + function poll() { + pollHandle = null; + var currentInstance = mySyncNode.node && mySyncNode.node.id; + if (!currentInstance) + return; + Dexie.vip(function () { + readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages) + .catch('DatabaseClosedError', function () { + // Handle database closed error gracefully while reading changes. + // Don't trigger 'unhandledrejection'. + // Even though we intercept the close() method, it might be called when in the middle of + // reading changes and then that flow will cancel with DatabaseClosedError. + }) + .finally(function () { + // Poll again in given interval: + if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) { + pollHandle = setTimeout(poll, LOCAL_POLL); + } + }); + }); + } + function cleanup() { + var ourSyncNode = mySyncNode.node; + if (!ourSyncNode) + return Promise.reject(new Dexie.DatabaseClosedError()); + return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function () { + // Cleanup dead local nodes that has no heartbeat for over a minute + // Dont do the following: + //nodes.where("lastHeartBeat").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == "local"; }).delete(); + // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes. + // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead. + var weBecameMaster = false; + db._syncNodes.where("lastHeartBeat").below(Date.now() - NODE_TIMEOUT).filter(function (node) { return node.type === 'local'; }).modify(function (node) { + if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) { + // Delete the node. + delete this.value; + // Cleanup localStorage "deadnode:" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.) + if (localStorage) { + localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name); + } + // Check if we are deleting a master node + if (node.isMaster) { + // The node we are deleting is master. We must take over that role. + // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction! + db._syncNodes.update(ourSyncNode, { isMaster: 1 }); + weBecameMaster = true; + } + // Cleanup intercomm messages destinated to the node being deleted. + // Those that waits for reply should be redirected to us. + db._intercomm.where({ destinationNode: node.id }).modify(function (msg) { + if (msg.wantReply) + msg.destinationNode = ourSyncNode.id; + else + // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request. + delete this.value; + }); + } + else if (!node.deleteTimeStamp) { + // Mark the node for deletion + node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD; + } + }).then(function () { + // Cleanup old revisions that no node is interested of. + Observable.deleteOldChanges(db); + return db.on("cleanup").fire(weBecameMaster); + }); + }); + } + function onBeforeUnload() { + // Mark our own sync node for deletion. + if (!mySyncNode.node) + return; + browserIsShuttingDown = true; + mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy. + mySyncNode.node.lastHeartBeat = 0; + db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now. + Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff... + // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below: + if (localStorage) { + localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, "dead"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below. + } + } + function onSuicide(dbname, nodeID) { + if (dbname === db.name && !Observable.wereTheOneDying) { + // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies. + // It's own call to put() may have been cancelled. + // Note also that in IE, this event may be called twice, but that doesnt harm! + Dexie.vip(function () { + db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup); + }); + } + } +} +// +// Static properties and methods +// +Observable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37; +Observable.on = Dexie.Events(null, "latestRevisionIncremented", "suicideNurseCall", "intercomm", "beforeunload"); // fire(dbname, value); +Observable.createUUID = createUUID; +Observable.deleteOldChanges = deleteOldChanges; +Observable._onStorage = initOnStorage(Observable); +Observable._onBeforeUnload = function () { + Observable.on.beforeunload.fire(); +}; +try { + Observable.localStorageImpl = global.localStorage; +} +catch (ex) { } +// +// Map window events to static events in Dexie.Observable: +// +if (global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); +} +// Register addon: +Dexie.Observable = Observable; +Dexie.addons.push(Observable); + +return Observable; + +}))); +//# sourceMappingURL=dexie-observable.js.map diff --git a/addons/Dexie.Observable/dist/dexie-observable.js.map b/addons/Dexie.Observable/dist/dexie-observable.js.map new file mode 100644 index 000000000..f516e5a0f --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.js","sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/change_types.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/on-storage.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js"],"sourcesContent":["export function nop() {}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function() {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\n });\n return uuid;\n}\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1)\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = (function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n })(parent);\n rootTransaction._lastWrittenRevision = Math.max(\n trans._lastWrittenRevision,\n rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n if (localStorage) localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\nimport {createUUID} from '../utils';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: table.name,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n };\n}\n","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n };\n}\n","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n })\n .catch((e) => {\n console.log(obj)\n console.log(e.stack)\n })\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n };\n}\n","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n };\n}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(origFunc) {\n return function(stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function(tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function(tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\nexport default function Observable(db) {\n /// \n /// Extension to Dexie providing Syncronization capabilities to Dexie.\n /// \n /// \n\n var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode.node = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\n\n db.close = override(db.close, function(origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function(origDelete) {\n return function() {\n return origDelete.apply(this, arguments).then(function(result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n \n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = (lastChange ? lastChange.rev : 0);\n mySyncNode.node = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function() {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db.transaction('rw', '_syncNodes', () => {\n return db._syncNodes\n .where('isMaster').equals(1)\n .first(currentMaster => {\n if (!currentMaster) {\n // There's no master. We must be the master\n mySyncNode.node.isMaster = 1;\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Master have been inactive for too long\n // Take over mastership\n mySyncNode.node.isMaster = 1;\n currentMaster.isMaster = 0;\n return db._syncNodes.put(currentMaster);\n }\n }).then(()=>{\n // Add our node to DB and start subscribing to events\n return db._syncNodes.add(mySyncNode.node).then(function() {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n });\n });\n }).then(function () {\n cleanup();\n });\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function() {\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(new Dexie.DatabaseClosedError());\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = (changes.length === LIMIT);\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n Dexie.vip(function() { // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n })\n .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted.\n // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function() {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function() {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n}\n\n//\n// Static properties and methods\n// \n\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n// Register addon:\nDexie.Observable = Observable;\nDexie.addons.push(Observable);\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAAwB;AAExB,yBAAgC,EAAE,EAAE,EAAE;IACpC,IAAI,EAAE,KAAK,GAAG;QAAE,OAAO,EAAE,CAAC;IAC1B,OAAO;QACL,IAAI,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;QACpC,IAAI,GAAG,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,EAAE;YACzC,IAAI,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;YAClC,OAAO,GAAG,CAAC,IAAI,CAAC;gBACd,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;aAC7B,CAAC,CAAC;SACJ;QACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;KAClC,CAAC;CACH;AAED;;IAEE,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACnB,IAAI,IAAI,GAAG,sCAAsC,CAAC,OAAO,CAAC,OAAO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.js new file mode 100644 index 000000000..dbc31c89a --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n(require("dexie")):"function"==typeof define&&define.amd?define(["dexie"],n):(e.Dexie=e.Dexie||{},e.Dexie.Observable=n(e.Dexie))}(this,function(e){"use strict";function n(){}function t(e,t){return e===n?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){var o=this,i=arguments;return n.then(function(){return t.apply(o,i)})}return t.apply(this,arguments)}}function o(){var e=Date.now();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===n?t:7&t|8).toString(16)})}function i(e,n){return function(t){return function(o,i,r,a){if(e.dynamicallyOpened())return t.apply(this,arguments);var s=!1;"readwrite"===o&&i.some(function(e){return r[e]&&r[e].observable})&&(s=!0,i=i.slice(0),-1===i.indexOf("_changes")&&i.push("_changes"));var c=t.call(this,o,i,r,a);return s&&(c._lastWrittenRevision=0,c.on("complete",function(){if(c._lastWrittenRevision)if(a){var e=function e(n){return n.parent?e(n.parent):n}(a);e._lastWrittenRevision=Math.max(c._lastWrittenRevision,e.lastWrittenRevision||0)}else n.timeoutHandle&&clearTimeout(n.timeoutHandle),n.timeoutHandle=setTimeout(function(){delete n.timeoutHandle,n(c._lastWrittenRevision)},25)}),c.parent&&c.parent.source&&(c.source=c.parent.source)),c}}}function r(n,t,o){return function(i){t.latestRevision[n.name]=t)return;W=t,e.vip(function(){s(t).catch("DatabaseClosedError",function(){})})}}function s(n,t,i){if(!t&&s.ongoingOperation)return s.ongoingOperation;var r=!1,a=B.node;if(!a)return R.reject(new e.DatabaseClosedError);var c=o._changes.where("rev").above(a.myRevision).limit(1e3).toArray(function(e){if(e.length>0){var n=e[e.length-1];r=1e3===e.length,o.on("changes").fire(e,r),a.myRevision=n.rev}else i&&o.on("changes").fire([],!1);var t=!1;return o._syncNodes.where(":id").equals(a.id).modify(function(e){t=!0,e.lastHeartBeat=Date.now(),e.deleteTimeStamp=null,e.myRevision=Math.max(e.myRevision,a.myRevision)}).then(function(){return t})}).then(function(e){if(!e)throw w?new Error("Browser is shutting down"):(o.close(),console.error("Out of sync"),g.location&&g.location.reload(!0),new Error("Out of sync"));if(r||v.latestRevision[o.name]>a.myRevision)return s(v.latestRevision[o.name],(t||0)+1,r)}).finally(function(){delete s.ongoingOperation});return t||(s.ongoingOperation=c),c}function c(){P=null;var e=B.node&&B.node.id;e&&o.transaction("rw!",o._syncNodes,function(){o._syncNodes.where({id:e}).first(function(e){return e?(e.lastHeartBeat=Date.now(),e.deleteTimeStamp=null,o._syncNodes.put(e)):void(o.isOpen()&&o.close())})}).catch("DatabaseClosedError",function(){}).finally(function(){B.node&&B.node.id===e&&o.isOpen()&&(P=setTimeout(c,S))})}function m(){K=null;var n=B.node&&B.node.id;n&&e.vip(function(){s(v.latestRevision[o.name]).then(y).then(H).catch("DatabaseClosedError",function(){}).finally(function(){B.node&&B.node.id===n&&o.isOpen()&&(K=setTimeout(m,O))})})}function y(){var n=B.node;return n?o.transaction("rw","_syncNodes","_changes","_intercomm",function(){var e=!1;o._syncNodes.where("lastHeartBeat").below(Date.now()-b).filter(function(e){return"local"===e.type}).modify(function(t){t.deleteTimeStamp&&t.deleteTimeStampn.latestRevision[r]&&(n.latestRevision[r]=a,e.ignoreTransaction(function(){n.on("latestRevisionIncremented").fire(r,a)}))}else if(0===i.indexOf("deadnode:")){var s=parseInt(i.split(":")[1],10);t.newValue&&n.on.suicideNurseCall.fire(r,s)}else"intercomm"===i&&t.newValue&&n.on.intercomm.fire(r)}}}(v),v._onBeforeUnload=function(){v.on.beforeunload.fire()};try{v.localStorageImpl=g.localStorage}catch(e){}return g.addEventListener&&(g.addEventListener("storage",v._onStorage),g.addEventListener("beforeunload",v._onBeforeUnload)),e.Observable=v,e.addons.push(v),v}); +//# sourceMappingURL=dist/dexie-observable.min.js.map \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.min.js.map b/addons/Dexie.Observable/dist/dexie-observable.min.js.map new file mode 100644 index 000000000..86a727619 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js","../src/change_types.js","../src/on-storage.js"],"names":["promisableChain","f1","f2","nop","res","apply","this","arguments","then","thiz","args","createUUID","d","Date","now","replace","c","r","Math","random","floor","toString","db","wakeupObservers","origFunc","mode","storenames","dbschema","parent","dynamicallyOpened","addChanges","some","storeName","observable","slice","indexOf","push","trans","call","_lastWrittenRevision","on","rootTransaction","findRootTransaction","max","lastWrittenRevision","timeoutHandle","clearTimeout","setTimeout","source","Observable","localStorage","latestRevision","name","Dexie","ignoreTransaction","fire","setItem","table","primKey","obj","rv","undefined","schema","uuid","keyPath","setByKeyPath","change","key","type","CREATE","promise","_changes","add","rev","onsuccess","resultKey","_then","put","onerror","delete","tableName","mods","oldObj","modsWithoutUndefined","anythingChanged","newObj","deepClone","propPath","mod","delByKeyPath","currentValue","getByKeyPath","JSON","stringify","UPDATE","DELETE","catch","e","console","log","stack","hook","_observing","subscribe","initCreatingHook","initUpdatingHook","initDeletingHook","SyncNode","crudMonitor","origOpen","Object","keys","_allTables","forEach","mapToClass","initIntercomm","mySyncNode","consumeIntercommMessages","node","transaction","_intercomm","where","destinationNode","id","toArray","messages","msg","consumeMessage","anyOf","map","Promise","reject","DatabaseClosedError","request","requestsWaitingForReply","requestId","isFailure","message","error","resolve","result","sendMessage","sender","onIntercomm","dbname","options","wantReply","extend","tables","_syncNodes","equals","count","receiverAlive","above","first","masterNode","messageId","intercomm","broadcastMessage","bIncludeSelf","mySyncNodeId","nodes","all","filter","stores","dbSchema","substr","orderBy","oldestNode","below","myRevision","limit","primaryKeys","keysToDelete","length","bulkDelete","isOpen","deleteOldChanges","onLatestRevisionIncremented","handledRevision","vip","readChanges","recursion","wasPartial","ongoingOperation","partial","ourSyncNode","changes","lastChange","ourNodeStillExists","modify","syncNode","lastHeartBeat","deleteTimeStamp","browserIsShuttingDown","Error","close","global","location","reload","finally","heartbeat","heartbeatHandle","currentInstance","HEARTBEAT_INTERVAL","poll","pollHandle","cleanup","LOCAL_POLL","weBecameMaster","NODE_TIMEOUT","value","removeItem","isMaster","update","HIBERNATE_GRACE_PERIOD","onBeforeUnload","wereTheOneDying","onSuicide","nodeID","localStorageImpl","defineClass","Number","String","url","syncProtocol","syncContext","syncOptions","connected","status","appliedRemoteRevision","remoteBaseRevisions","local","remote","dbUploadState","tablesToUpload","currentTable","currentKey","localBaseRevision","initWakeupObservers","overrideCreateTransaction","initOverrideCreateTransaction","initCrudMonitor","overrideOpen","initOverrideOpen","defineProperty","get","fake","version","_uncommittedChanges","DatabaseChange","Version","prototype","_parseStoresSpec","override","overrideParseStoresSpec","addEventType","_createTransaction","open","origClose","unsubscribe","suicideNurseCall","origDelete","last","latestRevisionIncremented","currentMaster","self","Events","_onStorage","event","parts","split","prop","parseInt","newValue","isNaN","_onBeforeUnload","beforeunload","ex","addEventListener","addons"],"mappings":"kQAEA,QAAAA,GAAgCC,EAAIC,GAClC,MAAID,KAAOE,EAAYD,EAChB,WACL,GAAIE,GAAMH,EAAGI,MAAMC,KAAMC,UACzB,IAAIH,GAA2B,kBAAbA,GAAII,KAAqB,CACzC,GAAIC,GAAOH,KAAMI,EAAOH,SACxB,OAAOH,GAAII,KAAK,WACd,MAAON,GAAGG,MAAMI,EAAMC,KAG1B,MAAOR,GAAGG,MAAMC,KAAMC,YAI1B,QAAAI,KAEE,GAAIC,GAAIC,KAAKC,KAMb,OALW,uCAAuCC,QAAQ,QAAS,SAASC,GAC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AIhC,QAAQ,qBAA4B,CAChD,GAAI2O,GAAQD,EAAM1M,IAAI4M,MAAM,KACxBC,EAAOF,EAAM,GACb9H,EAAS8H,EAAM,EACnB,IAAa,mBAATE,EAA2B,CAC7B,GAAIvM,GAAMwM,SAASJ,EAAMK,SAAU,KAC9BC,MAAM1M,IAAQA,EAAMxB,EAAWE,eAAe6F,KACjD/F,EAAWE,eAAe6F,GAAUvE,EACpCpB,EAAMC,kBAAkB,WACtBL,EAAWT,GAAG,6BAA6Be,KAAKyF,EAAQvE,UAGvD,IAAkC,IAA9BuM,EAAK7O,QAAQ,aAAoB,CAC1C,GAAIwL,GAASsD,SAASD,EAAKD,MAAM,KAAK,GAAI,GACtCF,GAAMK,UACRjO,EAAWT,GAAG6N,iBAAiB9M,KAAKyF,EAAQ2E,OAE5B,cAATqD,GACLH,EAAMK,UACRjO,EAAWT,GAAGqH,UAAUtG,KAAKyF,MFwdD/F,GAEtCA,EAAWmO,gBAAkB,WACzBnO,EAAWT,GAAG6O,aAAa9N,OAG/B,KACIN,EAAW2K,iBAAmBvB,EAAOnJ,aACvC,MAAOoO,UAKLjF,GAAOkF,mBACPlF,EAAOkF,iBAAiB,UAAWtO,EAAW2N,YAC9CvE,EAAOkF,iBAAiB,eAAgBtO,EAAWmO,kBAGvD/N,EAAMJ,WAAaA,EACnBI,EAAMmO,OAAOpP,KAAKa","file":"dist/dexie-observable.min.js","sourcesContent":["export function nop() {}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function() {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\n });\n return uuid;\n}\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1)\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = (function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n })(parent);\n rootTransaction._lastWrittenRevision = Math.max(\n trans._lastWrittenRevision,\n rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n if (localStorage) localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n };\n}\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\nimport {createUUID} from '../utils';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: table.name,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n };\n}\n","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n };\n}\n","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n })\n .catch((e) => {\n console.log(obj)\n console.log(e.stack)\n })\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n };\n}\n","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(origFunc) {\n return function(stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function(tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function(tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\nexport default function Observable(db) {\n /// \n /// Extension to Dexie providing Syncronization capabilities to Dexie.\n /// \n /// \n\n var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n db.observable = {};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode.node = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\n\n db.close = override(db.close, function(origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function(origDelete) {\n return function() {\n return origDelete.apply(this, arguments).then(function(result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n \n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = (lastChange ? lastChange.rev : 0);\n mySyncNode.node = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function() {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db.transaction('rw', '_syncNodes', () => {\n return db._syncNodes\n .where('isMaster').equals(1)\n .first(currentMaster => {\n if (!currentMaster) {\n // There's no master. We must be the master\n mySyncNode.node.isMaster = 1;\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Master have been inactive for too long\n // Take over mastership\n mySyncNode.node.isMaster = 1;\n currentMaster.isMaster = 0;\n return db._syncNodes.put(currentMaster);\n }\n }).then(()=>{\n // Add our node to DB and start subscribing to events\n return db._syncNodes.add(mySyncNode.node).then(function() {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n });\n });\n }).then(function () {\n cleanup();\n });\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function() {\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(new Dexie.DatabaseClosedError());\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = (changes.length === LIMIT);\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n Dexie.vip(function() { // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n })\n .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted.\n // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function() {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function() {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n}\n\n//\n// Static properties and methods\n// \n\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n// Register addon:\nDexie.Observable = Observable;\nDexie.addons.push(Observable);\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n };\n}\n"]} \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/README.md b/addons/Dexie.Syncable/dist/README.md deleted file mode 100644 index 38706a48d..000000000 --- a/addons/Dexie.Syncable/dist/README.md +++ /dev/null @@ -1,37 +0,0 @@ -## Can't find dexie-syncable.js? -Transpiled code (dist version) IS ONLY checked in to -the [releases](https://github.com/dfahlander/Dexie.js/tree/releases/addons/Dexie.Syncable/dist). -branch. - -## Download -[unpkg.com/dexie-syncable/dist/dexie-syncable.js](https://unpkg.com/dexie-syncable/dist/dexie-syncable.js) - -[unpkg.com/dexie-syncable/dist/dexie-syncable.min.js](https://unpkg.com/dexie-syncable/dist/dexie-syncable.min.js) - -[unpkg.com/dexie-syncable/dist/dexie-syncable.js.map](https://unpkg.com/dexie-syncable/dist/dexie-syncable.js.map) - -[unpkg.com/dexie-syncable/dist/dexie-syncable.min.js.map](https://unpkg.com/dexie-syncable/dist/dexie-syncable.min.js.map) - -## npm -``` -npm install dexie-syncable --save -``` -## bower -Since Dexie v1.3.4, addons are included in the dexie bower package. -``` -$ bower install dexie --save -$ ls bower_components/dexie/addons/Dexie.Syncable/dist -dexie-syncable.js dexie-syncable.js.map dexie-syncable.min.js dexie-syncable.min.js.map - -``` -## Or build them yourself... -Fork Dexie.js, then: -``` -git clone https://github.com/YOUR-USERNAME/Dexie.js.git -cd Dexie.js -npm install -cd addons/Dexie.Syncable -npm run build # or npm run watch - -``` -If you're on windows, you need to use an elevated command prompt of some reason to get `npm install` to work. diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.d.ts b/addons/Dexie.Syncable/dist/dexie-syncable.d.ts new file mode 100644 index 000000000..d3909ce26 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.d.ts @@ -0,0 +1,105 @@ +// Type definitions for dexie-syncable v1.0.0-beta.4 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Syncable +// Definitions by: David Fahlander + +import Dexie from 'dexie'; +import 'dexie-observable'; +import { IDatabaseChange, ISyncProtocol, SyncStatus } from '../api'; + +// +// Extend Dexie interface +// +declare module 'dexie' { + interface Dexie { + syncable: { + /** + * Connect to given URL using given protocol and options. See documentation at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.connect() + */ + connect(protocol: string, url: string, options?: any): Dexie.Promise; + + /** + * Stop syncing with given url.. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.disconnect() + */ + disconnect(url: string): void; + + /** + * Stop syncing and delete all sync state for given URL. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.delete() + */ + delete(url: string): void; + + /** + * List remote URLs. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.list() + */ + list (): Dexie.Promise; + + /** + * Get sync status for given URL. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.getStatus() + */ + getStatus(url: string): Dexie.Promise; + + /** + * Syncable events. See docs at: + * https://github.com/dfahlander/Dexie.js/wiki/db.syncable.on('statusChanged') + */ + on: Dexie.Syncable.SyncableEventSet; + } + + /** + * Table used for storing uncommitted changes when downloading partial change sets from + * a sync server. + * + * Each change is bound to a node id (represents the remote server that the change was + * downloaded from) + */ + _uncommittedChanges: Dexie.Table; + } + + module Dexie { + + // Extend SyncNode interface from Dexie.Observable to + // allow storing remote nodes in table _syncNodes. + module Observable { + interface SyncNode { + url: string, // Only applicable for "remote" nodes. Only used in Dexie.Syncable. + syncProtocol: string, // Tells which implementation of ISyncProtocol to use for remote syncing. + syncContext: any, + syncOptions: any, + status: number, + appliedRemoteRevision: any, + remoteBaseRevisions: { local: number, remote: any }[], + dbUploadState: { + tablesToUpload: string[], + currentTable: string, + currentKey: any, + localBaseRevision: number + } + } + } + + var Syncable : { + (db: Dexie) : void; + /** + * See documentation at: + * https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.registerSyncProtocol() + */ + registerSyncProtocol: (name: string, prototocolInstance: ISyncProtocol) => void; + + /** Translates a sync status number into a string "ERROR_WILL_RETRY", "ERROR", etc */ + StatusTexts: {[syncStatus:number]: string}; + } + + module Syncable { + interface SyncableEventSet extends DexieEventSet { + (eventName: 'statusChanged', subscriber: (status: number, url: string) => void): void; + } + } + } +} + +export default Dexie.Syncable; + diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.es.js b/addons/Dexie.Syncable/dist/dexie-syncable.es.js new file mode 100644 index 000000000..fad097cb2 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.es.js @@ -0,0 +1,1198 @@ +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; +import 'dexie-observable'; + +var Promise$1 = Dexie.Promise; +function initSyncableConnect(db, connect) { + return function syncableConnect(protocolInstance, protocolName, url, options) { + if (db.isOpen()) { + // Database is open + if (!db._localSyncNode) + throw new Error("Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!"); + if (db._localSyncNode.isMaster) { + // We are master node + return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id); + } + else { + // We are not master node + // Request master node to do the connect: + return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) { + // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves. + return db.observable.sendMessage('connect', { + protocolName: protocolName, + url: url, + options: options + }, masterNode.id, { wantReply: true }); + }); + } + } + else if (db.hasBeenClosed()) { + // Database has been closed. + return Promise$1.reject(new Dexie.DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$1.reject(new Dexie.InvalidStateError("Dexie.Syncable: Cannot connect. Database has failed to open")); + } + else { + // Database not yet open. It may be on its way to open, or open() hasn't yet been called. + // Wait for it to open, then connect. + var promise = new Promise$1(function (resolve, reject) { + db.on("ready", function () { + // First, check if this is the very first time we connect to given URL. + // Need to know, because if it is, we should stall the promise returned to + // db.on('ready') to not be fulfilled until the initial sync has succeeded. + return db._syncNodes.get({ url: url }, function (node) { + // Ok, now we know whether we should await the connect promise or not. + // No matter, we should now connect (will maybe create the SyncNode instance + // representing the given URL) + var connectPromise = db.syncable.connect(protocolName, url, options); + connectPromise.then(resolve, reject); // Resolve the returned promise when connected. + // Ok, so let's see if we should suspend DB queries until connected or not: + if (node && node.appliedRemoteRevision) { + // The very first initial sync has been done so we need not wait + // for the connect promise to complete. It can continue in background. + // Returning here will resume db.on('ready') and resume all queries that + // the application has put to the database. + return; + } + // This was the very first time we connect to the remote server, + // we must make sure that the initial sync request succeeeds before resuming + // database queries that the application code puts onto the database. + // If OFFLINE or other error, don't allow the application to proceed. + // We are assuming that an initial sync is essential for the application to + // function correctly. + return connectPromise; + }); + }); + // Force open() to happen. Otherwise connect() may stall forever. + db.open().catch(function (ex) { + // If open fails, db.on('ready') may not have been called and we must + // reject promise with InvalidStateError + reject(new Dexie.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open", ex)); + }); + }); + return promise; + } + }; +} + +function initPersistedContext(node) { + // + // PersistedContext : IPersistedContext + // + return /** @class */ (function () { + function PersistedContext(nodeID, otherProps) { + this.nodeID = nodeID; + if (otherProps) + Dexie.extend(this, otherProps); + } + PersistedContext.prototype.save = function () { + // Store this instance in the syncContext property of the node it belongs to. + return Dexie.vip(function () { + return node.save(); + }); + }; + return PersistedContext; + }()); +} + +function initGetOrCreateSyncNode(db, protocolName, url) { + return function getOrCreateSyncNode(options) { + return db.transaction('rw', db._syncNodes, db._changes, function () { + if (!url) + throw new Error("Url cannot be empty"); + // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise. + return db._syncNodes.where("url").equalsIgnoreCase(url).first(function (node) { + // If we found a node it will be instanceof SyncNode as Dexie.Observable + // maps to class + if (node) { + var PersistedContext = initPersistedContext(node); + // Node already there. Make syncContext become an instance of PersistedContext: + node.syncContext = new PersistedContext(node.id, node.syncContext); + node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen... + node.syncOptions = options; // Options could have been changed + db._syncNodes.put(node); + } + else { + // Create new node and sync everything + node = new db.observable.SyncNode(); + node.myRevision = -1; + node.appliedRemoteRevision = null; + node.remoteBaseRevisions = []; + node.type = "remote"; + node.syncProtocol = protocolName; + node.url = url; + node.syncOptions = options; + node.lastHeartBeat = Date.now(); + node.dbUploadState = null; + var PersistedContext_1 = initPersistedContext(node); + Dexie.Promise.resolve(function () { + // If options.initialUpload is explicitely false, set myRevision to currentRevision. + if (options.initialUpload === false) + return db._changes.toCollection().lastKey(function (currentRevision) { + node.myRevision = currentRevision; + }); + }()).then(function () { + db._syncNodes.add(node).then(function (nodeID) { + node.syncContext = new PersistedContext_1(nodeID); // Update syncContext in db with correct nodeId. + db._syncNodes.put(node); + }); + }); + } + return node; // returning node will make the db.transaction()-promise resolve with this value. + }); + }); + }; +} + +function initEnqueue(db) { + return function enqueue(context, fn, instanceID) { + function _enqueue() { + if (!context.ongoingOperation) { + context.ongoingOperation = Dexie.ignoreTransaction(function () { + return Dexie.vip(function () { + return fn(); + }); + }).finally(function () { + delete context.ongoingOperation; + }); + } + else { + context.ongoingOperation = context.ongoingOperation.then(function () { + return enqueue(context, fn, instanceID); + }); + } + return context.ongoingOperation; + } + if (!instanceID) { + // Caller wants to enqueue it until database becomes open. + if (db.isOpen()) { + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + } + else if (db._localSyncNode && instanceID === db._localSyncNode.id) { + // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB) + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + }; +} + +function initSaveToUncommittedChanges(db, node) { + return function saveToUncommittedChanges(changes, remoteRevision) { + return db.transaction('rw!', db._uncommittedChanges, function () { + return db._uncommittedChanges.bulkAdd(changes.map(function (change) { + var changeWithNodeId = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) + changeWithNodeId.obj = change.obj; + if (change.mods) + changeWithNodeId.mods = change.mods; + return changeWithNodeId; + })); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + return node.save(); + }); + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function bulkUpdate(table, changes) { + var keys = changes.map(function (c) { return c.key; }); + var map = {}; + // Retrieve current object of each change to update and map each + // found object's primary key to the existing object: + return table.where(':id').anyOf(keys).raw().each(function (obj, cursor) { + map[cursor.primaryKey + ''] = obj; + }).then(function () { + // Filter away changes whose key wasn't found in the local database + // (we can't update them if we do not know the existing values) + var updatesThatApply = changes.filter(function (c) { return map.hasOwnProperty(c.key + ''); }); + // Apply modifications onto each existing object (in memory) + // and generate array of resulting objects to put using bulkPut(): + var objsToPut = updatesThatApply.map(function (c) { + var curr = map[c.key + '']; + Object.keys(c.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]); + }); + return curr; + }); + return table.bulkPut(objsToPut); + }); +} + +function initApplyChanges(db) { + return function applyChanges(changes) { + var collectedChanges = {}; + changes.forEach(function (change) { + if (!collectedChanges.hasOwnProperty(change.table)) { + collectedChanges[change.table] = (_a = {}, _a[CREATE] = [], _a[DELETE] = [], _a[UPDATE] = [], _a); + } + collectedChanges[change.table][change.type].push(change); + var _a; + }); + var table_names = Object.keys(collectedChanges); + var tables = table_names.map(function (table) { return db.table(table); }); + return db.transaction("rw", tables, function () { + table_names.forEach(function (table_name) { + var table = db.table(table_name); + var specifyKeys = !table.schema.primKey.keyPath; + var createChangesToApply = collectedChanges[table_name][CREATE]; + var deleteChangesToApply = collectedChanges[table_name][DELETE]; + var updateChangesToApply = collectedChanges[table_name][UPDATE]; + if (createChangesToApply.length > 0) + table.bulkPut(createChangesToApply.map(function (c) { return c.obj; }), specifyKeys ? + createChangesToApply.map(function (c) { return c.key; }) : undefined); + if (updateChangesToApply.length > 0) + bulkUpdate(table, updateChangesToApply); + if (deleteChangesToApply.length > 0) + table.bulkDelete(deleteChangesToApply.map(function (c) { return c.key; })); + }); + }); + }; +} + +function initFinallyCommitAllChanges(db, node) { + var applyChanges = initApplyChanges(db); + return function finallyCommitAllChanges(changes, remoteRevision) { + // 1. Open a write transaction on all tables in DB + var tablesToIncludeInTrans = db.tables.filter(function (table) { return table.name === '_changes' || + table.name === '_uncommittedChanges' || + table.schema.observable; }); + return db.transaction('rw!', tablesToIncludeInTrans, function () { + var trans = Dexie.currentTransaction; + var localRevisionBeforeChanges = 0; + return db._changes.orderBy('rev').last(function (lastChange) { + // Store what revision we were at before committing the changes + localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0; + }).then(function () { + // Specify the source. Important for the change consumer to ignore changes originated from self! + trans.source = node.id; + // 2. Apply uncommitted changes and delete each uncommitted change + return db._uncommittedChanges.where('node').equals(node.id).toArray(); + }).then(function (uncommittedChanges) { + return applyChanges(uncommittedChanges); + }).then(function () { + return db._uncommittedChanges.where('node').equals(node.id).delete(); + }).then(function () { + // 3. Apply last chunk of changes + return applyChanges(changes); + }).then(function () { + // Get what revision we are at now: + return db._changes.orderBy('rev').last(); + }).then(function (lastChange) { + var currentLocalRevision = (lastChange && lastChange.rev) || 0; + // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision) + node.appliedRemoteRevision = remoteRevision; + node.remoteBaseRevisions.push({ remote: remoteRevision, local: currentLocalRevision }); + if (node.myRevision === localRevisionBeforeChanges) { + // If server was up-to-date before we added new changes from the server, update myRevision to last change + // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from + // ever sending an empty change list to server, which would otherwise be done every second time it would send changes. + node.myRevision = currentLocalRevision; + } + // Garbage collect remoteBaseRevisions not in use anymore: + if (node.remoteBaseRevisions.length > 1) { + for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) { + if (node.myRevision >= node.remoteBaseRevisions[i].local) { + node.remoteBaseRevisions.splice(0, i); + break; + } + } + } + // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction. + node.save().catch(function (err) { + console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: " + (err.stack || err)); + }); + }); + }); + }; +} + +function getBaseRevisionAndMaxClientRevision(node) { + /// + if (node.remoteBaseRevisions.length === 0) + return { + // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision: + maxClientRevision: Infinity, + remoteBaseRevision: null + }; + for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) { + if (node.myRevision >= node.remoteBaseRevisions[i].local) { + // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on. + return { + maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local, + remoteBaseRevision: node.remoteBaseRevisions[i].remote + }; + } + } + // There are at least one item in the list but the server hasn't yet become up-to-date with the 0 revision from client. + return { + maxClientRevision: node.remoteBaseRevisions[0].local, + remoteBaseRevision: null + }; +} + +function combineCreateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered. + Object.keys(nextChange.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]); + }); + return clonedChange; +} + +function combineUpdateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered. + Object.keys(nextChange.mods).forEach(function (keyPath) { + // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath + var hadParentPath = false; + Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) { + Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]); + hadParentPath = true; + }); + if (!hadParentPath) { + // Add or replace this keyPath and its new value + clonedChange.mods[keyPath] = nextChange.mods[keyPath]; + } + // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since + // we must mimic what would happen if applying the two changes after each other: + Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) { + delete clonedChange.mods[subPath]; + }); + }); + return clonedChange; +} + +function mergeChange(prevChange, nextChange) { + switch (prevChange.type) { + case CREATE: + switch (nextChange.type) { + case CREATE: + return nextChange; // Another CREATE replaces previous CREATE. + case UPDATE: + return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj + case DELETE: + return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm! + } + break; + case UPDATE: + switch (nextChange.type) { + case CREATE: + return nextChange; // Another CREATE replaces previous update. + case UPDATE: + return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set. + case DELETE: + return nextChange; // Only send the delete change. What was updated earlier is no longer of interest. + } + break; + case DELETE: + switch (nextChange.type) { + case CREATE: + return nextChange; // A resurection occurred. Only create change is of interest. + case UPDATE: + return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there. + case DELETE: + return prevChange; // Still a delete change. Leave as is. + } + break; + } +} + +function initGetChangesSinceRevision(db, node, hasMoreToGive) { + return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) { + /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result. + var changeSet = {}; + var numChanges = 0; + var partial = false; + var ignoreSource = node.id; + var nextRevision = revision; + return db.transaction('r', db._changes, function () { + var query = db._changes.where('rev').between(revision, maxRevision, false, true); + return query.until(function () { + if (numChanges === maxChanges) { + partial = true; + return true; + } + }).each(function (change) { + // Note the revision in nextRevision: + nextRevision = change.rev; + // change.source is set based on currentTransaction.source + if (change.source === ignoreSource) + return; + // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info: + var changeToSend = { + type: change.type, + table: change.table, + key: change.key + }; + if (change.type === CREATE) + changeToSend.obj = change.obj; + else if (change.type === UPDATE) + changeToSend.mods = change.mods; + var id = change.table + ":" + change.key; + var prevChange = changeSet[id]; + if (!prevChange) { + // This is the first change on this key. Add it unless it comes from the source that we are working against + changeSet[id] = changeToSend; + ++numChanges; + } + else { + // Merge the oldchange with the new change + var nextChange = changeToSend; + var mergedChange = mergeChange(prevChange, nextChange); + changeSet[id] = mergedChange; + } + }); + }).then(function () { + var changes = Object.keys(changeSet).map(function (key) { + return changeSet[key]; + }); + hasMoreToGive.hasMoreToGive = partial; + return cb(changes, partial, { myRevision: nextRevision }); + }); + }; +} + +function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) { + return function getTableObjectsAsChanges(state, changes, collection) { + /// + /// + /// + var limitReached = false; + return collection.until(function () { + if (changes.length === MAX_CHANGES_PER_CHUNK) { + limitReached = true; + return true; + } + }).each(function (item, cursor) { + changes.push({ + type: CREATE, + table: state.currentTable, + key: cursor.key, + obj: cursor.value + }); + state.currentKey = cursor.key; + }).then(function () { + if (limitReached) { + // Limit reached. Send partial result. + hasMoreToGive.hasMoreToGive = true; + return cb(changes, null, true, { dbUploadState: state }); + } + else { + // Done iterating this table. Check if there are more tables to go through: + if (state.tablesToUpload.length === 0) { + // Done iterating all tables + // Now append changes occurred during our dbUpload: + var brmcr = getBaseRevisionAndMaxClientRevision(node); + return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) { + changes = changes.concat(additionalChanges); + nodeModificationsOnAck.dbUploadState = null; + return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck); + }); + } + else { + // Not done iterating all tables. Continue on next table: + state.currentTable = state.tablesToUpload.shift(); + return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id')); + } + } + }); + }; +} + +function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) { + var MAX_CHANGES_PER_CHUNK = partialsThreshold; + return function getLocalChangesForNode(node, cb) { + /// + /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes + /// for that node. + /// + /// + /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result. + var getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive); + var getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb); + // Only a "remote" SyncNode created by Dexie.Syncable + // could not pass this test (remote nodes have myRevision: -1 on instantiation) + if (node.myRevision >= 0) { + // Node is based on a revision in our local database and will just need to get the changes that have occurred since that revision. + var brmcr = getBaseRevisionAndMaxClientRevision(node); + return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) { + return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck); + }); + } + else { + // Node hasn't got anything from our local database yet. We will need to upload the entire DB to the node in the form of CREATE changes. + // Check if we're in the middle of already doing that: + if (node.dbUploadState === null) { + // Initialize dbUploadState + var tablesToUpload = db.tables.filter(function (table) { + return table.schema.observable; + }).map(function (table) { + return table.name; + }); + if (tablesToUpload.length === 0) + return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all. + var dbUploadState = { + tablesToUpload: tablesToUpload, + currentTable: tablesToUpload.shift(), + currentKey: null + }; + return db._changes.orderBy('rev').last(function (lastChange) { + dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0; + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(dbUploadState, [], collection); + }); + } + else if (node.dbUploadState.currentKey) { + var collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey); + return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection); + } + else { + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection); + } + } + }; +} + +var Statuses = { + ERROR: -1, + OFFLINE: 0, + CONNECTING: 1, + ONLINE: 2, + SYNCING: 3, + ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect. +}; +var StatusTexts = { + "-1": "ERROR", + "0": "OFFLINE", + "1": "CONNECTING", + "2": "ONLINE", + "3": "SYNCING", + "4": "ERROR_WILL_RETRY" +}; + +var Promise$2 = Dexie.Promise; +function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) { + var enqueue = initEnqueue(db); + var hasMoreToGive = { hasMoreToGive: true }; + function stillAlive() { + // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead + // because the new instance should be considered a fresh instance and will have another local node. + return db._localSyncNode && db._localSyncNode.id === dbAliveID; + } + return function connectProtocol(node, activePeer) { + /// + var getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold); + var url = activePeer.url; + function changeStatusTo(newStatus) { + if (node.status !== newStatus) { + node.status = newStatus; + node.save().then(function () { + db.syncable.on.statusChanged.fire(newStatus, url); + // Also broadcast message to other nodes about the status + db.observable.broadcastMessage("syncStatusChanged", { newStatus: newStatus, url: url }, false); + }).catch('DatabaseClosedError', function () { + }); + } + } + activePeer.on('disconnect', function (newStatus) { + if (!isNaN(newStatus)) + changeStatusTo(newStatus); + }); + var connectedContinuation; + changeStatusTo(Statuses.CONNECTING); + return doSync(); + function doSync() { + // Use enqueue() to ensure only a single promise execution at a time. + return enqueue(doSync, function () { + // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence. + return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider); + }, dbAliveID); + } + function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess(). + // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants. + var finalSyncPromise = new Promise$2(function (resolve, reject) { + rejectConnectPromise.p = function (err) { + reject(err); + }; + Dexie.asap(function () { + try { + protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, function (continuation) { + resolve(continuation); + }, onError); + } + catch (ex) { + onError(ex, Infinity); + } + function onError(error, again) { + reject(error); + if (stillAlive()) { + if (!isNaN(again) && again < Infinity) { + setTimeout(function () { + if (stillAlive()) { + changeStatusTo(Statuses.SYNCING); + doSync().catch('DatabaseClosedError', abortTheProvider); + } + }, again); + changeStatusTo(Statuses.ERROR_WILL_RETRY, error); + if (connectedContinuation && connectedContinuation.disconnect) + connectedContinuation.disconnect(); + connectedContinuation = null; + } + else { + abortTheProvider(error); // Will fire ERROR on statusChanged event. + } + } + } + }); + }); + return finalSyncPromise.then(function () { + // Resolve caller of db.syncable.connect() with undefined. Not with continuation! + return undefined; + }).finally(function () { + // In case error happens after connect, don't try reject the connect promise anymore. + // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon + // is active and this happens. It would fire unhandledrejection but that we do not want. + rejectConnectPromise.p = null; + }); + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately, + // otherwise it will execute when finalSyncPromise resolves. + finalSyncPromise.then(continueSendingChanges); + return node.save(); + } + } + function abortTheProvider(error) { + activePeer.disconnect(Statuses.ERROR, error); + } + function getLocalChangesForNode_autoAckIfEmpty(node, cb) { + return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save().catch('DatabaseClosedError', function () { + }); + return getLocalChangesForNode(node, autoAck); + } + else { + return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck); + } + }); + } + function applyRemoteChanges(remoteChanges, remoteRevision, partial /*, clear*/) { + var saveToUncommittedChanges = initSaveToUncommittedChanges(db, node); + var finallyCommitAllChanges = initFinallyCommitAllChanges(db, node); + return enqueue(applyRemoteChanges, function () { + if (!stillAlive()) + return Promise$2.reject(new Dexie.DatabaseClosedError()); + // FIXTHIS: Check what to do if clear() is true! + return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision)) + .catch(function (error) { + abortTheProvider(error); + return Promise$2.reject(error); + }); + }, dbAliveID); + } + // + // + // Continuation Patterns Follows + // + // + function continueSendingChanges(continuation) { + if (!stillAlive()) { + if (continuation.disconnect) + continuation.disconnect(); + return; + } + connectedContinuation = continuation; + activePeer.on('disconnect', function () { + if (connectedContinuation) { + if (connectedContinuation.react) { + try { + // react pattern must provide a disconnect function. + connectedContinuation.disconnect(); + } + catch (e) { + } + } + connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice. + } + }); + if (continuation.react) { + continueUsingReactPattern(continuation); + } + else { + continueUsingPollPattern(continuation); + } + } + // React Pattern (eager) + function continueUsingReactPattern(continuation) { + var changesWaiting, // Boolean + isWaitingForServer; // Boolean + function onChanges() { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + if (isWaitingForServer) + changesWaiting = true; + else { + reactToChanges(); + } + } + } + db.on('changes', onChanges); + activePeer.on('disconnect', function () { + db.on.changes.unsubscribe(onChanges); + }); + function reactToChanges() { + if (!connectedContinuation) + return; + changesWaiting = false; + isWaitingForServer = true; + getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + if (!connectedContinuation) + return; + if (changes.length > 0) { + continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save().catch('DatabaseClosedError', function () { + }); + // More changes may be waiting: + reactToChanges(); + }); + } + else { + isWaitingForServer = false; + if (changesWaiting) { + // A change jumped in between the time-spot of quering _changes and getting called back with zero changes. + // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory. + reactToChanges(); + } + else { + changeStatusTo(Statuses.ONLINE); + } + } + }).catch(function (ex) { + console.error("Got " + ex.message + " caught by reactToChanges"); + abortTheProvider(ex); + }); + } + reactToChanges(); + } + // Poll Pattern + function continueUsingPollPattern() { + function syncAgain() { + getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError); + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save().catch('DatabaseClosedError', function () { + }); + } + function onSuccess(continuation) { + if (!connectedContinuation) { + // Got disconnected before succeeding. Quit. + return; + } + connectedContinuation = continuation; + if (partial) { + // We only sent partial changes. Need to do another round asap. + syncAgain(); + } + else { + // We've sent all changes now (in sync!) + if (!isNaN(continuation.again) && continuation.again < Infinity) { + // Provider wants to keep polling. Set Status to ONLINE. + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, continuation.again); + } + else { + // Provider seems finished polling. Since we are never going to poll again, + // disconnect provider and set status to OFFLINE until another call to db.syncable.connect(). + activePeer.disconnect(Statuses.OFFLINE); + } + } + } + function onError(error, again) { + if (!isNaN(again) && again < Infinity) { + if (connectedContinuation) { + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, again); + changeStatusTo(Statuses.ERROR_WILL_RETRY); + } // else status is already changed since we got disconnected. + } + else { + abortTheProvider(error); // Will fire ERROR on onStatusChanged. + } + } + }).catch(abortTheProvider); + } + if (hasMoreToGive.hasMoreToGive) { + syncAgain(); + } + else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) { + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, connectedContinuation.again); + } + else { + // Provider seems finished polling. Since we are never going to poll again, + // disconnect provider and set status to OFFLINE until another call to db.syncable.connect(). + activePeer.disconnect(Statuses.OFFLINE); + } + } + }; +} + +function initConnectFn(db, activePeers) { + return function connect(protocolInstance, protocolName, url, options, dbAliveID) { + /// + var existingPeer = activePeers.filter(function (peer) { + return peer.url === url; + }); + if (existingPeer.length > 0) { + var activePeer = existingPeer[0]; + var diffObject = {}; + Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject); + // Options have been changed + // We need to disconnect and reconnect + if (Object.keys(diffObject).length !== 0) { + return db.syncable.disconnect(url) + .then(function () { + return execConnect(); + }); + } + else { + // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that + // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly. + return existingPeer[0].connectPromise; + } + } + function execConnect() { + // Use an object otherwise we wouldn't be able to get the reject promise from + // connectProtocol + var rejectConnectPromise = { p: null }; + var connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise); + var getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url); + var connectPromise = getOrCreateSyncNode(options).then(function (node) { + return connectProtocol(node, activePeer); + }); + var disconnected = false; + var activePeer = { + url: url, + status: Statuses.OFFLINE, + connectPromise: connectPromise, + syncOptions: options, + on: Dexie.Events(null, "disconnect"), + disconnect: function (newStatus, error) { + var pos = activePeers.indexOf(activePeer); + if (pos >= 0) + activePeers.splice(pos, 1); + if (error && rejectConnectPromise.p) + rejectConnectPromise.p(error); + if (!disconnected) { + activePeer.on.disconnect.fire(newStatus, error); + } + disconnected = true; + } + }; + activePeers.push(activePeer); + return connectPromise; + } + return execConnect(); + }; +} + +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +// Depend on 'dexie-observable' +// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as "Dexie.Observable". +// That way, our plugin works in all UMD cases. +// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from "dexie-observable"'. +var override = Dexie.override; +var Promise = Dexie.Promise; +var Observable = Dexie.Observable; +function Syncable(db) { + /// + var activePeers = []; + var connectFn = initConnectFn(db, activePeers); + var syncableConnect = initSyncableConnect(db, connectFn); + db.on('message', function (msg) { + // Message from other local node arrives... + Dexie.vip(function () { + if (msg.type === 'connect') { + // We are master node and another non-master node wants us to do the connect. + db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject); + } + else if (msg.type === 'disconnect') { + db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject); + } + else if (msg.type === 'syncStatusChanged') { + // We are client and a master node informs us about syncStatus change. + // Lookup the connectedProvider and call its event + db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url); + } + }); + }); + db.on('cleanup', function (weBecameMaster) { + // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master. + if (weBecameMaster) { + // We took over the master role in Observable's cleanup method. + // We should connect to remote servers now. + // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR. + // Reason to reconnect to those with plain "ERROR" is that the ERROR state may occur when a database + // connection has been closed. The new master would then be expected to reconnect. + // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from + // an old closed one. + Dexie.ignoreTransaction(function () { return Dexie.vip(function () { + return db._syncNodes.where({ type: 'remote' }) + .filter(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { return Promise.all(connectedRemoteNodes.map(function (node) { + return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (e) { + console.warn("Dexie.Syncable: Could not connect to " + node.url + ". " + (e.stack || e)); + }); + })); }); + }); }).catch('DatabaseClosedError', function () { }); + } + }); + // "ready" subscriber for the master node that makes sure it will always connect to sync server + // when the database opens. It will not wait for the connection to complete, just initiate the + // connection so that it will continue syncing as long as the database is open. + // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure + // that db._localSyncNode exists and persisted before this subscriber kicks in. + db.on('ready', function onReady() { + // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state. + if (db._localSyncNode && db._localSyncNode.isMaster) { + // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!) + // This "ready" subscriber will never be the one performing the initial sync request, because + // even after calling db.syncable.connect(), there won't exist any "remote" sync node yet. + // Instead, db.syncable.connect() will subscribe to "ready" also, and that subscriber will be + // called after this one. There, in that subscriber, the initial sync request will take place + // and the "remote" node will be created so that this "ready" subscriber can auto-connect the + // next time this database is opened. + // CONCLUSION: We can always assume that the local DB has been in sync with the server at least + // once in the past for each "connectedRemoteNode" we find in query below. + // Don't halt db.ready while connecting (i.e. we do not return a promise here!) + db._syncNodes + .where('type').equals('remote') + .and(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { + // There are connected remote nodes that we must manage (or take over to manage) + connectedRemoteNodes.forEach(function (node) { return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions) + .catch(function () { }); } // A failure will be triggered in on('statusChanged'). We can ignore. + ); + }).catch('DatabaseClosedError', function () { }); + } + }, true); // True means the ready event will survive a db reopen - db.close()/db.open() + db.syncable = {}; + db.syncable.getStatus = function (url, cb) { + if (db.isOpen()) { + return Dexie.vip(function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node ? node.status : Statuses.OFFLINE; + }); + }).then(cb); + } + else { + return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb); + } + }; + db.syncable.getOptions = function (url, cb) { + return db.transaction('r?', db._syncNodes, function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node.syncOptions; + }).then(cb); + }); + }; + db.syncable.list = function () { + return db.transaction('r?', db._syncNodes, function () { + return db._syncNodes.where('type').equals('remote').toArray(function (a) { + return a.map(function (node) { return node.url; }); + }); + }); + }; + db.syncable.on = Dexie.Events(db, { statusChanged: "asap" }); + db.syncable.disconnect = function (url) { + return Dexie.ignoreTransaction(function () { + return Promise.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise.all(activePeers.filter(function (peer) { return peer.url === url; }).map(function (peer) { + return peer.disconnect(Statuses.OFFLINE); + })); + } + else { + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true }); + }); + } + }).then(function () { + return db._syncNodes.where("url").equals(url).modify(function (node) { + node.status = Statuses.OFFLINE; + }); + }); + }); + }; + db.syncable.connect = function (protocolName, url, options) { + options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined. + var protocolInstance = Syncable.registeredProtocols[protocolName]; + if (protocolInstance) { + return syncableConnect(protocolInstance, protocolName, url, options); + } + else { + return Promise.reject(new Error("ISyncProtocol '" + protocolName + "' is not registered in Dexie.Syncable.registerSyncProtocol()")); + } + }; + db.syncable.delete = function (url) { + return db.syncable.disconnect(url).then(function () { + return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, function () { + // Find the node(s) + // Several can be found, as detected by @martindiphoorn, + // let's delete them and cleanup _uncommittedChanges and _changes + // accordingly. + var nodeIDsToDelete; + return db._syncNodes + .where("url").equals(url) + .toArray(function (nodes) { return nodes.map(function (node) { return node.id; }); }) + .then(function (nodeIDs) { + nodeIDsToDelete = nodeIDs; + // Delete the syncNode that represents the remote endpoint. + return db._syncNodes.where('id').anyOf(nodeIDs).delete(); + }) + .then(function () { + // In case there were uncommittedChanges belonging to this, delete them as well + return db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete(); + }); + }).then(function () { + // Spawn background job to delete old changes, now that a node has been deleted, + // there might be changes in _changes table that is not needed to keep anymore. + // This is done in its own transaction, or possible several transaction to prohibit + // starvation + Observable.deleteOldChanges(db); + }); + }); + }; + db.syncable.unsyncedChanges = function (url) { + return db._syncNodes.where("url").equals(url).first(function (node) { + return db._changes.where('rev').above(node.myRevision).toArray(); + }); + }; + db.close = override(db.close, function (origClose) { + return function () { + activePeers.forEach(function (peer) { + peer.disconnect(); + }); + return origClose.apply(this, arguments); + }; + }); + Object.defineProperty(db.observable.SyncNode.prototype, 'save', { + enumerable: false, + configurable: true, + writable: true, + value: function () { + var _this = this; + return db.transaction('rw?', db._syncNodes, function () { + return db._syncNodes.put(_this); + }); + } + }); +} +Syncable.Statuses = Statuses; +Syncable.StatusTexts = StatusTexts; +Syncable.registeredProtocols = {}; // Map when key is the provider name. +Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a synchronization protocol that can synchronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + var partialsThreshold = protocolInstance.partialsThreshold; + if (typeof partialsThreshold === 'number') { + // Don't allow NaN or negative threshold + if (isNaN(partialsThreshold) || partialsThreshold < 0) { + throw new Error('The given number for the threshold is not supported'); + } + // If the threshold is 0 we will not send any client changes but will get server changes + } + else { + // Use Infinity as the default so simple protocols don't have to care about partial synchronization + protocolInstance.partialsThreshold = Infinity; + } + Syncable.registeredProtocols[name] = protocolInstance; +}; +// Register addon in Dexie: +Dexie.Syncable = Syncable; +Dexie.addons.push(Syncable); + +export default Syncable; +//# sourceMappingURL=dexie-syncable.es.js.map diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.es.js.map b/addons/Dexie.Syncable/dist/dexie-syncable.es.js.map new file mode 100644 index 000000000..b055fb8c7 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-syncable.es.js","sources":["../src/syncable-connect.js","../src/PersistedContext.js","../src/get-or-create-sync-node.js","../src/enqueue.js","../src/save-to-uncommitted-changes.js","../src/change_types.js","../src/bulk-update.js","../src/apply-changes.js","../src/finally-commit-all-changes.js","../src/get-local-changes-for-node/get-base-revision-and-max-client-revision.js","../src/combine-create-and-update.js","../src/combine-update-and-update.js","../src/merge-change.js","../src/get-local-changes-for-node/get-changes-since-revision.js","../src/get-local-changes-for-node/get-table-objects-as-changes.js","../src/get-local-changes-for-node/get-local-changes-for-node.js","../src/statuses.js","../src/connect-protocol.js","../src/connect-fn.js","../src/Dexie.Syncable.js"],"sourcesContent":["import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initSyncableConnect(db, connect) {\n return function syncableConnect(protocolInstance, protocolName, url, options) {\n if (db.isOpen()) {\n // Database is open\n if (!db._localSyncNode)\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\n\n if (db._localSyncNode.isMaster) {\n // We are master node\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\n } else {\n // We are not master node\n // Request master node to do the connect:\n return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\n // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves.\n return db.observable.sendMessage('connect', {\n protocolName: protocolName,\n url: url,\n options: options\n }, masterNode.id, {wantReply: true});\n });\n }\n } else if (db.hasBeenClosed()) {\n // Database has been closed.\n return Promise.reject(new Dexie.DatabaseClosedError());\n } else if (db.hasFailed()) {\n // Database has failed to open\n return Promise.reject(new Dexie.InvalidStateError(\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\n } else {\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\n // Wait for it to open, then connect.\n var promise = new Promise(function (resolve, reject) {\n db.on(\"ready\", () => {\n // First, check if this is the very first time we connect to given URL.\n // Need to know, because if it is, we should stall the promise returned to\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\n return db._syncNodes.get({url}, node => {\n // Ok, now we know whether we should await the connect promise or not.\n // No matter, we should now connect (will maybe create the SyncNode instance\n // representing the given URL)\n let connectPromise = db.syncable.connect(protocolName, url, options);\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\n // Ok, so let's see if we should suspend DB queries until connected or not:\n if (node && node.appliedRemoteRevision) {\n // The very first initial sync has been done so we need not wait\n // for the connect promise to complete. It can continue in background.\n // Returning here will resume db.on('ready') and resume all queries that\n // the application has put to the database.\n return;\n }\n // This was the very first time we connect to the remote server,\n // we must make sure that the initial sync request succeeeds before resuming\n // database queries that the application code puts onto the database.\n // If OFFLINE or other error, don't allow the application to proceed.\n // We are assuming that an initial sync is essential for the application to\n // function correctly.\n return connectPromise;\n });\n });\n // Force open() to happen. Otherwise connect() may stall forever.\n db.open().catch(ex => {\n // If open fails, db.on('ready') may not have been called and we must\n // reject promise with InvalidStateError\n reject(new Dexie.InvalidStateError(\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\n ex\n ));\n });\n });\n return promise;\n }\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initPersistedContext(node) {\n //\n // PersistedContext : IPersistedContext\n //\n return class PersistedContext {\n constructor(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n save() {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(() => {\n return node.save();\n });\n }\n }\n}\n","import Dexie from 'dexie';\n\nimport initPersistedContext from './PersistedContext';\n\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\n return function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, db._changes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\n // maps to class\n if (node) {\n const PersistedContext = initPersistedContext(node);\n // Node already there. Make syncContext become an instance of PersistedContext:\n node.syncContext = new PersistedContext(node.id, node.syncContext);\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\n node.syncOptions = options; // Options could have been changed\n db._syncNodes.put(node);\n } else {\n // Create new node and sync everything\n node = new db.observable.SyncNode();\n node.myRevision = -1;\n node.appliedRemoteRevision = null;\n node.remoteBaseRevisions = [];\n node.type = \"remote\";\n node.syncProtocol = protocolName;\n node.url = url;\n node.syncOptions = options;\n node.lastHeartBeat = Date.now();\n node.dbUploadState = null;\n const PersistedContext = initPersistedContext(node);\n Dexie.Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false)\n return db._changes.toCollection().lastKey(function (currentRevision) {\n node.myRevision = currentRevision;\n });\n }()).then(function () {\n db._syncNodes.add(node).then(function (nodeID) {\n node.syncContext = new PersistedContext(nodeID); // Update syncContext in db with correct nodeId.\n db._syncNodes.put(node);\n });\n });\n }\n\n return node; // returning node will make the db.transaction()-promise resolve with this value.\n });\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initEnqueue(db) {\n return function enqueue(context, fn, instanceID) {\n function _enqueue() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).finally(()=> {\n delete context.ongoingOperation;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enqueue(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enqueue it until database becomes open.\n if (db.isOpen()) {\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB)\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n };\n}\n","export default function initSaveToUncommittedChanges(db, node) {\n return function saveToUncommittedChanges(changes, remoteRevision) {\n return db.transaction('rw!', db._uncommittedChanges, () => {\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\n let changeWithNodeId = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeWithNodeId.obj = change.obj;\n if (change.mods) changeWithNodeId.mods = change.mods;\n return changeWithNodeId;\n }));\n }).then(() => {\n node.appliedRemoteRevision = remoteRevision;\n return node.save();\n });\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nexport default function bulkUpdate(table, changes) {\n let keys = changes.map(c => c.key);\n let map = {};\n // Retrieve current object of each change to update and map each\n // found object's primary key to the existing object:\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\n map[cursor.primaryKey+''] = obj;\n }).then(()=>{\n // Filter away changes whose key wasn't found in the local database\n // (we can't update them if we do not know the existing values)\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\n // Apply modifications onto each existing object (in memory)\n // and generate array of resulting objects to put using bulkPut():\n let objsToPut = updatesThatApply.map (c => {\n let curr = map[c.key+''];\n Object.keys(c.mods).forEach(keyPath => {\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\n });\n return curr;\n });\n return table.bulkPut(objsToPut);\n });\n}\n","import Dexie from 'dexie';\nimport { CREATE, DELETE, UPDATE } from './change_types';\nimport bulkUpdate from './bulk-update';\n\nexport default function initApplyChanges(db) {\n return function applyChanges(changes) {\n let collectedChanges = {};\n changes.forEach((change) => {\n if (!collectedChanges.hasOwnProperty(change.table)) {\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\n }\n collectedChanges[change.table][change.type].push(change);\n });\n let table_names = Object.keys(collectedChanges);\n let tables = table_names.map((table) => db.table(table));\n\n return db.transaction(\"rw\", tables, () => {\n table_names.forEach((table_name) => {\n const table = db.table(table_name);\n const specifyKeys = !table.schema.primKey.keyPath;\n const createChangesToApply = collectedChanges[table_name][CREATE];\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\n if (createChangesToApply.length > 0)\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\n createChangesToApply.map(c => c.key) : undefined);\n if (updateChangesToApply.length > 0)\n bulkUpdate(table, updateChangesToApply);\n if (deleteChangesToApply.length > 0)\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\n });\n });\n };\n}\n","import Dexie from 'dexie';\nimport initApplyChanges from './apply-changes';\n\nexport default function initFinallyCommitAllChanges(db, node) {\n const applyChanges = initApplyChanges(db);\n\n return function finallyCommitAllChanges(changes, remoteRevision) {\n // 1. Open a write transaction on all tables in DB\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\n table.name === '_uncommittedChanges' ||\n table.schema.observable);\n\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n return db._changes.orderBy('rev').last(function (lastChange) {\n // Store what revision we were at before committing the changes\n localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0;\n }).then(() => {\n // Specify the source. Important for the change consumer to ignore changes originated from self!\n trans.source = node.id;\n // 2. Apply uncommitted changes and delete each uncommitted change\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\n }).then(function (uncommittedChanges) {\n return applyChanges(uncommittedChanges);\n }).then(function () {\n return db._uncommittedChanges.where('node').equals(node.id).delete();\n }).then(function () {\n // 3. Apply last chunk of changes\n return applyChanges(changes);\n }).then(function () {\n // Get what revision we are at now:\n return db._changes.orderBy('rev').last();\n }).then(function (lastChange) {\n var currentLocalRevision = (lastChange && lastChange.rev) || 0;\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\n node.appliedRemoteRevision = remoteRevision;\n node.remoteBaseRevisions.push({remote: remoteRevision, local: currentLocalRevision});\n if (node.myRevision === localRevisionBeforeChanges) {\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\n node.myRevision = currentLocalRevision;\n }\n // Garbage collect remoteBaseRevisions not in use anymore:\n if (node.remoteBaseRevisions.length > 1) {\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n node.remoteBaseRevisions.splice(0, i);\n break;\n }\n }\n }\n // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n node.save().catch(err=> {\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\n });\n });\n });\n };\n}\n","export default function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0)\n return {\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\n maxClientRevision: Infinity,\n remoteBaseRevision: null\n };\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\n return {\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\n };\n }\n }\n // There are at least one item in the list but the server hasn't yet become up-to-date with the 0 revision from client.\n return {\n maxClientRevision: node.remoteBaseRevisions[0].local,\n remoteBaseRevision: null\n };\n}\n","import Dexie from 'dexie';\n\nexport default function combineCreateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n}\n","import Dexie from 'dexie';\n\nexport default function combineUpdateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\n var hadParentPath = false;\n Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\n Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\n hadParentPath = true;\n });\n if (!hadParentPath) {\n // Add or replace this keyPath and its new value\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\n }\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\n // we must mimic what would happen if applying the two changes after each other:\n Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\n delete clonedChange.mods[subPath];\n });\n });\n return clonedChange;\n}\n","import { CREATE, UPDATE, DELETE } from './change_types';\nimport combineCreateAndUpdate from './combine-create-and-update.js';\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\n\nexport default function mergeChange(prevChange, nextChange) {\n switch (prevChange.type) {\n case CREATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous CREATE.\n case UPDATE:\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\n case DELETE:\n return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm!\n }\n break;\n case UPDATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous update.\n case UPDATE:\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\n case DELETE:\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\n }\n break;\n case DELETE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // A resurection occurred. Only create change is of interest.\n case UPDATE:\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\n case DELETE:\n return prevChange; // Still a delete change. Leave as is.\n }\n break;\n }\n}\n","import {CREATE, UPDATE} from '../change_types';\nimport mergeChange from '../merge-change';\n\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\n return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n var changeSet = {};\n var numChanges = 0;\n var partial = false;\n var ignoreSource = node.id;\n var nextRevision = revision;\n return db.transaction('r', db._changes, function () {\n var query = db._changes.where('rev').between(revision, maxRevision, false, true);\n return query.until(() => {\n if (numChanges === maxChanges) {\n partial = true;\n return true;\n }\n }).each(function (change) {\n // Note the revision in nextRevision:\n nextRevision = change.rev;\n // change.source is set based on currentTransaction.source\n if (change.source === ignoreSource) return;\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE)\n changeToSend.obj = change.obj;\n else if (change.type === UPDATE)\n changeToSend.mods = change.mods;\n\n var id = change.table + \":\" + change.key;\n var prevChange = changeSet[id];\n if (!prevChange) {\n // This is the first change on this key. Add it unless it comes from the source that we are working against\n changeSet[id] = changeToSend;\n ++numChanges;\n } else {\n // Merge the oldchange with the new change\n var nextChange = changeToSend;\n var mergedChange = mergeChange(prevChange, nextChange);\n changeSet[id] = mergedChange;\n }\n });\n }).then(function () {\n var changes = Object.keys(changeSet).map(function (key) {\n return changeSet[key];\n });\n hasMoreToGive.hasMoreToGive = partial;\n return cb(changes, partial, {myRevision: nextRevision});\n });\n };\n}\n","import {CREATE} from '../change_types';\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\n\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\n return function getTableObjectsAsChanges(state, changes, collection) {\n /// \n /// \n /// \n var limitReached = false;\n return collection.until(function () {\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\n limitReached = true;\n return true;\n }\n }).each(function (item, cursor) {\n changes.push({\n type: CREATE,\n table: state.currentTable,\n key: cursor.key,\n obj: cursor.value\n });\n state.currentKey = cursor.key;\n }).then(function () {\n if (limitReached) {\n // Limit reached. Send partial result.\n hasMoreToGive.hasMoreToGive = true;\n return cb(changes, null, true, {dbUploadState: state});\n } else {\n // Done iterating this table. Check if there are more tables to go through:\n if (state.tablesToUpload.length === 0) {\n // Done iterating all tables\n // Now append changes occurred during our dbUpload:\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\n changes = changes.concat(additionalChanges);\n nodeModificationsOnAck.dbUploadState = null;\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Not done iterating all tables. Continue on next table:\n state.currentTable = state.tablesToUpload.shift();\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\n }\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\nimport initGetChangesSinceRevision from './get-changes-since-revision';\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\n\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\n\n return function getLocalChangesForNode(node, cb) {\n /// \n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\n /// for that node.\n /// \n /// \n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n\n const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\n\n // Only a \"remote\" SyncNode created by Dexie.Syncable\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\n if (node.myRevision >= 0) {\n // Node is based on a revision in our local database and will just need to get the changes that have occurred since that revision.\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Node hasn't got anything from our local database yet. We will need to upload the entire DB to the node in the form of CREATE changes.\n // Check if we're in the middle of already doing that:\n if (node.dbUploadState === null) {\n // Initialize dbUploadState\n var tablesToUpload = db.tables.filter(function (table) {\n return table.schema.observable;\n }).map(function (table) {\n return table.name;\n });\n if (tablesToUpload.length === 0) return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all.\n var dbUploadState = {\n tablesToUpload: tablesToUpload,\n currentTable: tablesToUpload.shift(),\n currentKey: null\n };\n return db._changes.orderBy('rev').last(function (lastChange) {\n dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0;\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(dbUploadState, [], collection);\n });\n } else if (node.dbUploadState.currentKey) {\n const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n };\n}\n","export const Statuses = {\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasn't yet become online, or it has been disconnected.\n CONNECTING: 1, // Trying to connect to server\n ONLINE: 2, // Connected to server and currently in sync with server\n SYNCING: 3, // Syncing with server. For poll pattern, this is every poll call. For react pattern, this is when local changes are being sent to server.\n ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect.\n};\n\nexport const StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n","import Dexie from 'dexie';\n\nimport initEnqueue from './enqueue';\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\nimport {Statuses} from './statuses';\n\nconst Promise = Dexie.Promise;\n\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\n const enqueue = initEnqueue(db);\n var hasMoreToGive = {hasMoreToGive: true};\n\n function stillAlive() {\n // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead\n // because the new instance should be considered a fresh instance and will have another local node.\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\n }\n\n return function connectProtocol(node, activePeer) {\n /// \n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\n\n const url = activePeer.url;\n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save().then(()=> {\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\n }).catch('DatabaseClosedError', ()=> {\n });\n }\n }\n\n activePeer.on('disconnect', function (newStatus) {\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\n });\n\n var connectedContinuation;\n changeStatusTo(Statuses.CONNECTING);\n return doSync();\n\n function doSync() {\n // Use enqueue() to ensure only a single promise execution at a time.\n return enqueue(doSync, function () {\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\n return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider);\n }, dbAliveID);\n }\n\n function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\n var finalSyncPromise = new Promise(function (resolve, reject) {\n rejectConnectPromise.p = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(\n node.syncContext,\n url,\n options,\n remoteBaseRevision,\n node.appliedRemoteRevision,\n changes,\n partial,\n applyRemoteChanges,\n onChangesAccepted,\n function (continuation) {\n resolve(continuation);\n },\n onError);\n } catch (ex) {\n onError(ex, Infinity);\n }\n\n function onError(error, again) {\n reject(error);\n if (stillAlive()) {\n if (!isNaN(again) && again < Infinity) {\n setTimeout(function () {\n if (stillAlive()) {\n changeStatusTo(Statuses.SYNCING);\n doSync().catch('DatabaseClosedError', abortTheProvider);\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\n connectedContinuation = null;\n } else {\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\n }\n }\n }\n });\n });\n\n return finalSyncPromise.then(function () {\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\n return undefined;\n }).finally(()=> {\n // In case error happens after connect, don't try reject the connect promise anymore.\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\n // is active and this happens. It would fire unhandledrejection but that we do not want.\n rejectConnectPromise.p = null;\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\n // otherwise it will execute when finalSyncPromise resolves.\n finalSyncPromise.then(continueSendingChanges);\n return node.save();\n }\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\n }\n\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\n\n return enqueue(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\n .catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) { // Database was closed.\n if (continuation.disconnect)\n continuation.disconnect();\n return;\n }\n\n connectedContinuation = continuation;\n activePeer.on('disconnect', function () {\n if (connectedContinuation) {\n if (connectedContinuation.react) {\n try {\n // react pattern must provide a disconnect function.\n connectedContinuation.disconnect();\n } catch (e) {\n }\n }\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\n }\n });\n\n if (continuation.react) {\n continueUsingReactPattern(continuation);\n } else {\n continueUsingPollPattern(continuation);\n }\n }\n\n // React Pattern (eager)\n function continueUsingReactPattern(continuation) {\n var changesWaiting, // Boolean\n isWaitingForServer; // Boolean\n\n\n function onChanges() {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n if (isWaitingForServer)\n changesWaiting = true;\n else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\n activePeer.on('disconnect', function () {\n db.on.changes.unsubscribe(onChanges);\n });\n\n function reactToChanges() {\n if (!connectedContinuation) return;\n changesWaiting = false;\n isWaitingForServer = true;\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (!connectedContinuation) return;\n if (changes.length > 0) {\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n // More changes may be waiting:\n reactToChanges();\n });\n } else {\n isWaitingForServer = false;\n if (changesWaiting) {\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\n reactToChanges();\n } else {\n changeStatusTo(Statuses.ONLINE);\n }\n }\n }).catch(ex => {\n console.error(`Got ${ex.message} caught by reactToChanges`);\n abortTheProvider(ex);\n });\n }\n\n reactToChanges();\n }\n\n // Poll Pattern\n function continueUsingPollPattern() {\n\n function syncAgain() {\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n }\n\n function onSuccess(continuation) {\n if (!connectedContinuation) {\n // Got disconnected before succeeding. Quit.\n return;\n }\n connectedContinuation = continuation;\n if (partial) {\n // We only sent partial changes. Need to do another round asap.\n syncAgain();\n } else {\n // We've sent all changes now (in sync!)\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\n // Provider wants to keep polling. Set Status to ONLINE.\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, continuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n }\n\n function onError(error, again) {\n if (!isNaN(again) && again < Infinity) {\n if (connectedContinuation) {\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\n } // else status is already changed since we got disconnected.\n } else {\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\n }\n }\n }).catch(abortTheProvider);\n }\n\n if (hasMoreToGive.hasMoreToGive) {\n syncAgain();\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, connectedContinuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n };\n}\n","import Dexie from 'dexie';\n\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\nimport initConnectProtocol from './connect-protocol';\nimport {Statuses} from './statuses';\n\nexport default function initConnectFn(db, activePeers) {\n return function connect(protocolInstance, protocolName, url, options, dbAliveID) {\n /// \n var existingPeer = activePeers.filter(function (peer) {\n return peer.url === url;\n });\n if (existingPeer.length > 0) {\n const activePeer = existingPeer[0];\n const diffObject = {};\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\n // Options have been changed\n // We need to disconnect and reconnect\n if (Object.keys(diffObject).length !== 0) {\n return db.syncable.disconnect(url)\n .then(() => {\n return execConnect();\n })\n } else {\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\n // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly.\n return existingPeer[0].connectPromise;\n }\n }\n\n function execConnect() {\n // Use an object otherwise we wouldn't be able to get the reject promise from\n // connectProtocol\n var rejectConnectPromise = {p: null};\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node, activePeer);\n });\n\n var disconnected = false;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n syncOptions: options,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n }\n\n return execConnect();\n };\n}\n","/* ========================================================================== \n * dexie-syncable.js\n * ==========================================================================\n *\n * Dexie addon for syncing indexedDB with remote endpoints.\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\n\nimport Dexie from \"dexie\";\n// Depend on 'dexie-observable'\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\n// That way, our plugin works in all UMD cases.\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\nimport \"dexie-observable\";\n\nimport initSyncableConnect from './syncable-connect';\nimport initConnectFn from './connect-fn';\nimport {Statuses, StatusTexts} from './statuses';\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n Observable = Dexie.Observable;\n\nexport default function Syncable (db) {\n /// \n\n var activePeers = [];\n\n const connectFn = initConnectFn(db, activePeers);\n const syncableConnect = initSyncableConnect(db, connectFn);\n\n db.on('message', function(msg) {\n // Message from other local node arrives...\n Dexie.vip(function() {\n if (msg.type === 'connect') {\n // We are master node and another non-master node wants us to do the connect.\n db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject);\n } else if (msg.type === 'syncStatusChanged') {\n // We are client and a master node informs us about syncStatus change.\n // Lookup the connectedProvider and call its event\n db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url);\n }\n });\n });\n\n db.on('cleanup', function(weBecameMaster) {\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\n if (weBecameMaster) {\n // We took over the master role in Observable's cleanup method.\n // We should connect to remote servers now.\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\n // connection has been closed. The new master would then be expected to reconnect.\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\n // an old closed one. \n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\n return db._syncNodes.where({type: 'remote'})\n .filter(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\n })\n )));\n })).catch('DatabaseClosedError', ()=>{});\n }\n });\n\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\n // when the database opens. It will not wait for the connection to complete, just initiate the\n // connection so that it will continue syncing as long as the database is open.\n\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\n db.on('ready', function onReady() {\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\n // This \"ready\" subscriber will never be the one performing the initial sync request, because\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\n // called after this one. There, in that subscriber, the initial sync request will take place\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\n // next time this database is opened.\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\n // once in the past for each \"connectedRemoteNode\" we find in query below.\n\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\n db._syncNodes\n .where('type').equals('remote')\n .and(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => {\n // There are connected remote nodes that we must manage (or take over to manage)\n connectedRemoteNodes.forEach(\n node => db.syncable.connect(\n node.syncProtocol,\n node.url,\n node.syncOptions) \n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\n );\n }).catch('DatabaseClosedError', ()=>{});\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\n\n db.syncable = {};\n\n db.syncable.getStatus = function(url, cb) {\n if (db.isOpen()) {\n return Dexie.vip(function() {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node ? node.status : Statuses.OFFLINE;\n });\n }).then(cb);\n } else {\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\n }\n };\n\n db.syncable.getOptions = function(url, cb) {\n return db.transaction('r?', db._syncNodes, () => {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node.syncOptions;\n }).then(cb);\n });\n };\n\n db.syncable.list = function() {\n return db.transaction('r?', db._syncNodes, ()=>{\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\n return a.map(function(node) { return node.url; });\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function(url) {\n return Dexie.ignoreTransaction(()=>{\n return Promise.resolve().then(()=>{\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\n return peer.disconnect(Statuses.OFFLINE);\n }));\n } else {\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\n });\n }\n }).then(()=>{\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\n node.status = Statuses.OFFLINE;\n });\n });\n });\n };\n\n db.syncable.connect = function(protocolName, url, options) {\n options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined.\n var protocolInstance = Syncable.registeredProtocols[protocolName];\n if (protocolInstance) {\n return syncableConnect(protocolInstance, protocolName, url, options);\n } else {\n return Promise.reject(\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\n );\n }\n };\n\n db.syncable.delete = function(url) {\n return db.syncable.disconnect(url).then(()=>{\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\n // Find the node(s)\n // Several can be found, as detected by @martindiphoorn,\n // let's delete them and cleanup _uncommittedChanges and _changes \n // accordingly.\n let nodeIDsToDelete;\n return db._syncNodes\n .where(\"url\").equals(url)\n .toArray(nodes => nodes.map(node => node.id))\n .then(nodeIDs => {\n nodeIDsToDelete = nodeIDs;\n // Delete the syncNode that represents the remote endpoint.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\n })\n .then (() =>\n // In case there were uncommittedChanges belonging to this, delete them as well\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\n }).then(()=> {\n // Spawn background job to delete old changes, now that a node has been deleted,\n // there might be changes in _changes table that is not needed to keep anymore.\n // This is done in its own transaction, or possible several transaction to prohibit\n // starvation\n Observable.deleteOldChanges(db);\n });\n });\n };\n\n db.syncable.unsyncedChanges = function(url) {\n return db._syncNodes.where(\"url\").equals(url).first(function(node) {\n return db._changes.where('rev').above(node.myRevision).toArray();\n });\n };\n\n db.close = override(db.close, function(origClose) {\n return function() {\n activePeers.forEach(function(peer) {\n peer.disconnect();\n });\n return origClose.apply(this, arguments);\n };\n });\n\n Object.defineProperty(\n db.observable.SyncNode.prototype,\n 'save', {\n enumerable: false,\n configurable: true,\n writable: true,\n value() {\n return db.transaction('rw?', db._syncNodes, () => {\n return db._syncNodes.put(this);\n });\n }\n });\n}\n\nSyncable.Statuses = Statuses;\n\nSyncable.StatusTexts = StatusTexts;\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\n /// \n /// Register a synchronization protocol that can synchronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n const partialsThreshold = protocolInstance.partialsThreshold;\n if (typeof partialsThreshold === 'number') {\n // Don't allow NaN or negative threshold\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\n throw new Error('The given number for the threshold is not supported');\n }\n // If the threshold is 0 we will not send any client changes but will get server changes\n } else {\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\n protocolInstance.partialsThreshold = Infinity;\n }\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Syncable;\nDexie.addons.push(Syncable);\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,SAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AAE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iB,GAAG,QAAQ,CAAC;KACjD;IACD,QAAQ,CAAC,mBAAmB,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC;CACzD,CAAC;;AAGF,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC1B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;;"} \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js b/addons/Dexie.Syncable/dist/dexie-syncable.js new file mode 100644 index 000000000..a97669038 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js @@ -0,0 +1,1205 @@ +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.4, Thu Mar 01 2018 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('dexie'), require('dexie-observable')) : + typeof define === 'function' && define.amd ? define(['dexie', 'dexie-observable'], factory) : + (global.Dexie = global.Dexie || {}, global.Dexie.Syncable = factory(global.Dexie)); +}(this, (function (Dexie) { 'use strict'; + +Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + +var Promise$1 = Dexie.Promise; +function initSyncableConnect(db, connect) { + return function syncableConnect(protocolInstance, protocolName, url, options) { + if (db.isOpen()) { + // Database is open + if (!db._localSyncNode) + throw new Error("Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!"); + if (db._localSyncNode.isMaster) { + // We are master node + return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id); + } + else { + // We are not master node + // Request master node to do the connect: + return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) { + // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves. + return db.observable.sendMessage('connect', { + protocolName: protocolName, + url: url, + options: options + }, masterNode.id, { wantReply: true }); + }); + } + } + else if (db.hasBeenClosed()) { + // Database has been closed. + return Promise$1.reject(new Dexie.DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$1.reject(new Dexie.InvalidStateError("Dexie.Syncable: Cannot connect. Database has failed to open")); + } + else { + // Database not yet open. It may be on its way to open, or open() hasn't yet been called. + // Wait for it to open, then connect. + var promise = new Promise$1(function (resolve, reject) { + db.on("ready", function () { + // First, check if this is the very first time we connect to given URL. + // Need to know, because if it is, we should stall the promise returned to + // db.on('ready') to not be fulfilled until the initial sync has succeeded. + return db._syncNodes.get({ url: url }, function (node) { + // Ok, now we know whether we should await the connect promise or not. + // No matter, we should now connect (will maybe create the SyncNode instance + // representing the given URL) + var connectPromise = db.syncable.connect(protocolName, url, options); + connectPromise.then(resolve, reject); // Resolve the returned promise when connected. + // Ok, so let's see if we should suspend DB queries until connected or not: + if (node && node.appliedRemoteRevision) { + // The very first initial sync has been done so we need not wait + // for the connect promise to complete. It can continue in background. + // Returning here will resume db.on('ready') and resume all queries that + // the application has put to the database. + return; + } + // This was the very first time we connect to the remote server, + // we must make sure that the initial sync request succeeeds before resuming + // database queries that the application code puts onto the database. + // If OFFLINE or other error, don't allow the application to proceed. + // We are assuming that an initial sync is essential for the application to + // function correctly. + return connectPromise; + }); + }); + // Force open() to happen. Otherwise connect() may stall forever. + db.open().catch(function (ex) { + // If open fails, db.on('ready') may not have been called and we must + // reject promise with InvalidStateError + reject(new Dexie.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open", ex)); + }); + }); + return promise; + } + }; +} + +function initPersistedContext(node) { + // + // PersistedContext : IPersistedContext + // + return /** @class */ (function () { + function PersistedContext(nodeID, otherProps) { + this.nodeID = nodeID; + if (otherProps) + Dexie.extend(this, otherProps); + } + PersistedContext.prototype.save = function () { + // Store this instance in the syncContext property of the node it belongs to. + return Dexie.vip(function () { + return node.save(); + }); + }; + return PersistedContext; + }()); +} + +function initGetOrCreateSyncNode(db, protocolName, url) { + return function getOrCreateSyncNode(options) { + return db.transaction('rw', db._syncNodes, db._changes, function () { + if (!url) + throw new Error("Url cannot be empty"); + // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise. + return db._syncNodes.where("url").equalsIgnoreCase(url).first(function (node) { + // If we found a node it will be instanceof SyncNode as Dexie.Observable + // maps to class + if (node) { + var PersistedContext = initPersistedContext(node); + // Node already there. Make syncContext become an instance of PersistedContext: + node.syncContext = new PersistedContext(node.id, node.syncContext); + node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen... + node.syncOptions = options; // Options could have been changed + db._syncNodes.put(node); + } + else { + // Create new node and sync everything + node = new db.observable.SyncNode(); + node.myRevision = -1; + node.appliedRemoteRevision = null; + node.remoteBaseRevisions = []; + node.type = "remote"; + node.syncProtocol = protocolName; + node.url = url; + node.syncOptions = options; + node.lastHeartBeat = Date.now(); + node.dbUploadState = null; + var PersistedContext_1 = initPersistedContext(node); + Dexie.Promise.resolve(function () { + // If options.initialUpload is explicitely false, set myRevision to currentRevision. + if (options.initialUpload === false) + return db._changes.toCollection().lastKey(function (currentRevision) { + node.myRevision = currentRevision; + }); + }()).then(function () { + db._syncNodes.add(node).then(function (nodeID) { + node.syncContext = new PersistedContext_1(nodeID); // Update syncContext in db with correct nodeId. + db._syncNodes.put(node); + }); + }); + } + return node; // returning node will make the db.transaction()-promise resolve with this value. + }); + }); + }; +} + +function initEnqueue(db) { + return function enqueue(context, fn, instanceID) { + function _enqueue() { + if (!context.ongoingOperation) { + context.ongoingOperation = Dexie.ignoreTransaction(function () { + return Dexie.vip(function () { + return fn(); + }); + }).finally(function () { + delete context.ongoingOperation; + }); + } + else { + context.ongoingOperation = context.ongoingOperation.then(function () { + return enqueue(context, fn, instanceID); + }); + } + return context.ongoingOperation; + } + if (!instanceID) { + // Caller wants to enqueue it until database becomes open. + if (db.isOpen()) { + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + } + else if (db._localSyncNode && instanceID === db._localSyncNode.id) { + // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB) + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + }; +} + +function initSaveToUncommittedChanges(db, node) { + return function saveToUncommittedChanges(changes, remoteRevision) { + return db.transaction('rw!', db._uncommittedChanges, function () { + return db._uncommittedChanges.bulkAdd(changes.map(function (change) { + var changeWithNodeId = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) + changeWithNodeId.obj = change.obj; + if (change.mods) + changeWithNodeId.mods = change.mods; + return changeWithNodeId; + })); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + return node.save(); + }); + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function bulkUpdate(table, changes) { + var keys = changes.map(function (c) { return c.key; }); + var map = {}; + // Retrieve current object of each change to update and map each + // found object's primary key to the existing object: + return table.where(':id').anyOf(keys).raw().each(function (obj, cursor) { + map[cursor.primaryKey + ''] = obj; + }).then(function () { + // Filter away changes whose key wasn't found in the local database + // (we can't update them if we do not know the existing values) + var updatesThatApply = changes.filter(function (c) { return map.hasOwnProperty(c.key + ''); }); + // Apply modifications onto each existing object (in memory) + // and generate array of resulting objects to put using bulkPut(): + var objsToPut = updatesThatApply.map(function (c) { + var curr = map[c.key + '']; + Object.keys(c.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]); + }); + return curr; + }); + return table.bulkPut(objsToPut); + }); +} + +function initApplyChanges(db) { + return function applyChanges(changes) { + var collectedChanges = {}; + changes.forEach(function (change) { + if (!collectedChanges.hasOwnProperty(change.table)) { + collectedChanges[change.table] = (_a = {}, _a[CREATE] = [], _a[DELETE] = [], _a[UPDATE] = [], _a); + } + collectedChanges[change.table][change.type].push(change); + var _a; + }); + var table_names = Object.keys(collectedChanges); + var tables = table_names.map(function (table) { return db.table(table); }); + return db.transaction("rw", tables, function () { + table_names.forEach(function (table_name) { + var table = db.table(table_name); + var specifyKeys = !table.schema.primKey.keyPath; + var createChangesToApply = collectedChanges[table_name][CREATE]; + var deleteChangesToApply = collectedChanges[table_name][DELETE]; + var updateChangesToApply = collectedChanges[table_name][UPDATE]; + if (createChangesToApply.length > 0) + table.bulkPut(createChangesToApply.map(function (c) { return c.obj; }), specifyKeys ? + createChangesToApply.map(function (c) { return c.key; }) : undefined); + if (updateChangesToApply.length > 0) + bulkUpdate(table, updateChangesToApply); + if (deleteChangesToApply.length > 0) + table.bulkDelete(deleteChangesToApply.map(function (c) { return c.key; })); + }); + }); + }; +} + +function initFinallyCommitAllChanges(db, node) { + var applyChanges = initApplyChanges(db); + return function finallyCommitAllChanges(changes, remoteRevision) { + // 1. Open a write transaction on all tables in DB + var tablesToIncludeInTrans = db.tables.filter(function (table) { return table.name === '_changes' || + table.name === '_uncommittedChanges' || + table.schema.observable; }); + return db.transaction('rw!', tablesToIncludeInTrans, function () { + var trans = Dexie.currentTransaction; + var localRevisionBeforeChanges = 0; + return db._changes.orderBy('rev').last(function (lastChange) { + // Store what revision we were at before committing the changes + localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0; + }).then(function () { + // Specify the source. Important for the change consumer to ignore changes originated from self! + trans.source = node.id; + // 2. Apply uncommitted changes and delete each uncommitted change + return db._uncommittedChanges.where('node').equals(node.id).toArray(); + }).then(function (uncommittedChanges) { + return applyChanges(uncommittedChanges); + }).then(function () { + return db._uncommittedChanges.where('node').equals(node.id).delete(); + }).then(function () { + // 3. Apply last chunk of changes + return applyChanges(changes); + }).then(function () { + // Get what revision we are at now: + return db._changes.orderBy('rev').last(); + }).then(function (lastChange) { + var currentLocalRevision = (lastChange && lastChange.rev) || 0; + // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision) + node.appliedRemoteRevision = remoteRevision; + node.remoteBaseRevisions.push({ remote: remoteRevision, local: currentLocalRevision }); + if (node.myRevision === localRevisionBeforeChanges) { + // If server was up-to-date before we added new changes from the server, update myRevision to last change + // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from + // ever sending an empty change list to server, which would otherwise be done every second time it would send changes. + node.myRevision = currentLocalRevision; + } + // Garbage collect remoteBaseRevisions not in use anymore: + if (node.remoteBaseRevisions.length > 1) { + for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) { + if (node.myRevision >= node.remoteBaseRevisions[i].local) { + node.remoteBaseRevisions.splice(0, i); + break; + } + } + } + // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction. + node.save().catch(function (err) { + console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: " + (err.stack || err)); + }); + }); + }); + }; +} + +function getBaseRevisionAndMaxClientRevision(node) { + /// + if (node.remoteBaseRevisions.length === 0) + return { + // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision: + maxClientRevision: Infinity, + remoteBaseRevision: null + }; + for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) { + if (node.myRevision >= node.remoteBaseRevisions[i].local) { + // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on. + return { + maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local, + remoteBaseRevision: node.remoteBaseRevisions[i].remote + }; + } + } + // There are at least one item in the list but the server hasn't yet become up-to-date with the 0 revision from client. + return { + maxClientRevision: node.remoteBaseRevisions[0].local, + remoteBaseRevision: null + }; +} + +function combineCreateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered. + Object.keys(nextChange.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]); + }); + return clonedChange; +} + +function combineUpdateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered. + Object.keys(nextChange.mods).forEach(function (keyPath) { + // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath + var hadParentPath = false; + Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) { + Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]); + hadParentPath = true; + }); + if (!hadParentPath) { + // Add or replace this keyPath and its new value + clonedChange.mods[keyPath] = nextChange.mods[keyPath]; + } + // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since + // we must mimic what would happen if applying the two changes after each other: + Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) { + delete clonedChange.mods[subPath]; + }); + }); + return clonedChange; +} + +function mergeChange(prevChange, nextChange) { + switch (prevChange.type) { + case CREATE: + switch (nextChange.type) { + case CREATE: + return nextChange; // Another CREATE replaces previous CREATE. + case UPDATE: + return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj + case DELETE: + return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm! + } + break; + case UPDATE: + switch (nextChange.type) { + case CREATE: + return nextChange; // Another CREATE replaces previous update. + case UPDATE: + return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set. + case DELETE: + return nextChange; // Only send the delete change. What was updated earlier is no longer of interest. + } + break; + case DELETE: + switch (nextChange.type) { + case CREATE: + return nextChange; // A resurection occurred. Only create change is of interest. + case UPDATE: + return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there. + case DELETE: + return prevChange; // Still a delete change. Leave as is. + } + break; + } +} + +function initGetChangesSinceRevision(db, node, hasMoreToGive) { + return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) { + /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result. + var changeSet = {}; + var numChanges = 0; + var partial = false; + var ignoreSource = node.id; + var nextRevision = revision; + return db.transaction('r', db._changes, function () { + var query = db._changes.where('rev').between(revision, maxRevision, false, true); + return query.until(function () { + if (numChanges === maxChanges) { + partial = true; + return true; + } + }).each(function (change) { + // Note the revision in nextRevision: + nextRevision = change.rev; + // change.source is set based on currentTransaction.source + if (change.source === ignoreSource) + return; + // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info: + var changeToSend = { + type: change.type, + table: change.table, + key: change.key + }; + if (change.type === CREATE) + changeToSend.obj = change.obj; + else if (change.type === UPDATE) + changeToSend.mods = change.mods; + var id = change.table + ":" + change.key; + var prevChange = changeSet[id]; + if (!prevChange) { + // This is the first change on this key. Add it unless it comes from the source that we are working against + changeSet[id] = changeToSend; + ++numChanges; + } + else { + // Merge the oldchange with the new change + var nextChange = changeToSend; + var mergedChange = mergeChange(prevChange, nextChange); + changeSet[id] = mergedChange; + } + }); + }).then(function () { + var changes = Object.keys(changeSet).map(function (key) { + return changeSet[key]; + }); + hasMoreToGive.hasMoreToGive = partial; + return cb(changes, partial, { myRevision: nextRevision }); + }); + }; +} + +function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) { + return function getTableObjectsAsChanges(state, changes, collection) { + /// + /// + /// + var limitReached = false; + return collection.until(function () { + if (changes.length === MAX_CHANGES_PER_CHUNK) { + limitReached = true; + return true; + } + }).each(function (item, cursor) { + changes.push({ + type: CREATE, + table: state.currentTable, + key: cursor.key, + obj: cursor.value + }); + state.currentKey = cursor.key; + }).then(function () { + if (limitReached) { + // Limit reached. Send partial result. + hasMoreToGive.hasMoreToGive = true; + return cb(changes, null, true, { dbUploadState: state }); + } + else { + // Done iterating this table. Check if there are more tables to go through: + if (state.tablesToUpload.length === 0) { + // Done iterating all tables + // Now append changes occurred during our dbUpload: + var brmcr = getBaseRevisionAndMaxClientRevision(node); + return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) { + changes = changes.concat(additionalChanges); + nodeModificationsOnAck.dbUploadState = null; + return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck); + }); + } + else { + // Not done iterating all tables. Continue on next table: + state.currentTable = state.tablesToUpload.shift(); + return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id')); + } + } + }); + }; +} + +function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) { + var MAX_CHANGES_PER_CHUNK = partialsThreshold; + return function getLocalChangesForNode(node, cb) { + /// + /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes + /// for that node. + /// + /// + /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result. + var getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive); + var getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb); + // Only a "remote" SyncNode created by Dexie.Syncable + // could not pass this test (remote nodes have myRevision: -1 on instantiation) + if (node.myRevision >= 0) { + // Node is based on a revision in our local database and will just need to get the changes that have occurred since that revision. + var brmcr = getBaseRevisionAndMaxClientRevision(node); + return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) { + return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck); + }); + } + else { + // Node hasn't got anything from our local database yet. We will need to upload the entire DB to the node in the form of CREATE changes. + // Check if we're in the middle of already doing that: + if (node.dbUploadState === null) { + // Initialize dbUploadState + var tablesToUpload = db.tables.filter(function (table) { + return table.schema.observable; + }).map(function (table) { + return table.name; + }); + if (tablesToUpload.length === 0) + return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all. + var dbUploadState = { + tablesToUpload: tablesToUpload, + currentTable: tablesToUpload.shift(), + currentKey: null + }; + return db._changes.orderBy('rev').last(function (lastChange) { + dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0; + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(dbUploadState, [], collection); + }); + } + else if (node.dbUploadState.currentKey) { + var collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey); + return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection); + } + else { + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection); + } + } + }; +} + +var Statuses = { + ERROR: -1, + OFFLINE: 0, + CONNECTING: 1, + ONLINE: 2, + SYNCING: 3, + ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect. +}; +var StatusTexts = { + "-1": "ERROR", + "0": "OFFLINE", + "1": "CONNECTING", + "2": "ONLINE", + "3": "SYNCING", + "4": "ERROR_WILL_RETRY" +}; + +var Promise$2 = Dexie.Promise; +function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) { + var enqueue = initEnqueue(db); + var hasMoreToGive = { hasMoreToGive: true }; + function stillAlive() { + // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead + // because the new instance should be considered a fresh instance and will have another local node. + return db._localSyncNode && db._localSyncNode.id === dbAliveID; + } + return function connectProtocol(node, activePeer) { + /// + var getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold); + var url = activePeer.url; + function changeStatusTo(newStatus) { + if (node.status !== newStatus) { + node.status = newStatus; + node.save().then(function () { + db.syncable.on.statusChanged.fire(newStatus, url); + // Also broadcast message to other nodes about the status + db.observable.broadcastMessage("syncStatusChanged", { newStatus: newStatus, url: url }, false); + }).catch('DatabaseClosedError', function () { + }); + } + } + activePeer.on('disconnect', function (newStatus) { + if (!isNaN(newStatus)) + changeStatusTo(newStatus); + }); + var connectedContinuation; + changeStatusTo(Statuses.CONNECTING); + return doSync(); + function doSync() { + // Use enqueue() to ensure only a single promise execution at a time. + return enqueue(doSync, function () { + // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence. + return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider); + }, dbAliveID); + } + function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess(). + // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants. + var finalSyncPromise = new Promise$2(function (resolve, reject) { + rejectConnectPromise.p = function (err) { + reject(err); + }; + Dexie.asap(function () { + try { + protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, function (continuation) { + resolve(continuation); + }, onError); + } + catch (ex) { + onError(ex, Infinity); + } + function onError(error, again) { + reject(error); + if (stillAlive()) { + if (!isNaN(again) && again < Infinity) { + setTimeout(function () { + if (stillAlive()) { + changeStatusTo(Statuses.SYNCING); + doSync().catch('DatabaseClosedError', abortTheProvider); + } + }, again); + changeStatusTo(Statuses.ERROR_WILL_RETRY, error); + if (connectedContinuation && connectedContinuation.disconnect) + connectedContinuation.disconnect(); + connectedContinuation = null; + } + else { + abortTheProvider(error); // Will fire ERROR on statusChanged event. + } + } + } + }); + }); + return finalSyncPromise.then(function () { + // Resolve caller of db.syncable.connect() with undefined. Not with continuation! + return undefined; + }).finally(function () { + // In case error happens after connect, don't try reject the connect promise anymore. + // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon + // is active and this happens. It would fire unhandledrejection but that we do not want. + rejectConnectPromise.p = null; + }); + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately, + // otherwise it will execute when finalSyncPromise resolves. + finalSyncPromise.then(continueSendingChanges); + return node.save(); + } + } + function abortTheProvider(error) { + activePeer.disconnect(Statuses.ERROR, error); + } + function getLocalChangesForNode_autoAckIfEmpty(node, cb) { + return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save().catch('DatabaseClosedError', function () { + }); + return getLocalChangesForNode(node, autoAck); + } + else { + return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck); + } + }); + } + function applyRemoteChanges(remoteChanges, remoteRevision, partial /*, clear*/) { + var saveToUncommittedChanges = initSaveToUncommittedChanges(db, node); + var finallyCommitAllChanges = initFinallyCommitAllChanges(db, node); + return enqueue(applyRemoteChanges, function () { + if (!stillAlive()) + return Promise$2.reject(new Dexie.DatabaseClosedError()); + // FIXTHIS: Check what to do if clear() is true! + return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision)) + .catch(function (error) { + abortTheProvider(error); + return Promise$2.reject(error); + }); + }, dbAliveID); + } + // + // + // Continuation Patterns Follows + // + // + function continueSendingChanges(continuation) { + if (!stillAlive()) { + if (continuation.disconnect) + continuation.disconnect(); + return; + } + connectedContinuation = continuation; + activePeer.on('disconnect', function () { + if (connectedContinuation) { + if (connectedContinuation.react) { + try { + // react pattern must provide a disconnect function. + connectedContinuation.disconnect(); + } + catch (e) { + } + } + connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice. + } + }); + if (continuation.react) { + continueUsingReactPattern(continuation); + } + else { + continueUsingPollPattern(continuation); + } + } + // React Pattern (eager) + function continueUsingReactPattern(continuation) { + var changesWaiting, // Boolean + isWaitingForServer; // Boolean + function onChanges() { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + if (isWaitingForServer) + changesWaiting = true; + else { + reactToChanges(); + } + } + } + db.on('changes', onChanges); + activePeer.on('disconnect', function () { + db.on.changes.unsubscribe(onChanges); + }); + function reactToChanges() { + if (!connectedContinuation) + return; + changesWaiting = false; + isWaitingForServer = true; + getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + if (!connectedContinuation) + return; + if (changes.length > 0) { + continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save().catch('DatabaseClosedError', function () { + }); + // More changes may be waiting: + reactToChanges(); + }); + } + else { + isWaitingForServer = false; + if (changesWaiting) { + // A change jumped in between the time-spot of quering _changes and getting called back with zero changes. + // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory. + reactToChanges(); + } + else { + changeStatusTo(Statuses.ONLINE); + } + } + }).catch(function (ex) { + console.error("Got " + ex.message + " caught by reactToChanges"); + abortTheProvider(ex); + }); + } + reactToChanges(); + } + // Poll Pattern + function continueUsingPollPattern() { + function syncAgain() { + getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) { + protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError); + function onChangesAccepted() { + Object.keys(nodeModificationsOnAck).forEach(function (keyPath) { + Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]); + }); + node.save().catch('DatabaseClosedError', function () { + }); + } + function onSuccess(continuation) { + if (!connectedContinuation) { + // Got disconnected before succeeding. Quit. + return; + } + connectedContinuation = continuation; + if (partial) { + // We only sent partial changes. Need to do another round asap. + syncAgain(); + } + else { + // We've sent all changes now (in sync!) + if (!isNaN(continuation.again) && continuation.again < Infinity) { + // Provider wants to keep polling. Set Status to ONLINE. + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, continuation.again); + } + else { + // Provider seems finished polling. Since we are never going to poll again, + // disconnect provider and set status to OFFLINE until another call to db.syncable.connect(). + activePeer.disconnect(Statuses.OFFLINE); + } + } + } + function onError(error, again) { + if (!isNaN(again) && again < Infinity) { + if (connectedContinuation) { + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, again); + changeStatusTo(Statuses.ERROR_WILL_RETRY); + } // else status is already changed since we got disconnected. + } + else { + abortTheProvider(error); // Will fire ERROR on onStatusChanged. + } + } + }).catch(abortTheProvider); + } + if (hasMoreToGive.hasMoreToGive) { + syncAgain(); + } + else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) { + changeStatusTo(Statuses.ONLINE); + setTimeout(function () { + if (connectedContinuation) { + changeStatusTo(Statuses.SYNCING); + syncAgain(); + } + }, connectedContinuation.again); + } + else { + // Provider seems finished polling. Since we are never going to poll again, + // disconnect provider and set status to OFFLINE until another call to db.syncable.connect(). + activePeer.disconnect(Statuses.OFFLINE); + } + } + }; +} + +function initConnectFn(db, activePeers) { + return function connect(protocolInstance, protocolName, url, options, dbAliveID) { + /// + var existingPeer = activePeers.filter(function (peer) { + return peer.url === url; + }); + if (existingPeer.length > 0) { + var activePeer = existingPeer[0]; + var diffObject = {}; + Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject); + // Options have been changed + // We need to disconnect and reconnect + if (Object.keys(diffObject).length !== 0) { + return db.syncable.disconnect(url) + .then(function () { + return execConnect(); + }); + } + else { + // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that + // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly. + return existingPeer[0].connectPromise; + } + } + function execConnect() { + // Use an object otherwise we wouldn't be able to get the reject promise from + // connectProtocol + var rejectConnectPromise = { p: null }; + var connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise); + var getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url); + var connectPromise = getOrCreateSyncNode(options).then(function (node) { + return connectProtocol(node, activePeer); + }); + var disconnected = false; + var activePeer = { + url: url, + status: Statuses.OFFLINE, + connectPromise: connectPromise, + syncOptions: options, + on: Dexie.Events(null, "disconnect"), + disconnect: function (newStatus, error) { + var pos = activePeers.indexOf(activePeer); + if (pos >= 0) + activePeers.splice(pos, 1); + if (error && rejectConnectPromise.p) + rejectConnectPromise.p(error); + if (!disconnected) { + activePeer.on.disconnect.fire(newStatus, error); + } + disconnected = true; + } + }; + activePeers.push(activePeer); + return connectPromise; + } + return execConnect(); + }; +} + +/* ========================================================================== + * dexie-syncable.js + * ========================================================================== + * + * Dexie addon for syncing indexedDB with remote endpoints. + * + * By David Fahlander, david.fahlander@gmail.com, + * Nikolas Poniros, https://github.com/nponiros + * + * ========================================================================== + * + * Version 1.0.0-beta.4, Thu Mar 01 2018 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +// Depend on 'dexie-observable' +// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as "Dexie.Observable". +// That way, our plugin works in all UMD cases. +// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from "dexie-observable"'. +var override = Dexie.override; +var Promise = Dexie.Promise; +var Observable = Dexie.Observable; +function Syncable(db) { + /// + var activePeers = []; + var connectFn = initConnectFn(db, activePeers); + var syncableConnect = initSyncableConnect(db, connectFn); + db.on('message', function (msg) { + // Message from other local node arrives... + Dexie.vip(function () { + if (msg.type === 'connect') { + // We are master node and another non-master node wants us to do the connect. + db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject); + } + else if (msg.type === 'disconnect') { + db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject); + } + else if (msg.type === 'syncStatusChanged') { + // We are client and a master node informs us about syncStatus change. + // Lookup the connectedProvider and call its event + db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url); + } + }); + }); + db.on('cleanup', function (weBecameMaster) { + // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master. + if (weBecameMaster) { + // We took over the master role in Observable's cleanup method. + // We should connect to remote servers now. + // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR. + // Reason to reconnect to those with plain "ERROR" is that the ERROR state may occur when a database + // connection has been closed. The new master would then be expected to reconnect. + // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from + // an old closed one. + Dexie.ignoreTransaction(function () { return Dexie.vip(function () { + return db._syncNodes.where({ type: 'remote' }) + .filter(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { return Promise.all(connectedRemoteNodes.map(function (node) { + return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(function (e) { + console.warn("Dexie.Syncable: Could not connect to " + node.url + ". " + (e.stack || e)); + }); + })); }); + }); }).catch('DatabaseClosedError', function () { }); + } + }); + // "ready" subscriber for the master node that makes sure it will always connect to sync server + // when the database opens. It will not wait for the connection to complete, just initiate the + // connection so that it will continue syncing as long as the database is open. + // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure + // that db._localSyncNode exists and persisted before this subscriber kicks in. + db.on('ready', function onReady() { + // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state. + if (db._localSyncNode && db._localSyncNode.isMaster) { + // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!) + // This "ready" subscriber will never be the one performing the initial sync request, because + // even after calling db.syncable.connect(), there won't exist any "remote" sync node yet. + // Instead, db.syncable.connect() will subscribe to "ready" also, and that subscriber will be + // called after this one. There, in that subscriber, the initial sync request will take place + // and the "remote" node will be created so that this "ready" subscriber can auto-connect the + // next time this database is opened. + // CONCLUSION: We can always assume that the local DB has been in sync with the server at least + // once in the past for each "connectedRemoteNode" we find in query below. + // Don't halt db.ready while connecting (i.e. we do not return a promise here!) + db._syncNodes + .where('type').equals('remote') + .and(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { + // There are connected remote nodes that we must manage (or take over to manage) + connectedRemoteNodes.forEach(function (node) { return db.syncable.connect(node.syncProtocol, node.url, node.syncOptions) + .catch(function () { }); } // A failure will be triggered in on('statusChanged'). We can ignore. + ); + }).catch('DatabaseClosedError', function () { }); + } + }, true); // True means the ready event will survive a db reopen - db.close()/db.open() + db.syncable = {}; + db.syncable.getStatus = function (url, cb) { + if (db.isOpen()) { + return Dexie.vip(function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node ? node.status : Statuses.OFFLINE; + }); + }).then(cb); + } + else { + return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb); + } + }; + db.syncable.getOptions = function (url, cb) { + return db.transaction('r?', db._syncNodes, function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node.syncOptions; + }).then(cb); + }); + }; + db.syncable.list = function () { + return db.transaction('r?', db._syncNodes, function () { + return db._syncNodes.where('type').equals('remote').toArray(function (a) { + return a.map(function (node) { return node.url; }); + }); + }); + }; + db.syncable.on = Dexie.Events(db, { statusChanged: "asap" }); + db.syncable.disconnect = function (url) { + return Dexie.ignoreTransaction(function () { + return Promise.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise.all(activePeers.filter(function (peer) { return peer.url === url; }).map(function (peer) { + return peer.disconnect(Statuses.OFFLINE); + })); + } + else { + return db._syncNodes.where('isMaster').above(0).first(function (masterNode) { + return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, { wantReply: true }); + }); + } + }).then(function () { + return db._syncNodes.where("url").equals(url).modify(function (node) { + node.status = Statuses.OFFLINE; + }); + }); + }); + }; + db.syncable.connect = function (protocolName, url, options) { + options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined. + var protocolInstance = Syncable.registeredProtocols[protocolName]; + if (protocolInstance) { + return syncableConnect(protocolInstance, protocolName, url, options); + } + else { + return Promise.reject(new Error("ISyncProtocol '" + protocolName + "' is not registered in Dexie.Syncable.registerSyncProtocol()")); + } + }; + db.syncable.delete = function (url) { + return db.syncable.disconnect(url).then(function () { + return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, function () { + // Find the node(s) + // Several can be found, as detected by @martindiphoorn, + // let's delete them and cleanup _uncommittedChanges and _changes + // accordingly. + var nodeIDsToDelete; + return db._syncNodes + .where("url").equals(url) + .toArray(function (nodes) { return nodes.map(function (node) { return node.id; }); }) + .then(function (nodeIDs) { + nodeIDsToDelete = nodeIDs; + // Delete the syncNode that represents the remote endpoint. + return db._syncNodes.where('id').anyOf(nodeIDs).delete(); + }) + .then(function () { + // In case there were uncommittedChanges belonging to this, delete them as well + return db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete(); + }); + }).then(function () { + // Spawn background job to delete old changes, now that a node has been deleted, + // there might be changes in _changes table that is not needed to keep anymore. + // This is done in its own transaction, or possible several transaction to prohibit + // starvation + Observable.deleteOldChanges(db); + }); + }); + }; + db.syncable.unsyncedChanges = function (url) { + return db._syncNodes.where("url").equals(url).first(function (node) { + return db._changes.where('rev').above(node.myRevision).toArray(); + }); + }; + db.close = override(db.close, function (origClose) { + return function () { + activePeers.forEach(function (peer) { + peer.disconnect(); + }); + return origClose.apply(this, arguments); + }; + }); + Object.defineProperty(db.observable.SyncNode.prototype, 'save', { + enumerable: false, + configurable: true, + writable: true, + value: function () { + var _this = this; + return db.transaction('rw?', db._syncNodes, function () { + return db._syncNodes.put(_this); + }); + } + }); +} +Syncable.Statuses = Statuses; +Syncable.StatusTexts = StatusTexts; +Syncable.registeredProtocols = {}; // Map when key is the provider name. +Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a synchronization protocol that can synchronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + var partialsThreshold = protocolInstance.partialsThreshold; + if (typeof partialsThreshold === 'number') { + // Don't allow NaN or negative threshold + if (isNaN(partialsThreshold) || partialsThreshold < 0) { + throw new Error('The given number for the threshold is not supported'); + } + // If the threshold is 0 we will not send any client changes but will get server changes + } + else { + // Use Infinity as the default so simple protocols don't have to care about partial synchronization + protocolInstance.partialsThreshold = Infinity; + } + Syncable.registeredProtocols[name] = protocolInstance; +}; +// Register addon in Dexie: +Dexie.Syncable = Syncable; +Dexie.addons.push(Syncable); + +return Syncable; + +}))); +//# sourceMappingURL=dexie-syncable.js.map diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js.map b/addons/Dexie.Syncable/dist/dexie-syncable.js.map new file mode 100644 index 000000000..0ce1d8d56 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-syncable.js","sources":["../src/syncable-connect.js","../src/PersistedContext.js","../src/get-or-create-sync-node.js","../src/enqueue.js","../src/save-to-uncommitted-changes.js","../src/change_types.js","../src/bulk-update.js","../src/apply-changes.js","../src/finally-commit-all-changes.js","../src/get-local-changes-for-node/get-base-revision-and-max-client-revision.js","../src/combine-create-and-update.js","../src/combine-update-and-update.js","../src/merge-change.js","../src/get-local-changes-for-node/get-changes-since-revision.js","../src/get-local-changes-for-node/get-table-objects-as-changes.js","../src/get-local-changes-for-node/get-local-changes-for-node.js","../src/statuses.js","../src/connect-protocol.js","../src/connect-fn.js","../src/Dexie.Syncable.js"],"sourcesContent":["import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initSyncableConnect(db, connect) {\n return function syncableConnect(protocolInstance, protocolName, url, options) {\n if (db.isOpen()) {\n // Database is open\n if (!db._localSyncNode)\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\n\n if (db._localSyncNode.isMaster) {\n // We are master node\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\n } else {\n // We are not master node\n // Request master node to do the connect:\n return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\n // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves.\n return db.observable.sendMessage('connect', {\n protocolName: protocolName,\n url: url,\n options: options\n }, masterNode.id, {wantReply: true});\n });\n }\n } else if (db.hasBeenClosed()) {\n // Database has been closed.\n return Promise.reject(new Dexie.DatabaseClosedError());\n } else if (db.hasFailed()) {\n // Database has failed to open\n return Promise.reject(new Dexie.InvalidStateError(\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\n } else {\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\n // Wait for it to open, then connect.\n var promise = new Promise(function (resolve, reject) {\n db.on(\"ready\", () => {\n // First, check if this is the very first time we connect to given URL.\n // Need to know, because if it is, we should stall the promise returned to\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\n return db._syncNodes.get({url}, node => {\n // Ok, now we know whether we should await the connect promise or not.\n // No matter, we should now connect (will maybe create the SyncNode instance\n // representing the given URL)\n let connectPromise = db.syncable.connect(protocolName, url, options);\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\n // Ok, so let's see if we should suspend DB queries until connected or not:\n if (node && node.appliedRemoteRevision) {\n // The very first initial sync has been done so we need not wait\n // for the connect promise to complete. It can continue in background.\n // Returning here will resume db.on('ready') and resume all queries that\n // the application has put to the database.\n return;\n }\n // This was the very first time we connect to the remote server,\n // we must make sure that the initial sync request succeeeds before resuming\n // database queries that the application code puts onto the database.\n // If OFFLINE or other error, don't allow the application to proceed.\n // We are assuming that an initial sync is essential for the application to\n // function correctly.\n return connectPromise;\n });\n });\n // Force open() to happen. Otherwise connect() may stall forever.\n db.open().catch(ex => {\n // If open fails, db.on('ready') may not have been called and we must\n // reject promise with InvalidStateError\n reject(new Dexie.InvalidStateError(\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\n ex\n ));\n });\n });\n return promise;\n }\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initPersistedContext(node) {\n //\n // PersistedContext : IPersistedContext\n //\n return class PersistedContext {\n constructor(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n save() {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(() => {\n return node.save();\n });\n }\n }\n}\n","import Dexie from 'dexie';\n\nimport initPersistedContext from './PersistedContext';\n\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\n return function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, db._changes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\n // maps to class\n if (node) {\n const PersistedContext = initPersistedContext(node);\n // Node already there. Make syncContext become an instance of PersistedContext:\n node.syncContext = new PersistedContext(node.id, node.syncContext);\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\n node.syncOptions = options; // Options could have been changed\n db._syncNodes.put(node);\n } else {\n // Create new node and sync everything\n node = new db.observable.SyncNode();\n node.myRevision = -1;\n node.appliedRemoteRevision = null;\n node.remoteBaseRevisions = [];\n node.type = \"remote\";\n node.syncProtocol = protocolName;\n node.url = url;\n node.syncOptions = options;\n node.lastHeartBeat = Date.now();\n node.dbUploadState = null;\n const PersistedContext = initPersistedContext(node);\n Dexie.Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false)\n return db._changes.toCollection().lastKey(function (currentRevision) {\n node.myRevision = currentRevision;\n });\n }()).then(function () {\n db._syncNodes.add(node).then(function (nodeID) {\n node.syncContext = new PersistedContext(nodeID); // Update syncContext in db with correct nodeId.\n db._syncNodes.put(node);\n });\n });\n }\n\n return node; // returning node will make the db.transaction()-promise resolve with this value.\n });\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initEnqueue(db) {\n return function enqueue(context, fn, instanceID) {\n function _enqueue() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).finally(()=> {\n delete context.ongoingOperation;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enqueue(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enqueue it until database becomes open.\n if (db.isOpen()) {\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB)\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n };\n}\n","export default function initSaveToUncommittedChanges(db, node) {\n return function saveToUncommittedChanges(changes, remoteRevision) {\n return db.transaction('rw!', db._uncommittedChanges, () => {\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\n let changeWithNodeId = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeWithNodeId.obj = change.obj;\n if (change.mods) changeWithNodeId.mods = change.mods;\n return changeWithNodeId;\n }));\n }).then(() => {\n node.appliedRemoteRevision = remoteRevision;\n return node.save();\n });\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nexport default function bulkUpdate(table, changes) {\n let keys = changes.map(c => c.key);\n let map = {};\n // Retrieve current object of each change to update and map each\n // found object's primary key to the existing object:\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\n map[cursor.primaryKey+''] = obj;\n }).then(()=>{\n // Filter away changes whose key wasn't found in the local database\n // (we can't update them if we do not know the existing values)\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\n // Apply modifications onto each existing object (in memory)\n // and generate array of resulting objects to put using bulkPut():\n let objsToPut = updatesThatApply.map (c => {\n let curr = map[c.key+''];\n Object.keys(c.mods).forEach(keyPath => {\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\n });\n return curr;\n });\n return table.bulkPut(objsToPut);\n });\n}\n","import Dexie from 'dexie';\nimport { CREATE, DELETE, UPDATE } from './change_types';\nimport bulkUpdate from './bulk-update';\n\nexport default function initApplyChanges(db) {\n return function applyChanges(changes) {\n let collectedChanges = {};\n changes.forEach((change) => {\n if (!collectedChanges.hasOwnProperty(change.table)) {\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\n }\n collectedChanges[change.table][change.type].push(change);\n });\n let table_names = Object.keys(collectedChanges);\n let tables = table_names.map((table) => db.table(table));\n\n return db.transaction(\"rw\", tables, () => {\n table_names.forEach((table_name) => {\n const table = db.table(table_name);\n const specifyKeys = !table.schema.primKey.keyPath;\n const createChangesToApply = collectedChanges[table_name][CREATE];\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\n if (createChangesToApply.length > 0)\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\n createChangesToApply.map(c => c.key) : undefined);\n if (updateChangesToApply.length > 0)\n bulkUpdate(table, updateChangesToApply);\n if (deleteChangesToApply.length > 0)\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\n });\n });\n };\n}\n","import Dexie from 'dexie';\nimport initApplyChanges from './apply-changes';\n\nexport default function initFinallyCommitAllChanges(db, node) {\n const applyChanges = initApplyChanges(db);\n\n return function finallyCommitAllChanges(changes, remoteRevision) {\n // 1. Open a write transaction on all tables in DB\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\n table.name === '_uncommittedChanges' ||\n table.schema.observable);\n\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n return db._changes.orderBy('rev').last(function (lastChange) {\n // Store what revision we were at before committing the changes\n localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0;\n }).then(() => {\n // Specify the source. Important for the change consumer to ignore changes originated from self!\n trans.source = node.id;\n // 2. Apply uncommitted changes and delete each uncommitted change\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\n }).then(function (uncommittedChanges) {\n return applyChanges(uncommittedChanges);\n }).then(function () {\n return db._uncommittedChanges.where('node').equals(node.id).delete();\n }).then(function () {\n // 3. Apply last chunk of changes\n return applyChanges(changes);\n }).then(function () {\n // Get what revision we are at now:\n return db._changes.orderBy('rev').last();\n }).then(function (lastChange) {\n var currentLocalRevision = (lastChange && lastChange.rev) || 0;\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\n node.appliedRemoteRevision = remoteRevision;\n node.remoteBaseRevisions.push({remote: remoteRevision, local: currentLocalRevision});\n if (node.myRevision === localRevisionBeforeChanges) {\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\n node.myRevision = currentLocalRevision;\n }\n // Garbage collect remoteBaseRevisions not in use anymore:\n if (node.remoteBaseRevisions.length > 1) {\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n node.remoteBaseRevisions.splice(0, i);\n break;\n }\n }\n }\n // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n node.save().catch(err=> {\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\n });\n });\n });\n };\n}\n","export default function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0)\n return {\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\n maxClientRevision: Infinity,\n remoteBaseRevision: null\n };\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\n return {\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\n };\n }\n }\n // There are at least one item in the list but the server hasn't yet become up-to-date with the 0 revision from client.\n return {\n maxClientRevision: node.remoteBaseRevisions[0].local,\n remoteBaseRevision: null\n };\n}\n","import Dexie from 'dexie';\n\nexport default function combineCreateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n}\n","import Dexie from 'dexie';\n\nexport default function combineUpdateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\n var hadParentPath = false;\n Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\n Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\n hadParentPath = true;\n });\n if (!hadParentPath) {\n // Add or replace this keyPath and its new value\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\n }\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\n // we must mimic what would happen if applying the two changes after each other:\n Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\n delete clonedChange.mods[subPath];\n });\n });\n return clonedChange;\n}\n","import { CREATE, UPDATE, DELETE } from './change_types';\nimport combineCreateAndUpdate from './combine-create-and-update.js';\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\n\nexport default function mergeChange(prevChange, nextChange) {\n switch (prevChange.type) {\n case CREATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous CREATE.\n case UPDATE:\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\n case DELETE:\n return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm!\n }\n break;\n case UPDATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous update.\n case UPDATE:\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\n case DELETE:\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\n }\n break;\n case DELETE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // A resurection occurred. Only create change is of interest.\n case UPDATE:\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\n case DELETE:\n return prevChange; // Still a delete change. Leave as is.\n }\n break;\n }\n}\n","import {CREATE, UPDATE} from '../change_types';\nimport mergeChange from '../merge-change';\n\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\n return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n var changeSet = {};\n var numChanges = 0;\n var partial = false;\n var ignoreSource = node.id;\n var nextRevision = revision;\n return db.transaction('r', db._changes, function () {\n var query = db._changes.where('rev').between(revision, maxRevision, false, true);\n return query.until(() => {\n if (numChanges === maxChanges) {\n partial = true;\n return true;\n }\n }).each(function (change) {\n // Note the revision in nextRevision:\n nextRevision = change.rev;\n // change.source is set based on currentTransaction.source\n if (change.source === ignoreSource) return;\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE)\n changeToSend.obj = change.obj;\n else if (change.type === UPDATE)\n changeToSend.mods = change.mods;\n\n var id = change.table + \":\" + change.key;\n var prevChange = changeSet[id];\n if (!prevChange) {\n // This is the first change on this key. Add it unless it comes from the source that we are working against\n changeSet[id] = changeToSend;\n ++numChanges;\n } else {\n // Merge the oldchange with the new change\n var nextChange = changeToSend;\n var mergedChange = mergeChange(prevChange, nextChange);\n changeSet[id] = mergedChange;\n }\n });\n }).then(function () {\n var changes = Object.keys(changeSet).map(function (key) {\n return changeSet[key];\n });\n hasMoreToGive.hasMoreToGive = partial;\n return cb(changes, partial, {myRevision: nextRevision});\n });\n };\n}\n","import {CREATE} from '../change_types';\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\n\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\n return function getTableObjectsAsChanges(state, changes, collection) {\n /// \n /// \n /// \n var limitReached = false;\n return collection.until(function () {\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\n limitReached = true;\n return true;\n }\n }).each(function (item, cursor) {\n changes.push({\n type: CREATE,\n table: state.currentTable,\n key: cursor.key,\n obj: cursor.value\n });\n state.currentKey = cursor.key;\n }).then(function () {\n if (limitReached) {\n // Limit reached. Send partial result.\n hasMoreToGive.hasMoreToGive = true;\n return cb(changes, null, true, {dbUploadState: state});\n } else {\n // Done iterating this table. Check if there are more tables to go through:\n if (state.tablesToUpload.length === 0) {\n // Done iterating all tables\n // Now append changes occurred during our dbUpload:\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\n changes = changes.concat(additionalChanges);\n nodeModificationsOnAck.dbUploadState = null;\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Not done iterating all tables. Continue on next table:\n state.currentTable = state.tablesToUpload.shift();\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\n }\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\nimport initGetChangesSinceRevision from './get-changes-since-revision';\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\n\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\n\n return function getLocalChangesForNode(node, cb) {\n /// \n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\n /// for that node.\n /// \n /// \n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n\n const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\n\n // Only a \"remote\" SyncNode created by Dexie.Syncable\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\n if (node.myRevision >= 0) {\n // Node is based on a revision in our local database and will just need to get the changes that have occurred since that revision.\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Node hasn't got anything from our local database yet. We will need to upload the entire DB to the node in the form of CREATE changes.\n // Check if we're in the middle of already doing that:\n if (node.dbUploadState === null) {\n // Initialize dbUploadState\n var tablesToUpload = db.tables.filter(function (table) {\n return table.schema.observable;\n }).map(function (table) {\n return table.name;\n });\n if (tablesToUpload.length === 0) return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all.\n var dbUploadState = {\n tablesToUpload: tablesToUpload,\n currentTable: tablesToUpload.shift(),\n currentKey: null\n };\n return db._changes.orderBy('rev').last(function (lastChange) {\n dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0;\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(dbUploadState, [], collection);\n });\n } else if (node.dbUploadState.currentKey) {\n const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n };\n}\n","export const Statuses = {\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasn't yet become online, or it has been disconnected.\n CONNECTING: 1, // Trying to connect to server\n ONLINE: 2, // Connected to server and currently in sync with server\n SYNCING: 3, // Syncing with server. For poll pattern, this is every poll call. For react pattern, this is when local changes are being sent to server.\n ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect.\n};\n\nexport const StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n","import Dexie from 'dexie';\n\nimport initEnqueue from './enqueue';\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\nimport {Statuses} from './statuses';\n\nconst Promise = Dexie.Promise;\n\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\n const enqueue = initEnqueue(db);\n var hasMoreToGive = {hasMoreToGive: true};\n\n function stillAlive() {\n // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead\n // because the new instance should be considered a fresh instance and will have another local node.\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\n }\n\n return function connectProtocol(node, activePeer) {\n /// \n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\n\n const url = activePeer.url;\n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save().then(()=> {\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\n }).catch('DatabaseClosedError', ()=> {\n });\n }\n }\n\n activePeer.on('disconnect', function (newStatus) {\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\n });\n\n var connectedContinuation;\n changeStatusTo(Statuses.CONNECTING);\n return doSync();\n\n function doSync() {\n // Use enqueue() to ensure only a single promise execution at a time.\n return enqueue(doSync, function () {\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\n return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider);\n }, dbAliveID);\n }\n\n function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\n var finalSyncPromise = new Promise(function (resolve, reject) {\n rejectConnectPromise.p = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(\n node.syncContext,\n url,\n options,\n remoteBaseRevision,\n node.appliedRemoteRevision,\n changes,\n partial,\n applyRemoteChanges,\n onChangesAccepted,\n function (continuation) {\n resolve(continuation);\n },\n onError);\n } catch (ex) {\n onError(ex, Infinity);\n }\n\n function onError(error, again) {\n reject(error);\n if (stillAlive()) {\n if (!isNaN(again) && again < Infinity) {\n setTimeout(function () {\n if (stillAlive()) {\n changeStatusTo(Statuses.SYNCING);\n doSync().catch('DatabaseClosedError', abortTheProvider);\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\n connectedContinuation = null;\n } else {\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\n }\n }\n }\n });\n });\n\n return finalSyncPromise.then(function () {\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\n return undefined;\n }).finally(()=> {\n // In case error happens after connect, don't try reject the connect promise anymore.\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\n // is active and this happens. It would fire unhandledrejection but that we do not want.\n rejectConnectPromise.p = null;\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\n // otherwise it will execute when finalSyncPromise resolves.\n finalSyncPromise.then(continueSendingChanges);\n return node.save();\n }\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\n }\n\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\n\n return enqueue(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\n .catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) { // Database was closed.\n if (continuation.disconnect)\n continuation.disconnect();\n return;\n }\n\n connectedContinuation = continuation;\n activePeer.on('disconnect', function () {\n if (connectedContinuation) {\n if (connectedContinuation.react) {\n try {\n // react pattern must provide a disconnect function.\n connectedContinuation.disconnect();\n } catch (e) {\n }\n }\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\n }\n });\n\n if (continuation.react) {\n continueUsingReactPattern(continuation);\n } else {\n continueUsingPollPattern(continuation);\n }\n }\n\n // React Pattern (eager)\n function continueUsingReactPattern(continuation) {\n var changesWaiting, // Boolean\n isWaitingForServer; // Boolean\n\n\n function onChanges() {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n if (isWaitingForServer)\n changesWaiting = true;\n else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\n activePeer.on('disconnect', function () {\n db.on.changes.unsubscribe(onChanges);\n });\n\n function reactToChanges() {\n if (!connectedContinuation) return;\n changesWaiting = false;\n isWaitingForServer = true;\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (!connectedContinuation) return;\n if (changes.length > 0) {\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n // More changes may be waiting:\n reactToChanges();\n });\n } else {\n isWaitingForServer = false;\n if (changesWaiting) {\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\n reactToChanges();\n } else {\n changeStatusTo(Statuses.ONLINE);\n }\n }\n }).catch(ex => {\n console.error(`Got ${ex.message} caught by reactToChanges`);\n abortTheProvider(ex);\n });\n }\n\n reactToChanges();\n }\n\n // Poll Pattern\n function continueUsingPollPattern() {\n\n function syncAgain() {\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n }\n\n function onSuccess(continuation) {\n if (!connectedContinuation) {\n // Got disconnected before succeeding. Quit.\n return;\n }\n connectedContinuation = continuation;\n if (partial) {\n // We only sent partial changes. Need to do another round asap.\n syncAgain();\n } else {\n // We've sent all changes now (in sync!)\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\n // Provider wants to keep polling. Set Status to ONLINE.\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, continuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n }\n\n function onError(error, again) {\n if (!isNaN(again) && again < Infinity) {\n if (connectedContinuation) {\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\n } // else status is already changed since we got disconnected.\n } else {\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\n }\n }\n }).catch(abortTheProvider);\n }\n\n if (hasMoreToGive.hasMoreToGive) {\n syncAgain();\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, connectedContinuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n };\n}\n","import Dexie from 'dexie';\n\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\nimport initConnectProtocol from './connect-protocol';\nimport {Statuses} from './statuses';\n\nexport default function initConnectFn(db, activePeers) {\n return function connect(protocolInstance, protocolName, url, options, dbAliveID) {\n /// \n var existingPeer = activePeers.filter(function (peer) {\n return peer.url === url;\n });\n if (existingPeer.length > 0) {\n const activePeer = existingPeer[0];\n const diffObject = {};\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\n // Options have been changed\n // We need to disconnect and reconnect\n if (Object.keys(diffObject).length !== 0) {\n return db.syncable.disconnect(url)\n .then(() => {\n return execConnect();\n })\n } else {\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\n // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly.\n return existingPeer[0].connectPromise;\n }\n }\n\n function execConnect() {\n // Use an object otherwise we wouldn't be able to get the reject promise from\n // connectProtocol\n var rejectConnectPromise = {p: null};\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node, activePeer);\n });\n\n var disconnected = false;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n syncOptions: options,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n }\n\n return execConnect();\n };\n}\n","/* ========================================================================== \n * dexie-syncable.js\n * ==========================================================================\n *\n * Dexie addon for syncing indexedDB with remote endpoints.\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\n\nimport Dexie from \"dexie\";\n// Depend on 'dexie-observable'\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\n// That way, our plugin works in all UMD cases.\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\nimport \"dexie-observable\";\n\nimport initSyncableConnect from './syncable-connect';\nimport initConnectFn from './connect-fn';\nimport {Statuses, StatusTexts} from './statuses';\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n Observable = Dexie.Observable;\n\nexport default function Syncable (db) {\n /// \n\n var activePeers = [];\n\n const connectFn = initConnectFn(db, activePeers);\n const syncableConnect = initSyncableConnect(db, connectFn);\n\n db.on('message', function(msg) {\n // Message from other local node arrives...\n Dexie.vip(function() {\n if (msg.type === 'connect') {\n // We are master node and another non-master node wants us to do the connect.\n db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject);\n } else if (msg.type === 'syncStatusChanged') {\n // We are client and a master node informs us about syncStatus change.\n // Lookup the connectedProvider and call its event\n db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url);\n }\n });\n });\n\n db.on('cleanup', function(weBecameMaster) {\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\n if (weBecameMaster) {\n // We took over the master role in Observable's cleanup method.\n // We should connect to remote servers now.\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\n // connection has been closed. The new master would then be expected to reconnect.\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\n // an old closed one. \n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\n return db._syncNodes.where({type: 'remote'})\n .filter(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\n })\n )));\n })).catch('DatabaseClosedError', ()=>{});\n }\n });\n\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\n // when the database opens. It will not wait for the connection to complete, just initiate the\n // connection so that it will continue syncing as long as the database is open.\n\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\n db.on('ready', function onReady() {\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\n // This \"ready\" subscriber will never be the one performing the initial sync request, because\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\n // called after this one. There, in that subscriber, the initial sync request will take place\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\n // next time this database is opened.\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\n // once in the past for each \"connectedRemoteNode\" we find in query below.\n\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\n db._syncNodes\n .where('type').equals('remote')\n .and(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => {\n // There are connected remote nodes that we must manage (or take over to manage)\n connectedRemoteNodes.forEach(\n node => db.syncable.connect(\n node.syncProtocol,\n node.url,\n node.syncOptions) \n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\n );\n }).catch('DatabaseClosedError', ()=>{});\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\n\n db.syncable = {};\n\n db.syncable.getStatus = function(url, cb) {\n if (db.isOpen()) {\n return Dexie.vip(function() {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node ? node.status : Statuses.OFFLINE;\n });\n }).then(cb);\n } else {\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\n }\n };\n\n db.syncable.getOptions = function(url, cb) {\n return db.transaction('r?', db._syncNodes, () => {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node.syncOptions;\n }).then(cb);\n });\n };\n\n db.syncable.list = function() {\n return db.transaction('r?', db._syncNodes, ()=>{\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\n return a.map(function(node) { return node.url; });\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function(url) {\n return Dexie.ignoreTransaction(()=>{\n return Promise.resolve().then(()=>{\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\n return peer.disconnect(Statuses.OFFLINE);\n }));\n } else {\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\n });\n }\n }).then(()=>{\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\n node.status = Statuses.OFFLINE;\n });\n });\n });\n };\n\n db.syncable.connect = function(protocolName, url, options) {\n options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined.\n var protocolInstance = Syncable.registeredProtocols[protocolName];\n if (protocolInstance) {\n return syncableConnect(protocolInstance, protocolName, url, options);\n } else {\n return Promise.reject(\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\n );\n }\n };\n\n db.syncable.delete = function(url) {\n return db.syncable.disconnect(url).then(()=>{\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\n // Find the node(s)\n // Several can be found, as detected by @martindiphoorn,\n // let's delete them and cleanup _uncommittedChanges and _changes \n // accordingly.\n let nodeIDsToDelete;\n return db._syncNodes\n .where(\"url\").equals(url)\n .toArray(nodes => nodes.map(node => node.id))\n .then(nodeIDs => {\n nodeIDsToDelete = nodeIDs;\n // Delete the syncNode that represents the remote endpoint.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\n })\n .then (() =>\n // In case there were uncommittedChanges belonging to this, delete them as well\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\n }).then(()=> {\n // Spawn background job to delete old changes, now that a node has been deleted,\n // there might be changes in _changes table that is not needed to keep anymore.\n // This is done in its own transaction, or possible several transaction to prohibit\n // starvation\n Observable.deleteOldChanges(db);\n });\n });\n };\n\n db.syncable.unsyncedChanges = function(url) {\n return db._syncNodes.where(\"url\").equals(url).first(function(node) {\n return db._changes.where('rev').above(node.myRevision).toArray();\n });\n };\n\n db.close = override(db.close, function(origClose) {\n return function() {\n activePeers.forEach(function(peer) {\n peer.disconnect();\n });\n return origClose.apply(this, arguments);\n };\n });\n\n Object.defineProperty(\n db.observable.SyncNode.prototype,\n 'save', {\n enumerable: false,\n configurable: true,\n writable: true,\n value() {\n return db.transaction('rw?', db._syncNodes, () => {\n return db._syncNodes.put(this);\n });\n }\n });\n}\n\nSyncable.Statuses = Statuses;\n\nSyncable.StatusTexts = StatusTexts;\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\n /// \n /// Register a synchronization protocol that can synchronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n const partialsThreshold = protocolInstance.partialsThreshold;\n if (typeof partialsThreshold === 'number') {\n // Don't allow NaN or negative threshold\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\n throw new Error('The given number for the threshold is not supported');\n }\n // If the threshold is 0 we will not send any client changes but will get server changes\n } else {\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\n protocolInstance.partialsThreshold = Infinity;\n }\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Syncable;\nDexie.addons.push(Syncable);\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,SAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AAE9B,6BAA4C,EAAE,EAAE,OAAO;IACrD,OAAO,yBAAyB,gBAAgB,EAAE,YAAY,EAAE,GAAG,EAAE,OAAO;QAC1E,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE;;YAEf,IAAI,CAAC,EAAE,CAAC,cAAc;gBACpB,MAAM,IAAI,KAAK,CAAC,wFAAwF,CAAC,CAAC;YAE5G,IAAI,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE;;gBAE9B,OAAO,OAAO,CAAC,gBAAgB,EAAE,YAAY,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC;aACpF;iBAAM;;;gBAGL,OAAO,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,UAAU;;oBAEjF,OAAO,EAAE,CAAC,UA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AAE,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,EAAE;gBACxC,OAAO,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,KAAI,CAAC,CAAC;aACtC,CAAC,CAAC;SACN;KACH,CAAC,CAAC;CACP;AAED,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAE7B,QAAQ,CAAC,WAAW,GAAG,WAAW,CAAC;AAEnC,QAAQ,CAAC,mBAAmB,GAAG,EAAE,CAAC;AAElC,QAAQ,CAAC,oBAAoB,GAAG,UAAS,IAAI,EAAE,gBAAgB;;;;;;IAM3D,IAAM,iBAAiB,GAAG,gBAAgB,CAAC,iBAAiB,CAAC;IAC7D,IAAI,OAAO,iBAAiB,KAAK,QAAQ,EAAE;;QAEvC,IAAI,KAAK,CAAC,iBAAiB,CAAC,IAAI,iBAAiB,GAAG,CAAC,EAAE;YACnD,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;SAC1E;;KAEJ;SAAM;;QAEH,gBAAgB,CAAC,iBAAiB,GAAG,QAAQ,CAAC;KACjD;IACD,QAAQ,CAAC,mBAAmB,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC;CACzD,CAAC;;AAGF,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC1B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;;;;"} \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.min.js b/addons/Dexie.Syncable/dist/dexie-syncable.min.js new file mode 100644 index 000000000..3ac2057ae --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n(require("dexie"),require("dexie-observable")):"function"==typeof define&&define.amd?define(["dexie","dexie-observable"],n):(e.Dexie=e.Dexie||{},e.Dexie.Syncable=n(e.Dexie))}(this,function(e){"use strict";function n(n,t){return function(r,o,i,c){if(n.isOpen()){if(!n._localSyncNode)throw new Error("Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!");return n._localSyncNode.isMaster?t(r,o,i,c,n._localSyncNode.id):n.table("_syncNodes").where("isMaster").above(0).first(function(e){return n.observable.sendMessage("connect",{protocolName:o,url:i,options:c},e.id,{wantReply:!0})})}return n.hasBeenClosed()?N.reject(new e.DatabaseClosedError):n.hasFailed()?N.reject(new e.InvalidStateError("Dexie.Syncable: Cannot connect. Database has failed to open")):new N(function(t,r){n.on("ready",function(){return n._syncNodes.get({url:i},function(e){var a=n.syncable.connect(o,i,c);if(a.then(t,r),!e||!e.appliedRemoteRevision)return a})}),n.open().catch(function(n){r(new e.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open",n))})})}}function t(n){return function(){function t(n,t){this.nodeID=n,t&&e.extend(this,t)}return t.prototype.save=function(){return e.vip(function(){return n.save()})},t}()}function r(n,r,o){return function(i){return n.transaction("rw",n._syncNodes,n._changes,function(){if(!o)throw new Error("Url cannot be empty");return n._syncNodes.where("url").equalsIgnoreCase(o).first(function(c){if(c){var a=t(c);c.syncContext=new a(c.id,c.syncContext),c.syncProtocol=r,c.syncOptions=i,n._syncNodes.put(c)}else{c=new n.observable.SyncNode,c.myRevision=-1,c.appliedRemoteRevision=null,c.remoteBaseRevisions=[],c.type="remote",c.syncProtocol=r,c.url=o,c.syncOptions=i,c.lastHeartBeat=Date.now(),c.dbUploadState=null;var s=t(c);e.Promise.resolve(function(){if(!1===i.initialUpload)return n._changes.toCollection().lastKey(function(e){c.myRevision=e})}()).then(function(){n._syncNodes.add(c).then(function(e){c.syncContext=new s(e),n._syncNodes.put(c)})})}return c})})}}function o(n){return function t(r,o,i){function c(){return r.ongoingOperation?r.ongoingOperation=r.ongoingOperation.then(function(){return t(r,o,i)}):r.ongoingOperation=e.ignoreTransaction(function(){return e.vip(function(){return o()})}).finally(function(){delete r.ongoingOperation}),r.ongoingOperation}return i?n._localSyncNode&&i===n._localSyncNode.id?c():e.Promise.reject(new e.DatabaseClosedError):n.isOpen()?c():e.Promise.reject(new e.DatabaseClosedError)}}function i(e,n){return function(t,r){return e.transaction("rw!",e._uncommittedChanges,function(){return e._uncommittedChanges.bulkAdd(t.map(function(e){var t={node:n.id,type:e.type,table:e.table,key:e.key};return e.obj&&(t.obj=e.obj),e.mods&&(t.mods=e.mods),t}))}).then(function(){return n.appliedRemoteRevision=r,n.save()})}}function c(n,t){var r=t.map(function(e){return e.key}),o={};return n.where(":id").anyOf(r).raw().each(function(e,n){o[n.primaryKey+""]=e}).then(function(){var r=t.filter(function(e){return o.hasOwnProperty(e.key+"")}),i=r.map(function(n){var t=o[n.key+""];return Object.keys(n.mods).forEach(function(r){e.setByKeyPath(t,r,n.mods[r])}),t});return n.bulkPut(i)})}function a(e){return function(n){var t={};n.forEach(function(e){t.hasOwnProperty(e.table)||(t[e.table]=(n={},n[g]=[],n[O]=[],n[R]=[],n)),t[e.table][e.type].push(e);var n});var r=Object.keys(t),o=r.map(function(n){return e.table(n)});return e.transaction("rw",o,function(){r.forEach(function(n){var r=e.table(n),o=!r.schema.primKey.keyPath,i=t[n][g],a=t[n][O],s=t[n][R];i.length>0&&r.bulkPut(i.map(function(e){return e.obj}),o?i.map(function(e){return e.key}):void 0),s.length>0&&c(r,s),a.length>0&&r.bulkDelete(a.map(function(e){return e.key}))})})}}function s(n,t){var r=a(n);return function(o,i){var c=n.tables.filter(function(e){return"_changes"===e.name||"_uncommittedChanges"===e.name||e.schema.observable});return n.transaction("rw!",c,function(){var c=e.currentTransaction,a=0;return n._changes.orderBy("rev").last(function(e){a=e&&e.rev||0}).then(function(){return c.source=t.id,n._uncommittedChanges.where("node").equals(t.id).toArray()}).then(function(e){return r(e)}).then(function(){return n._uncommittedChanges.where("node").equals(t.id).delete()}).then(function(){return r(o)}).then(function(){return n._changes.orderBy("rev").last()}).then(function(e){var n=e&&e.rev||0;if(t.appliedRemoteRevision=i,t.remoteBaseRevisions.push({remote:i,local:n}),t.myRevision===a&&(t.myRevision=n),t.remoteBaseRevisions.length>1)for(var r=t.remoteBaseRevisions.length-1;r>0;--r)if(t.myRevision>=t.remoteBaseRevisions[r].local){t.remoteBaseRevisions.splice(0,r);break}t.save().catch(function(e){console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: "+(e.stack||e))})})})}}function u(e){if(0===e.remoteBaseRevisions.length)return{maxClientRevision:1/0,remoteBaseRevision:null};for(var n=e.remoteBaseRevisions.length-1;n>=0;--n)if(e.myRevision>=e.remoteBaseRevisions[n].local)return{maxClientRevision:n===e.remoteBaseRevisions.length-1?1/0:e.remoteBaseRevisions[n+1].local,remoteBaseRevision:e.remoteBaseRevisions[n].remote};return{maxClientRevision:e.remoteBaseRevisions[0].local,remoteBaseRevision:null}}function l(n,t){var r=e.deepClone(n);return Object.keys(t.mods).forEach(function(n){e.setByKeyPath(r.obj,n,t.mods[n])}),r}function f(n,t){var r=e.deepClone(n);return Object.keys(t.mods).forEach(function(o){var i=!1;Object.keys(n.mods).filter(function(e){return 0===o.indexOf(e+".")}).forEach(function(n){e.setByKeyPath(r.mods[n],o.substr(n.length+1),t.mods[o]),i=!0}),i||(r.mods[o]=t.mods[o]),Object.keys(n.mods).filter(function(e){return 0===e.indexOf(o+".")}).forEach(function(e){delete r.mods[e]})}),r}function d(e,n){switch(e.type){case g:switch(n.type){case g:return n;case R:return l(e,n);case O:return n}break;case R:switch(n.type){case g:return n;case R:return f(e,n);case O:return n}break;case O:switch(n.type){case g:return n;case R:case O:return e}}}function y(e,n,t){return function(r,o,i,c){var a={},s=0,u=!1,l=n.id,f=r;return e.transaction("r",e._changes,function(){return e._changes.where("rev").between(r,i,!1,!0).until(function(){if(s===o)return u=!0,!0}).each(function(e){if(f=e.rev,e.source!==l){var n={type:e.type,table:e.table,key:e.key};e.type===g?n.obj=e.obj:e.type===R&&(n.mods=e.mods);var t=e.table+":"+e.key,r=a[t];if(r){var o=n,i=d(r,o);a[t]=i}else a[t]=n,++s}})}).then(function(){var e=Object.keys(a).map(function(e){return a[e]});return t.hasMoreToGive=u,c(e,u,{myRevision:f})})}}function h(e,n,t,r,o,i){return function c(a,s,l){var f=!1;return l.until(function(){if(s.length===t)return f=!0,!0}).each(function(e,n){s.push({type:g,table:a.currentTable,key:n.key,obj:n.value}),a.currentKey=n.key}).then(function(){if(f)return o.hasMoreToGive=!0,i(s,null,!0,{dbUploadState:a});if(0===a.tablesToUpload.length){var l=u(n);return r(a.localBaseRevision,t-s.length,l.maxClientRevision,function(e,n,t){return s=s.concat(e),t.dbUploadState=null,i(s,l.remoteBaseRevision,n,t)})}return a.currentTable=a.tablesToUpload.shift(),c(a,s,e.table(a.currentTable).orderBy(":id"))})}}function v(n,t,r){var o=r;return function(r,i){var c=y(n,r,t),a=h(n,r,o,c,t,i);if(r.myRevision>=0){var s=u(r);return c(r.myRevision,o,s.maxClientRevision,function(e,n,t){return i(e,s.remoteBaseRevision,n,t)})}if(null===r.dbUploadState){var l=n.tables.filter(function(e){return e.schema.observable}).map(function(e){return e.name});if(0===l.length)return e.Promise.resolve(i([],null,!1,{}));var f={tablesToUpload:l,currentTable:l.shift(),currentKey:null};return n._changes.orderBy("rev").last(function(e){f.localBaseRevision=e&&e.rev||0;var t=n.table(f.currentTable).orderBy(":id");return a(f,[],t)})}if(r.dbUploadState.currentKey){var d=n.table(r.dbUploadState.currentTable).where(":id").above(r.dbUploadState.currentKey);return a(e.deepClone(r.dbUploadState),[],d)}var d=n.table(f.currentTable).orderBy(":id");return a(e.deepClone(r.dbUploadState),[],d)}}function b(n,t,r,c,a){function u(){return n._localSyncNode&&n._localSyncNode.id===r}var l=o(n),f={hasMoreToGive:!0};return function(o,d){function y(e){o.status!==e&&(o.status=e,o.save().then(function(){n.syncable.on.statusChanged.fire(e,_),n.observable.broadcastMessage("syncStatusChanged",{newStatus:e,url:_},!1)}).catch("DatabaseClosedError",function(){}))}function h(){return l(h,function(){return m(o,b)},r)}function b(n,r,i,s){function l(){return Object.keys(s).forEach(function(n){e.setByKeyPath(o,n,s[n])}),f.then(g),o.save()}var f=new C(function(s,f){a.p=function(e){f(e)},e.asap(function(){function e(e,n){f(e),u()&&(!isNaN(n)&&n<1/0?(setTimeout(function(){u()&&(y(E.SYNCING),h().catch("DatabaseClosedError",p))},n),y(E.ERROR_WILL_RETRY,e),S&&S.disconnect&&S.disconnect(),S=null):p(e))}try{t.sync(o.syncContext,_,c,r,o.appliedRemoteRevision,n,i,N,l,function(e){s(e)},e)}catch(n){e(n,1/0)}})});return f.then(function(){}).finally(function(){a.p=null})}function p(e){d.disconnect(E.ERROR,e)}function m(n,t){return w(n,function r(o,i,c,a){return 0===o.length&&"myRevision"in a&&a.myRevision!==n.myRevision?(Object.keys(a).forEach(function(t){e.setByKeyPath(n,t,a[t])}),n.save().catch("DatabaseClosedError",function(){}),w(n,r)):t(o,i,c,a)})}function N(t,c,a){var f=i(n,o),d=s(n,o);return l(N,function(){return u()?(a?f(t,c):d(t,c)).catch(function(e){return p(e),C.reject(e)}):C.reject(new e.DatabaseClosedError)},r)}function g(e){if(!u())return void(e.disconnect&&e.disconnect());S=e,d.on("disconnect",function(){if(S){if(S.react)try{S.disconnect()}catch(e){}S=null}}),e.react?R(e):O()}function R(t){function r(){S&&(y(E.SYNCING),a?c=!0:i())}function i(){S&&(c=!1,a=!0,m(o,function(n,r,s,u){S&&(n.length>0?t.react(n,r,s,function(){Object.keys(u).forEach(function(n){e.setByKeyPath(o,n,u[n])}),o.save().catch("DatabaseClosedError",function(){}),i()}):(a=!1,c?i():y(E.ONLINE)))}).catch(function(e){console.error("Got "+e.message+" caught by reactToChanges"),p(e)}))}var c,a;n.on("changes",r),d.on("disconnect",function(){n.on.changes.unsubscribe(r)}),i()}function O(){function n(){m(o,function(r,i,a,s){function u(){Object.keys(s).forEach(function(n){e.setByKeyPath(o,n,s[n])}),o.save().catch("DatabaseClosedError",function(){})}function l(e){S&&(S=e,a?n():!isNaN(e.again)&&e.again<1/0?(y(E.ONLINE),setTimeout(function(){S&&(y(E.SYNCING),n())},e.again)):d.disconnect(E.OFFLINE))}function f(e,t){!isNaN(t)&&t<1/0?S&&(setTimeout(function(){S&&(y(E.SYNCING),n())},t),y(E.ERROR_WILL_RETRY)):p(e)}t.sync(o.syncContext,_,c,i,o.appliedRemoteRevision,r,a,N,u,l,f)}).catch(p)}f.hasMoreToGive?n():S&&!isNaN(S.again)&&S.again<1/0?(y(E.ONLINE),setTimeout(function(){S&&(y(E.SYNCING),n())},S.again)):d.disconnect(E.OFFLINE)}var w=v(n,f,t.partialsThreshold),_=d.url;d.on("disconnect",function(e){isNaN(e)||y(e)});var S;return y(E.CONNECTING),h()}}function p(n,t){return function(o,i,c,a,s){function u(){var u={p:null},l=b(n,o,s,a,u),f=r(n,i,c),d=f(a).then(function(e){return l(e,h)}),y=!1,h={url:c,status:E.OFFLINE,connectPromise:d,syncOptions:a,on:e.Events(null,"disconnect"),disconnect:function(e,n){var r=t.indexOf(h);r>=0&&t.splice(r,1),n&&u.p&&u.p(n),y||h.on.disconnect.fire(e,n),y=!0}};return t.push(h),d}var l=t.filter(function(e){return e.url===c});if(l.length>0){var f=l[0],d={};return e.getObjectDiff(f.syncOptions,a,d),0!==Object.keys(d).length?n.syncable.disconnect(c).then(function(){return u()}):l[0].connectPromise}return u()}}function m(t){var r=[],o=p(t,r),i=n(t,o);t.on("message",function(n){e.vip(function(){"connect"===n.type?t.syncable.connect(n.message.protocolName,n.message.url,n.message.options).then(n.resolve,n.reject):"disconnect"===n.type?t.syncable.disconnect(n.message.url).then(n.resolve,n.reject):"syncStatusChanged"===n.type&&t.syncable.on.statusChanged.fire(n.message.newStatus,n.message.url)})}),t.on("cleanup",function(n){n&&e.ignoreTransaction(function(){return e.vip(function(){return t._syncNodes.where({type:"remote"}).filter(function(e){return e.status!==E.OFFLINE}).toArray(function(e){return S.all(e.map(function(e){return t.syncable.connect(e.syncProtocol,e.url,e.syncOptions).catch(function(n){console.warn("Dexie.Syncable: Could not connect to "+e.url+". "+(n.stack||n))})}))})})}).catch("DatabaseClosedError",function(){})}),t.on("ready",function(){t._localSyncNode&&t._localSyncNode.isMaster&&t._syncNodes.where("type").equals("remote").and(function(e){return e.status!==E.OFFLINE}).toArray(function(e){e.forEach(function(e){return t.syncable.connect(e.syncProtocol,e.url,e.syncOptions).catch(function(){})})}).catch("DatabaseClosedError",function(){})},!0),t.syncable={},t.syncable.getStatus=function(n,r){return t.isOpen()?e.vip(function(){return t._syncNodes.where("url").equals(n).first(function(e){return e?e.status:E.OFFLINE})}).then(r):S.resolve(m.Statuses.OFFLINE).then(r)},t.syncable.getOptions=function(e,n){return t.transaction("r?",t._syncNodes,function(){return t._syncNodes.where("url").equals(e).first(function(e){return e.syncOptions}).then(n)})},t.syncable.list=function(){return t.transaction("r?",t._syncNodes,function(){return t._syncNodes.where("type").equals("remote").toArray(function(e){return e.map(function(e){return e.url})})})},t.syncable.on=e.Events(t,{statusChanged:"asap"}),t.syncable.disconnect=function(n){return e.ignoreTransaction(function(){return S.resolve().then(function(){return t._localSyncNode&&t._localSyncNode.isMaster?S.all(r.filter(function(e){return e.url===n}).map(function(e){return e.disconnect(E.OFFLINE)})):t._syncNodes.where("isMaster").above(0).first(function(e){return t.observable.sendMessage("disconnect",{url:n},e.id,{wantReply:!0})})}).then(function(){return t._syncNodes.where("url").equals(n).modify(function(e){e.status=E.OFFLINE})})})},t.syncable.connect=function(e,n,t){t=t||{};var r=m.registeredProtocols[e];return r?i(r,e,n,t):S.reject(new Error("ISyncProtocol '"+e+"' is not registered in Dexie.Syncable.registerSyncProtocol()"))},t.syncable.delete=function(e){return t.syncable.disconnect(e).then(function(){return t.transaction("rw!",t._syncNodes,t._changes,t._uncommittedChanges,function(){var n;return t._syncNodes.where("url").equals(e).toArray(function(e){return e.map(function(e){return e.id})}).then(function(e){return n=e,t._syncNodes.where("id").anyOf(e).delete()}).then(function(){return t._uncommittedChanges.where("node").anyOf(n).delete()})}).then(function(){k.deleteOldChanges(t)})})},t.syncable.unsyncedChanges=function(e){return t._syncNodes.where("url").equals(e).first(function(e){return t._changes.where("rev").above(e.myRevision).toArray()})},t.close=_(t.close,function(e){return function(){return r.forEach(function(e){e.disconnect()}),e.apply(this,arguments)}}),Object.defineProperty(t.observable.SyncNode.prototype,"save",{enumerable:!1,configurable:!0,writable:!0,value:function(){var e=this;return t.transaction("rw?",t._syncNodes,function(){return t._syncNodes.put(e)})}})}e="default"in e?e.default:e;var N=e.Promise,g=1,R=2,O=3,E={ERROR:-1,OFFLINE:0,CONNECTING:1,ONLINE:2,SYNCING:3,ERROR_WILL_RETRY:4},w={"-1":"ERROR",0:"OFFLINE",1:"CONNECTING",2:"ONLINE",3:"SYNCING",4:"ERROR_WILL_RETRY"},C=e.Promise,_=e.override,S=e.Promise,k=e.Observable;return m.Statuses=E,m.StatusTexts=w,m.registeredProtocols={},m.registerSyncProtocol=function(e,n){var t=n.partialsThreshold;if("number"==typeof t){if(isNaN(t)||t<0)throw new Error("The given number for the threshold is not supported")}else n.partialsThreshold=1/0;m.registeredProtocols[e]=n},e.Syncable=m,e.addons.push(m),m}); +//# sourceMappingURL=dist/dexie-syncable.min.js.map \ No newline at end of file diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.min.js.map b/addons/Dexie.Syncable/dist/dexie-syncable.min.js.map new file mode 100644 index 000000000..ff15a7081 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/syncable-connect.js","../src/PersistedContext.js","../src/get-or-create-sync-node.js","../src/enqueue.js","../src/save-to-uncommitted-changes.js","../src/bulk-update.js","../src/apply-changes.js","../src/finally-commit-all-changes.js","../src/get-local-changes-for-node/get-base-revision-and-max-client-revision.js","../src/combine-create-and-update.js","../src/combine-update-and-update.js","../src/merge-change.js","../src/get-local-changes-for-node/get-changes-since-revision.js","../src/get-local-changes-for-node/get-table-objects-as-changes.js","../src/get-local-changes-for-node/get-local-changes-for-node.js","../src/connect-protocol.js","../src/connect-fn.js","../src/Dexie.Syncable.js","../src/change_types.js","../src/statuses.js"],"names":["initSyncableConnect","db","connect","protocolInstance","protocolName","url","options","isOpen","_localSyncNode","Error","isMaster","id","table","where","above","first","masterNode","observable","sendMessage","wantReply","hasBeenClosed","Promise","reject","Dexie","DatabaseClosedError","hasFailed","InvalidStateError","resolve","on","_syncNodes","get","node","connectPromise","syncable","then","appliedRemoteRevision","open","catch","ex","PersistedContext","nodeID","otherProps","this","extend","prototype","save","vip","transaction","_changes","equalsIgnoreCase","initPersistedContext","syncContext","syncProtocol","syncOptions","put","SyncNode","myRevision","remoteBaseRevisions","type","lastHeartBeat","Date","now","dbUploadState","PersistedContext_1","initialUpload","toCollection","lastKey","currentRevision","add","enqueue","context","fn","instanceID","_enqueue","ongoingOperation","ignoreTransaction","finally","changes","remoteRevision","_uncommittedChanges","bulkAdd","map","change","changeWithNodeId","key","obj","mods","keys","c","anyOf","raw","each","cursor","primaryKey","updatesThatApply","filter","hasOwnProperty","objsToPut","curr","Object","forEach","keyPath","setByKeyPath","bulkPut","collectedChanges","_a","CREATE","DELETE","UPDATE","push","table_names","tables","table_name","specifyKeys","schema","primKey","createChangesToApply","deleteChangesToApply","updateChangesToApply","length","undefined","bulkUpdate","bulkDelete","applyChanges","initApplyChanges","tablesToIncludeInTrans","name","trans","currentTransaction","localRevisionBeforeChanges","orderBy","last","lastChange","rev","source","equals","toArray","uncommittedChanges","delete","currentLocalRevision","remote","local","i","splice","err","console","warn","stack","maxClientRevision","Infinity","remoteBaseRevision","prevChange","nextChange","clonedChange","deepClone","hadParentPath","parentPath","indexOf","substr","subPath","combineCreateAndUpdate","combineUpdateAndUpdate","hasMoreToGive","revision","maxChanges","maxRevision","cb","changeSet","numChanges","partial","ignoreSource","nextRevision","between","until","changeToSend","mergedChange","mergeChange","MAX_CHANGES_PER_CHUNK","getChangesSinceRevision","getTableObjectsAsChanges","state","collection","limitReached","item","currentTable","value","currentKey","tablesToUpload","brmcr","getBaseRevisionAndMaxClientRevision","localBaseRevision","additionalChanges","nodeModificationsOnAck","concat","shift","partialsThreshold","initGetChangesSinceRevision","initGetTableObjectsAsChanges","initConnectProtocol","dbAliveID","rejectConnectPromise","stillAlive","initEnqueue","activePeer","changeStatusTo","newStatus","status","statusChanged","fire","broadcastMessage","doSync","getLocalChangesForNode_autoAckIfEmpty","sendChangesToProvider","onChangesAccepted","finalSyncPromise","continueSendingChanges","p","asap","onError","error","again","isNaN","setTimeout","Statuses","SYNCING","abortTheProvider","ERROR_WILL_RETRY","connectedContinuation","disconnect","sync","applyRemoteChanges","continuation","ERROR","getLocalChangesForNode","autoAck","remoteChanges","saveToUncommittedChanges","initSaveToUncommittedChanges","finallyCommitAllChanges","initFinallyCommitAllChanges","react","e","continueUsingReactPattern","continueUsingPollPattern","onChanges","isWaitingForServer","changesWaiting","reactToChanges","ONLINE","message","unsubscribe","syncAgain","onSuccess","OFFLINE","initGetLocalChangesForNode","CONNECTING","activePeers","execConnect","connectProtocol","getOrCreateSyncNode","initGetOrCreateSyncNode","disconnected","Events","pos","existingPeer","peer","diffObject","getObjectDiff","Syncable","connectFn","initConnectFn","syncableConnect","msg","weBecameMaster","connectedRemoteNodes","all","and","getStatus","getOptions","list","a","modify","registeredProtocols","nodeIDsToDelete","nodes","nodeIDs","Observable","deleteOldChanges","unsyncedChanges","close","override","origClose","apply","arguments","defineProperty","enumerable","configurable","writable","_this","StatusTexts","-1","0","1","2","3","4","registerSyncProtocol","addons"],"mappings":"gSAIA,SAAAA,GAA4CC,EAAIC,GAC9C,MAAO,UAAyBC,EAAkBC,EAAcC,EAAKC,GACnE,GAAIL,EAAGM,SAAU,CAEf,IAAKN,EAAGO,eACN,KAAM,IAAIC,OAAM,yFAElB,OAAIR,GAAGO,eAAeE,SAEbR,EAAQC,EAAkBC,EAAcC,EAAKC,EAASL,EAAGO,eAAeG,IAIxEV,EAAGW,MAAM,cAAcC,MAAM,YAAYC,MAAM,GAAGC,MAAM,SAAUC,GAEvE,MAAOf,GAAGgB,WAAWC,YAAY,WAC/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AS,EACTD,EAAS,ECHToH,GACXS,OAAQ,EACRqB,QAAS,EACTE,WAAY,EACZP,OAAQ,EACRxB,QAAS,EACTE,iBAAkB,GAGPyE,GACXC,KAAM,QACNC,EAAK,UACLC,EAAK,aACLC,EAAK,SACLC,EAAK,UACLC,EAAK,oBJPD5R,EAAUE,EAAMF,QEsBlB6Q,EAAW3Q,EAAM2Q,SACjB7Q,EAAUE,EAAMF,QAChByQ,EAAavQ,EAAMuQ,iBA8MvBlB,GAAS7C,SAAWA,EAEpB6C,EAAS+B,YAAcA,EAEvB/B,EAASc,uBAETd,EAASsC,qBAAuB,SAASpL,EAAM3H,GAM3C,GAAMgM,GAAoBhM,EAAiBgM,iBAC3C,IAAiC,gBAAtBA,IAEP,GAAI0B,MAAM1B,IAAsBA,EAAoB,EAChD,KAAM,IAAI1L,OAAM,2DAKpBN,GAAiBgM,kBAAoB9C,EAAAA,CAEzCuH,GAASc,oBAAoB5J,GAAQ3H,GAIzCoB,EAAMqP,SAAWA,EACjBrP,EAAM4R,OAAOtM,KAAK+J","file":"dist/dexie-syncable.min.js","sourcesContent":["import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initSyncableConnect(db, connect) {\n return function syncableConnect(protocolInstance, protocolName, url, options) {\n if (db.isOpen()) {\n // Database is open\n if (!db._localSyncNode)\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\n\n if (db._localSyncNode.isMaster) {\n // We are master node\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\n } else {\n // We are not master node\n // Request master node to do the connect:\n return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\n // There will always be a master node. In theory we may self have become master node when we come here. But that's ok. We'll request ourselves.\n return db.observable.sendMessage('connect', {\n protocolName: protocolName,\n url: url,\n options: options\n }, masterNode.id, {wantReply: true});\n });\n }\n } else if (db.hasBeenClosed()) {\n // Database has been closed.\n return Promise.reject(new Dexie.DatabaseClosedError());\n } else if (db.hasFailed()) {\n // Database has failed to open\n return Promise.reject(new Dexie.InvalidStateError(\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\n } else {\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\n // Wait for it to open, then connect.\n var promise = new Promise(function (resolve, reject) {\n db.on(\"ready\", () => {\n // First, check if this is the very first time we connect to given URL.\n // Need to know, because if it is, we should stall the promise returned to\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\n return db._syncNodes.get({url}, node => {\n // Ok, now we know whether we should await the connect promise or not.\n // No matter, we should now connect (will maybe create the SyncNode instance\n // representing the given URL)\n let connectPromise = db.syncable.connect(protocolName, url, options);\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\n // Ok, so let's see if we should suspend DB queries until connected or not:\n if (node && node.appliedRemoteRevision) {\n // The very first initial sync has been done so we need not wait\n // for the connect promise to complete. It can continue in background.\n // Returning here will resume db.on('ready') and resume all queries that\n // the application has put to the database.\n return;\n }\n // This was the very first time we connect to the remote server,\n // we must make sure that the initial sync request succeeeds before resuming\n // database queries that the application code puts onto the database.\n // If OFFLINE or other error, don't allow the application to proceed.\n // We are assuming that an initial sync is essential for the application to\n // function correctly.\n return connectPromise;\n });\n });\n // Force open() to happen. Otherwise connect() may stall forever.\n db.open().catch(ex => {\n // If open fails, db.on('ready') may not have been called and we must\n // reject promise with InvalidStateError\n reject(new Dexie.InvalidStateError(\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\n ex\n ));\n });\n });\n return promise;\n }\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initPersistedContext(node) {\n //\n // PersistedContext : IPersistedContext\n //\n return class PersistedContext {\n constructor(nodeID, otherProps) {\n this.nodeID = nodeID;\n if (otherProps) Dexie.extend(this, otherProps);\n }\n\n save() {\n // Store this instance in the syncContext property of the node it belongs to.\n return Dexie.vip(() => {\n return node.save();\n });\n }\n }\n}\n","import Dexie from 'dexie';\n\nimport initPersistedContext from './PersistedContext';\n\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\n return function getOrCreateSyncNode(options) {\n return db.transaction('rw', db._syncNodes, db._changes, function () {\n if (!url) throw new Error(\"Url cannot be empty\");\n\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\n // maps to class\n if (node) {\n const PersistedContext = initPersistedContext(node);\n // Node already there. Make syncContext become an instance of PersistedContext:\n node.syncContext = new PersistedContext(node.id, node.syncContext);\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\n node.syncOptions = options; // Options could have been changed\n db._syncNodes.put(node);\n } else {\n // Create new node and sync everything\n node = new db.observable.SyncNode();\n node.myRevision = -1;\n node.appliedRemoteRevision = null;\n node.remoteBaseRevisions = [];\n node.type = \"remote\";\n node.syncProtocol = protocolName;\n node.url = url;\n node.syncOptions = options;\n node.lastHeartBeat = Date.now();\n node.dbUploadState = null;\n const PersistedContext = initPersistedContext(node);\n Dexie.Promise.resolve(function () {\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\n if (options.initialUpload === false)\n return db._changes.toCollection().lastKey(function (currentRevision) {\n node.myRevision = currentRevision;\n });\n }()).then(function () {\n db._syncNodes.add(node).then(function (nodeID) {\n node.syncContext = new PersistedContext(nodeID); // Update syncContext in db with correct nodeId.\n db._syncNodes.put(node);\n });\n });\n }\n\n return node; // returning node will make the db.transaction()-promise resolve with this value.\n });\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initEnqueue(db) {\n return function enqueue(context, fn, instanceID) {\n function _enqueue() {\n if (!context.ongoingOperation) {\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\n return Dexie.vip(function () {\n return fn();\n });\n }).finally(()=> {\n delete context.ongoingOperation;\n });\n } else {\n context.ongoingOperation = context.ongoingOperation.then(function () {\n return enqueue(context, fn, instanceID);\n });\n }\n return context.ongoingOperation;\n }\n\n if (!instanceID) {\n // Caller wants to enqueue it until database becomes open.\n if (db.isOpen()) {\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\n // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB)\n return _enqueue();\n } else {\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\n }\n };\n}\n","export default function initSaveToUncommittedChanges(db, node) {\n return function saveToUncommittedChanges(changes, remoteRevision) {\n return db.transaction('rw!', db._uncommittedChanges, () => {\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\n let changeWithNodeId = {\n node: node.id,\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.obj) changeWithNodeId.obj = change.obj;\n if (change.mods) changeWithNodeId.mods = change.mods;\n return changeWithNodeId;\n }));\n }).then(() => {\n node.appliedRemoteRevision = remoteRevision;\n return node.save();\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function bulkUpdate(table, changes) {\n let keys = changes.map(c => c.key);\n let map = {};\n // Retrieve current object of each change to update and map each\n // found object's primary key to the existing object:\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\n map[cursor.primaryKey+''] = obj;\n }).then(()=>{\n // Filter away changes whose key wasn't found in the local database\n // (we can't update them if we do not know the existing values)\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\n // Apply modifications onto each existing object (in memory)\n // and generate array of resulting objects to put using bulkPut():\n let objsToPut = updatesThatApply.map (c => {\n let curr = map[c.key+''];\n Object.keys(c.mods).forEach(keyPath => {\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\n });\n return curr;\n });\n return table.bulkPut(objsToPut);\n });\n}\n","import Dexie from 'dexie';\nimport { CREATE, DELETE, UPDATE } from './change_types';\nimport bulkUpdate from './bulk-update';\n\nexport default function initApplyChanges(db) {\n return function applyChanges(changes) {\n let collectedChanges = {};\n changes.forEach((change) => {\n if (!collectedChanges.hasOwnProperty(change.table)) {\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\n }\n collectedChanges[change.table][change.type].push(change);\n });\n let table_names = Object.keys(collectedChanges);\n let tables = table_names.map((table) => db.table(table));\n\n return db.transaction(\"rw\", tables, () => {\n table_names.forEach((table_name) => {\n const table = db.table(table_name);\n const specifyKeys = !table.schema.primKey.keyPath;\n const createChangesToApply = collectedChanges[table_name][CREATE];\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\n if (createChangesToApply.length > 0)\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\n createChangesToApply.map(c => c.key) : undefined);\n if (updateChangesToApply.length > 0)\n bulkUpdate(table, updateChangesToApply);\n if (deleteChangesToApply.length > 0)\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\n });\n });\n };\n}\n","import Dexie from 'dexie';\nimport initApplyChanges from './apply-changes';\n\nexport default function initFinallyCommitAllChanges(db, node) {\n const applyChanges = initApplyChanges(db);\n\n return function finallyCommitAllChanges(changes, remoteRevision) {\n // 1. Open a write transaction on all tables in DB\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\n table.name === '_uncommittedChanges' ||\n table.schema.observable);\n\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\n var trans = Dexie.currentTransaction;\n var localRevisionBeforeChanges = 0;\n return db._changes.orderBy('rev').last(function (lastChange) {\n // Store what revision we were at before committing the changes\n localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0;\n }).then(() => {\n // Specify the source. Important for the change consumer to ignore changes originated from self!\n trans.source = node.id;\n // 2. Apply uncommitted changes and delete each uncommitted change\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\n }).then(function (uncommittedChanges) {\n return applyChanges(uncommittedChanges);\n }).then(function () {\n return db._uncommittedChanges.where('node').equals(node.id).delete();\n }).then(function () {\n // 3. Apply last chunk of changes\n return applyChanges(changes);\n }).then(function () {\n // Get what revision we are at now:\n return db._changes.orderBy('rev').last();\n }).then(function (lastChange) {\n var currentLocalRevision = (lastChange && lastChange.rev) || 0;\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\n node.appliedRemoteRevision = remoteRevision;\n node.remoteBaseRevisions.push({remote: remoteRevision, local: currentLocalRevision});\n if (node.myRevision === localRevisionBeforeChanges) {\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\n node.myRevision = currentLocalRevision;\n }\n // Garbage collect remoteBaseRevisions not in use anymore:\n if (node.remoteBaseRevisions.length > 1) {\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n node.remoteBaseRevisions.splice(0, i);\n break;\n }\n }\n }\n // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\n node.save().catch(err=> {\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\n });\n });\n });\n };\n}\n","export default function getBaseRevisionAndMaxClientRevision(node) {\n /// \n if (node.remoteBaseRevisions.length === 0)\n return {\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\n maxClientRevision: Infinity,\n remoteBaseRevision: null\n };\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\n return {\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\n };\n }\n }\n // There are at least one item in the list but the server hasn't yet become up-to-date with the 0 revision from client.\n return {\n maxClientRevision: node.remoteBaseRevisions[0].local,\n remoteBaseRevision: null\n };\n}\n","import Dexie from 'dexie';\n\nexport default function combineCreateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\n });\n return clonedChange;\n}\n","import Dexie from 'dexie';\n\nexport default function combineUpdateAndUpdate(prevChange, nextChange) {\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\n Object.keys(nextChange.mods).forEach(function (keyPath) {\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\n var hadParentPath = false;\n Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\n Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\n hadParentPath = true;\n });\n if (!hadParentPath) {\n // Add or replace this keyPath and its new value\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\n }\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\n // we must mimic what would happen if applying the two changes after each other:\n Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\n delete clonedChange.mods[subPath];\n });\n });\n return clonedChange;\n}\n","import { CREATE, UPDATE, DELETE } from './change_types';\nimport combineCreateAndUpdate from './combine-create-and-update.js';\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\n\nexport default function mergeChange(prevChange, nextChange) {\n switch (prevChange.type) {\n case CREATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous CREATE.\n case UPDATE:\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\n case DELETE:\n return nextChange; // Object created and then deleted. If it wasnt for that we MUST handle resent changes, we would skip entire change here. But what if the CREATE was sent earlier, and then CREATE/DELETE at later stage? It would become a ghost object in DB. Therefore, we MUST keep the delete change! If object doesnt exist, it wont harm!\n }\n break;\n case UPDATE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // Another CREATE replaces previous update.\n case UPDATE:\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\n case DELETE:\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\n }\n break;\n case DELETE:\n switch (nextChange.type) {\n case CREATE:\n return nextChange; // A resurection occurred. Only create change is of interest.\n case UPDATE:\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\n case DELETE:\n return prevChange; // Still a delete change. Leave as is.\n }\n break;\n }\n}\n","import {CREATE, UPDATE} from '../change_types';\nimport mergeChange from '../merge-change';\n\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\n return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n var changeSet = {};\n var numChanges = 0;\n var partial = false;\n var ignoreSource = node.id;\n var nextRevision = revision;\n return db.transaction('r', db._changes, function () {\n var query = db._changes.where('rev').between(revision, maxRevision, false, true);\n return query.until(() => {\n if (numChanges === maxChanges) {\n partial = true;\n return true;\n }\n }).each(function (change) {\n // Note the revision in nextRevision:\n nextRevision = change.rev;\n // change.source is set based on currentTransaction.source\n if (change.source === ignoreSource) return;\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info:\n var changeToSend = {\n type: change.type,\n table: change.table,\n key: change.key\n };\n if (change.type === CREATE)\n changeToSend.obj = change.obj;\n else if (change.type === UPDATE)\n changeToSend.mods = change.mods;\n\n var id = change.table + \":\" + change.key;\n var prevChange = changeSet[id];\n if (!prevChange) {\n // This is the first change on this key. Add it unless it comes from the source that we are working against\n changeSet[id] = changeToSend;\n ++numChanges;\n } else {\n // Merge the oldchange with the new change\n var nextChange = changeToSend;\n var mergedChange = mergeChange(prevChange, nextChange);\n changeSet[id] = mergedChange;\n }\n });\n }).then(function () {\n var changes = Object.keys(changeSet).map(function (key) {\n return changeSet[key];\n });\n hasMoreToGive.hasMoreToGive = partial;\n return cb(changes, partial, {myRevision: nextRevision});\n });\n };\n}\n","import {CREATE} from '../change_types';\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\n\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\n return function getTableObjectsAsChanges(state, changes, collection) {\n /// \n /// \n /// \n var limitReached = false;\n return collection.until(function () {\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\n limitReached = true;\n return true;\n }\n }).each(function (item, cursor) {\n changes.push({\n type: CREATE,\n table: state.currentTable,\n key: cursor.key,\n obj: cursor.value\n });\n state.currentKey = cursor.key;\n }).then(function () {\n if (limitReached) {\n // Limit reached. Send partial result.\n hasMoreToGive.hasMoreToGive = true;\n return cb(changes, null, true, {dbUploadState: state});\n } else {\n // Done iterating this table. Check if there are more tables to go through:\n if (state.tablesToUpload.length === 0) {\n // Done iterating all tables\n // Now append changes occurred during our dbUpload:\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\n changes = changes.concat(additionalChanges);\n nodeModificationsOnAck.dbUploadState = null;\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Not done iterating all tables. Continue on next table:\n state.currentTable = state.tablesToUpload.shift();\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\n }\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\nimport initGetChangesSinceRevision from './get-changes-since-revision';\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\n\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\n\n return function getLocalChangesForNode(node, cb) {\n /// \n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\n /// for that node.\n /// \n /// \n /// Callback that will retrieve next chunk of changes and a boolean telling if it's a partial result or not. If truthy, result is partial and there are more changes to come. If falsy, these changes are the final result.\n\n const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\n\n // Only a \"remote\" SyncNode created by Dexie.Syncable\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\n if (node.myRevision >= 0) {\n // Node is based on a revision in our local database and will just need to get the changes that have occurred since that revision.\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\n });\n } else {\n // Node hasn't got anything from our local database yet. We will need to upload the entire DB to the node in the form of CREATE changes.\n // Check if we're in the middle of already doing that:\n if (node.dbUploadState === null) {\n // Initialize dbUploadState\n var tablesToUpload = db.tables.filter(function (table) {\n return table.schema.observable;\n }).map(function (table) {\n return table.name;\n });\n if (tablesToUpload.length === 0) return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all.\n var dbUploadState = {\n tablesToUpload: tablesToUpload,\n currentTable: tablesToUpload.shift(),\n currentKey: null\n };\n return db._changes.orderBy('rev').last(function (lastChange) {\n dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0;\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(dbUploadState, [], collection);\n });\n } else if (node.dbUploadState.currentKey) {\n const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n } else {\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\n }\n }\n };\n}\n","import Dexie from 'dexie';\n\nimport initEnqueue from './enqueue';\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\nimport {Statuses} from './statuses';\n\nconst Promise = Dexie.Promise;\n\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\n const enqueue = initEnqueue(db);\n var hasMoreToGive = {hasMoreToGive: true};\n\n function stillAlive() {\n // A better method than doing db.isOpen() because the same db instance may have been reopened, but then this sync call should be dead\n // because the new instance should be considered a fresh instance and will have another local node.\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\n }\n\n return function connectProtocol(node, activePeer) {\n /// \n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\n\n const url = activePeer.url;\n\n function changeStatusTo(newStatus) {\n if (node.status !== newStatus) {\n node.status = newStatus;\n node.save().then(()=> {\n db.syncable.on.statusChanged.fire(newStatus, url);\n // Also broadcast message to other nodes about the status\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\n }).catch('DatabaseClosedError', ()=> {\n });\n }\n }\n\n activePeer.on('disconnect', function (newStatus) {\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\n });\n\n var connectedContinuation;\n changeStatusTo(Statuses.CONNECTING);\n return doSync();\n\n function doSync() {\n // Use enqueue() to ensure only a single promise execution at a time.\n return enqueue(doSync, function () {\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\n return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider);\n }, dbAliveID);\n }\n\n function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\n var finalSyncPromise = new Promise(function (resolve, reject) {\n rejectConnectPromise.p = function (err) {\n reject(err);\n };\n Dexie.asap(function () {\n try {\n protocolInstance.sync(\n node.syncContext,\n url,\n options,\n remoteBaseRevision,\n node.appliedRemoteRevision,\n changes,\n partial,\n applyRemoteChanges,\n onChangesAccepted,\n function (continuation) {\n resolve(continuation);\n },\n onError);\n } catch (ex) {\n onError(ex, Infinity);\n }\n\n function onError(error, again) {\n reject(error);\n if (stillAlive()) {\n if (!isNaN(again) && again < Infinity) {\n setTimeout(function () {\n if (stillAlive()) {\n changeStatusTo(Statuses.SYNCING);\n doSync().catch('DatabaseClosedError', abortTheProvider);\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\n connectedContinuation = null;\n } else {\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\n }\n }\n }\n });\n });\n\n return finalSyncPromise.then(function () {\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\n return undefined;\n }).finally(()=> {\n // In case error happens after connect, don't try reject the connect promise anymore.\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\n // is active and this happens. It would fire unhandledrejection but that we do not want.\n rejectConnectPromise.p = null;\n });\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\n // otherwise it will execute when finalSyncPromise resolves.\n finalSyncPromise.then(continueSendingChanges);\n return node.save();\n }\n }\n\n function abortTheProvider(error) {\n activePeer.disconnect(Statuses.ERROR, error);\n }\n\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n return getLocalChangesForNode(node, autoAck);\n } else {\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\n }\n });\n }\n\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\n\n return enqueue(applyRemoteChanges, function () {\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\n // FIXTHIS: Check what to do if clear() is true!\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\n .catch(function (error) {\n abortTheProvider(error);\n return Promise.reject(error);\n });\n }, dbAliveID);\n }\n\n //\n //\n // Continuation Patterns Follows\n //\n //\n\n function continueSendingChanges(continuation) {\n if (!stillAlive()) { // Database was closed.\n if (continuation.disconnect)\n continuation.disconnect();\n return;\n }\n\n connectedContinuation = continuation;\n activePeer.on('disconnect', function () {\n if (connectedContinuation) {\n if (connectedContinuation.react) {\n try {\n // react pattern must provide a disconnect function.\n connectedContinuation.disconnect();\n } catch (e) {\n }\n }\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\n }\n });\n\n if (continuation.react) {\n continueUsingReactPattern(continuation);\n } else {\n continueUsingPollPattern(continuation);\n }\n }\n\n // React Pattern (eager)\n function continueUsingReactPattern(continuation) {\n var changesWaiting, // Boolean\n isWaitingForServer; // Boolean\n\n\n function onChanges() {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n if (isWaitingForServer)\n changesWaiting = true;\n else {\n reactToChanges();\n }\n }\n }\n\n db.on('changes', onChanges);\n\n activePeer.on('disconnect', function () {\n db.on.changes.unsubscribe(onChanges);\n });\n\n function reactToChanges() {\n if (!connectedContinuation) return;\n changesWaiting = false;\n isWaitingForServer = true;\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n if (!connectedContinuation) return;\n if (changes.length > 0) {\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n // More changes may be waiting:\n reactToChanges();\n });\n } else {\n isWaitingForServer = false;\n if (changesWaiting) {\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\n reactToChanges();\n } else {\n changeStatusTo(Statuses.ONLINE);\n }\n }\n }).catch(ex => {\n console.error(`Got ${ex.message} caught by reactToChanges`);\n abortTheProvider(ex);\n });\n }\n\n reactToChanges();\n }\n\n // Poll Pattern\n function continueUsingPollPattern() {\n\n function syncAgain() {\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\n\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\n\n function onChangesAccepted() {\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\n });\n node.save().catch('DatabaseClosedError', ()=> {\n });\n }\n\n function onSuccess(continuation) {\n if (!connectedContinuation) {\n // Got disconnected before succeeding. Quit.\n return;\n }\n connectedContinuation = continuation;\n if (partial) {\n // We only sent partial changes. Need to do another round asap.\n syncAgain();\n } else {\n // We've sent all changes now (in sync!)\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\n // Provider wants to keep polling. Set Status to ONLINE.\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, continuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n }\n\n function onError(error, again) {\n if (!isNaN(again) && again < Infinity) {\n if (connectedContinuation) {\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, again);\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\n } // else status is already changed since we got disconnected.\n } else {\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\n }\n }\n }).catch(abortTheProvider);\n }\n\n if (hasMoreToGive.hasMoreToGive) {\n syncAgain();\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\n changeStatusTo(Statuses.ONLINE);\n setTimeout(function () {\n if (connectedContinuation) {\n changeStatusTo(Statuses.SYNCING);\n syncAgain();\n }\n }, connectedContinuation.again);\n } else {\n // Provider seems finished polling. Since we are never going to poll again,\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\n activePeer.disconnect(Statuses.OFFLINE);\n }\n }\n };\n}\n","import Dexie from 'dexie';\n\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\nimport initConnectProtocol from './connect-protocol';\nimport {Statuses} from './statuses';\n\nexport default function initConnectFn(db, activePeers) {\n return function connect(protocolInstance, protocolName, url, options, dbAliveID) {\n /// \n var existingPeer = activePeers.filter(function (peer) {\n return peer.url === url;\n });\n if (existingPeer.length > 0) {\n const activePeer = existingPeer[0];\n const diffObject = {};\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\n // Options have been changed\n // We need to disconnect and reconnect\n if (Object.keys(diffObject).length !== 0) {\n return db.syncable.disconnect(url)\n .then(() => {\n return execConnect();\n })\n } else {\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\n // have already been started and eventually also resolved. If promise has already resolved (node connected), calling existing promise.then() will give a callback directly.\n return existingPeer[0].connectPromise;\n }\n }\n\n function execConnect() {\n // Use an object otherwise we wouldn't be able to get the reject promise from\n // connectProtocol\n var rejectConnectPromise = {p: null};\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\n return connectProtocol(node, activePeer);\n });\n\n var disconnected = false;\n var activePeer = {\n url: url,\n status: Statuses.OFFLINE,\n connectPromise: connectPromise,\n syncOptions: options,\n on: Dexie.Events(null, \"disconnect\"),\n disconnect: function (newStatus, error) {\n var pos = activePeers.indexOf(activePeer);\n if (pos >= 0) activePeers.splice(pos, 1);\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\n if (!disconnected) {\n activePeer.on.disconnect.fire(newStatus, error);\n }\n disconnected = true;\n }\n };\n activePeers.push(activePeer);\n\n return connectPromise;\n }\n\n return execConnect();\n };\n}\n","/* ========================================================================== \n * dexie-syncable.js\n * ==========================================================================\n *\n * Dexie addon for syncing indexedDB with remote endpoints.\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\n\nimport Dexie from \"dexie\";\n// Depend on 'dexie-observable'\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\n// That way, our plugin works in all UMD cases.\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\nimport \"dexie-observable\";\n\nimport initSyncableConnect from './syncable-connect';\nimport initConnectFn from './connect-fn';\nimport {Statuses, StatusTexts} from './statuses';\n\nvar override = Dexie.override,\n Promise = Dexie.Promise,\n Observable = Dexie.Observable;\n\nexport default function Syncable (db) {\n /// \n\n var activePeers = [];\n\n const connectFn = initConnectFn(db, activePeers);\n const syncableConnect = initSyncableConnect(db, connectFn);\n\n db.on('message', function(msg) {\n // Message from other local node arrives...\n Dexie.vip(function() {\n if (msg.type === 'connect') {\n // We are master node and another non-master node wants us to do the connect.\n db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\n } else if (msg.type === 'disconnect') {\n db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject);\n } else if (msg.type === 'syncStatusChanged') {\n // We are client and a master node informs us about syncStatus change.\n // Lookup the connectedProvider and call its event\n db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url);\n }\n });\n });\n\n db.on('cleanup', function(weBecameMaster) {\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\n if (weBecameMaster) {\n // We took over the master role in Observable's cleanup method.\n // We should connect to remote servers now.\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\n // connection has been closed. The new master would then be expected to reconnect.\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\n // an old closed one. \n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\n return db._syncNodes.where({type: 'remote'})\n .filter(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\n })\n )));\n })).catch('DatabaseClosedError', ()=>{});\n }\n });\n\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\n // when the database opens. It will not wait for the connection to complete, just initiate the\n // connection so that it will continue syncing as long as the database is open.\n\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\n db.on('ready', function onReady() {\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\n // This \"ready\" subscriber will never be the one performing the initial sync request, because\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\n // called after this one. There, in that subscriber, the initial sync request will take place\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\n // next time this database is opened.\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\n // once in the past for each \"connectedRemoteNode\" we find in query below.\n\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\n db._syncNodes\n .where('type').equals('remote')\n .and(node => node.status !== Statuses.OFFLINE)\n .toArray(connectedRemoteNodes => {\n // There are connected remote nodes that we must manage (or take over to manage)\n connectedRemoteNodes.forEach(\n node => db.syncable.connect(\n node.syncProtocol,\n node.url,\n node.syncOptions) \n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\n );\n }).catch('DatabaseClosedError', ()=>{});\n }\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\n\n db.syncable = {};\n\n db.syncable.getStatus = function(url, cb) {\n if (db.isOpen()) {\n return Dexie.vip(function() {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node ? node.status : Statuses.OFFLINE;\n });\n }).then(cb);\n } else {\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\n }\n };\n\n db.syncable.getOptions = function(url, cb) {\n return db.transaction('r?', db._syncNodes, () => {\n return db._syncNodes.where('url').equals(url).first(function(node) {\n return node.syncOptions;\n }).then(cb);\n });\n };\n\n db.syncable.list = function() {\n return db.transaction('r?', db._syncNodes, ()=>{\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\n return a.map(function(node) { return node.url; });\n });\n });\n };\n\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\n\n db.syncable.disconnect = function(url) {\n return Dexie.ignoreTransaction(()=>{\n return Promise.resolve().then(()=>{\n if (db._localSyncNode && db._localSyncNode.isMaster) {\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\n return peer.disconnect(Statuses.OFFLINE);\n }));\n } else {\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\n });\n }\n }).then(()=>{\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\n node.status = Statuses.OFFLINE;\n });\n });\n });\n };\n\n db.syncable.connect = function(protocolName, url, options) {\n options = options || {}; // Make sure options is always an object because 1) Provider expects it to be. 2) We'll be persisting it and you cannot persist undefined.\n var protocolInstance = Syncable.registeredProtocols[protocolName];\n if (protocolInstance) {\n return syncableConnect(protocolInstance, protocolName, url, options);\n } else {\n return Promise.reject(\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\n );\n }\n };\n\n db.syncable.delete = function(url) {\n return db.syncable.disconnect(url).then(()=>{\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\n // Find the node(s)\n // Several can be found, as detected by @martindiphoorn,\n // let's delete them and cleanup _uncommittedChanges and _changes \n // accordingly.\n let nodeIDsToDelete;\n return db._syncNodes\n .where(\"url\").equals(url)\n .toArray(nodes => nodes.map(node => node.id))\n .then(nodeIDs => {\n nodeIDsToDelete = nodeIDs;\n // Delete the syncNode that represents the remote endpoint.\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\n })\n .then (() =>\n // In case there were uncommittedChanges belonging to this, delete them as well\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\n }).then(()=> {\n // Spawn background job to delete old changes, now that a node has been deleted,\n // there might be changes in _changes table that is not needed to keep anymore.\n // This is done in its own transaction, or possible several transaction to prohibit\n // starvation\n Observable.deleteOldChanges(db);\n });\n });\n };\n\n db.syncable.unsyncedChanges = function(url) {\n return db._syncNodes.where(\"url\").equals(url).first(function(node) {\n return db._changes.where('rev').above(node.myRevision).toArray();\n });\n };\n\n db.close = override(db.close, function(origClose) {\n return function() {\n activePeers.forEach(function(peer) {\n peer.disconnect();\n });\n return origClose.apply(this, arguments);\n };\n });\n\n Object.defineProperty(\n db.observable.SyncNode.prototype,\n 'save', {\n enumerable: false,\n configurable: true,\n writable: true,\n value() {\n return db.transaction('rw?', db._syncNodes, () => {\n return db._syncNodes.put(this);\n });\n }\n });\n}\n\nSyncable.Statuses = Statuses;\n\nSyncable.StatusTexts = StatusTexts;\n\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\n\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\n /// \n /// Register a synchronization protocol that can synchronize databases with remote servers.\n /// \n /// Provider name\n /// Implementation of ISyncProtocol\n const partialsThreshold = protocolInstance.partialsThreshold;\n if (typeof partialsThreshold === 'number') {\n // Don't allow NaN or negative threshold\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\n throw new Error('The given number for the threshold is not supported');\n }\n // If the threshold is 0 we will not send any client changes but will get server changes\n } else {\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\n protocolInstance.partialsThreshold = Infinity;\n }\n Syncable.registeredProtocols[name] = protocolInstance;\n};\n\n// Register addon in Dexie:\nDexie.Syncable = Syncable;\nDexie.addons.push(Syncable);\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","export const Statuses = {\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\n OFFLINE: 0, // The sync provider hasn't yet become online, or it has been disconnected.\n CONNECTING: 1, // Trying to connect to server\n ONLINE: 2, // Connected to server and currently in sync with server\n SYNCING: 3, // Syncing with server. For poll pattern, this is every poll call. For react pattern, this is when local changes are being sent to server.\n ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect.\n};\n\nexport const StatusTexts = {\n \"-1\": \"ERROR\",\n \"0\": \"OFFLINE\",\n \"1\": \"CONNECTING\",\n \"2\": \"ONLINE\",\n \"3\": \"SYNCING\",\n \"4\": \"ERROR_WILL_RETRY\"\n};\n"]} \ No newline at end of file diff --git a/dist/README.md b/dist/README.md deleted file mode 100644 index edbd0da65..000000000 --- a/dist/README.md +++ /dev/null @@ -1,51 +0,0 @@ -## Can't find dexie.js? -Dexie's dist files are no longer checked in to github except temporarily when tagging -a release version (just so that bower will continue to work). The reason for this is because -checking in dist files bloats the commit history and makes it error prone to contribute to the -repo. To support bower though, we have to continue checking in dist files when releasing, -but that is now handled by the release.sh script, who also removes them directly afterwards. - -If you still just want to download dexie.js to include in a test HTML page, go -to the following download site: - -### Download -[dexie.min.js](https://unpkg.com/dexie/dist/dexie.min.js) - -[dexie.min.js.map](https://unpkg.com/dexie/dist/dexie.min.js.map) - -### Typings -[dexie.d.ts](https://unpkg.com/dexie/dist/dexie.d.ts) - -### Optional Stuff -[dexie.js (non-minified version)](https://unpkg.com/dexie/dist/dexie.js) - -[dexie.js.map](https://unpkg.com/dexie/dist/dexie.js.map) - -[dexie.min.js.gz (Minified and gzipped)](https://unpkg.com/dexie/dist/dexie.min.js.gz) - -## Install from NPM -``` -npm install dexie --save -``` - -## Install from bower -``` -bower install dexie --save -``` - -## How to build -1. cd to dexie package -2. npm install -3. npm run build - -## Contributing to Dexie.js? - -Watch: -``` -npm run watch -``` - -Test: -``` -npm test -``` diff --git a/dist/dexie.d.ts b/dist/dexie.d.ts new file mode 100644 index 000000000..8f1b1e582 --- /dev/null +++ b/dist/dexie.d.ts @@ -0,0 +1,527 @@ +// Type definitions for Dexie v2.0.2 +// Project: https://github.com/dfahlander/Dexie.js +// Definitions by: David Fahlander + +declare type IndexableTypePart = + string | number | Date | ArrayBuffer | ArrayBufferView | DataView | Array>; + +declare type IndexableTypeArray = Array; +declare type IndexableTypeArrayReadonly = ReadonlyArray; +export declare type IndexableType = IndexableTypePart | IndexableTypeArrayReadonly; + +declare type ThenShortcut = (value: T) => TResult | PromiseLike; + +declare type TransactionMode = 'r' | 'r!' | 'r?' | 'rw' | 'rw!' | 'rw?'; + +interface ProbablyError { + name?: string; + stack?: string; + message?: string; +} + +// Dexie is actually default exported at the end of this file. +// Still, need to keep this explicit export anyway. Needed in order for +// Typescript 2.1 to allow extension of the Dexie API. +export declare class Dexie { + constructor(databaseName: string, options?: { + addons?: Array<(db: Dexie) => void>, + autoOpen?: boolean, + indexedDB?: IDBFactory, + IDBKeyRange?: {new(): IDBKeyRange} + }); + + readonly name: string; + readonly tables: Dexie.Table[]; + readonly verno: number; + + static addons: Array<(db: Dexie) => void>; + static version: number; + static semVer: string; + static currentTransaction: Dexie.Transaction; + static waitFor (promise: PromiseLike | T) : Dexie.Promise; + static waitFor (promise: PromiseLike | T, timeoutMilliseconds: number) : Dexie.Promise; + + static getDatabaseNames(): Dexie.Promise; + static getDatabaseNames(thenShortcut: ThenShortcut): Dexie.Promise; + + static override (origFunc:F, overridedFactory: (fn:any)=>any) : F; + + static getByKeyPath(obj: Object, keyPath: string): any; + + static setByKeyPath(obj: Object, keyPath: string, value: any): void; + + static delByKeyPath(obj: Object, keyPath: string): void; + + static shallowClone (obj: T): T; + + static deepClone(obj: T): T; + + static asap(fn: Function) : void; + + static maxKey: Array> | string; + static minKey: number; + + static exists(dbName: string) : Dexie.Promise; + + static delete(dbName: string): Dexie.Promise; + + static dependencies: { + indexedDB: IDBFactory, + IDBKeyRange: IDBKeyRange + }; + + static default: Dexie; + + version(versionNumber: Number): Dexie.Version; + + on: Dexie.DbEvents; + + open(): Dexie.Promise; + + table(tableName: string): Dexie.Table; + + table(tableName: string): Dexie.Table; + + table(tableName: string): Dexie.Table; + + transaction(mode: TransactionMode, table: Dexie.Table, scope: () => PromiseLike | U): Dexie.Promise; + + transaction(mode: TransactionMode, table: Dexie.Table, table2: Dexie.Table, scope: () => PromiseLike | U): Dexie.Promise; + + transaction(mode: TransactionMode, table: Dexie.Table, table2: Dexie.Table, table3: Dexie.Table, scope: () => PromiseLike | U): Dexie.Promise; + + transaction(mode: TransactionMode, table: Dexie.Table, table2: Dexie.Table, table3: Dexie.Table, table4: Dexie.Table, scope: () => PromiseLike | U): Dexie.Promise; + + transaction(mode: TransactionMode, table: Dexie.Table, table2: Dexie.Table, table3: Dexie.Table, table4: Dexie.Table, table5: Dexie.Table, scope: () => PromiseLike | U): Dexie.Promise; + + transaction(mode: TransactionMode, tables: Dexie.Table[], scope: () => PromiseLike | U): Dexie.Promise; + + close(): void; + + delete(): Dexie.Promise; + + isOpen(): boolean; + + hasBeenClosed(): boolean; + + hasFailed(): boolean; + + dynamicallyOpened(): boolean; + + backendDB(): IDBDatabase; + + vip(scopeFunction: () => U): U; + + // Make it possible to touch physical class constructors where they reside - as properties on db instance. + // For example, checking if (x instanceof db.Table). Can't do (x instanceof Dexie.Table because it's just a virtual interface) + Table : new()=>Dexie.Table; + WhereClause: new()=>Dexie.WhereClause; + Version: new()=>Dexie.Version; + Transaction: new()=>Dexie.Transaction; + Collection: new()=>Dexie.Collection; +} + +export declare module Dexie { + + interface Promise { + // From Promise in lib.es2015.d.ts and lib.es2015.symbol.wellknown.d.ts but with return type Dexie.Promise: + then(onfulfilled?: ((value: T) => T | PromiseLike) | undefined | null, onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): Dexie.Promise; + then(onfulfilled: ((value: T) => T | PromiseLike) | undefined | null, onrejected: (reason: any) => TResult | PromiseLike): Dexie.Promise; + then(onfulfilled: (value: T) => TResult | PromiseLike, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Dexie.Promise; + then(onfulfilled: (value: T) => TResult1 | PromiseLike, onrejected: (reason: any) => TResult2 | PromiseLike): Dexie.Promise; + catch(onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): Dexie.Promise; + catch(onrejected: (reason: any) => TResult | PromiseLike): Dexie.Promise; + readonly [Symbol.toStringTag]: "Promise"; + + // Extended methods provided by Dexie.Promise: + + /** + * Catch errors where error => error.name === errorName. Other errors will remain uncaught. + * + * @param errorName Name of the type of error to catch such as 'RangeError', 'TypeError', 'DatabaseClosedError', etc. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(errorName: string, onrejected: (reason: Error) => TResult | PromiseLike): Dexie.Promise; + + /** + * Catch errors where error => error.name === errorName. Other errors will remain uncaught. + * + * @param errorName Name of the type of error to catch such as 'RangeError', 'TypeError', 'DatabaseClosedError', etc. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(errorName: string, onrejected: (reason: Error) => T | PromiseLike): Dexie.Promise; + + /** + * Catch errors where error => error instanceof errorConstructor. Other errors will remain uncaught. + * + * @param errorConstructor Type of error to catch such as RangeError, TypeError, etc. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(errorConstructor: {new():TError}, onrejected: (reason: TError) => TResult | PromiseLike): Dexie.Promise; + + /** + * Catch errors where error => error instanceof errorConstructor. Other errors will remain uncaught. + * + * @param errorConstructor Type of error to catch such as RangeError, TypeError, etc. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(errorConstructor: {new():TError}, onrejected: (reason: TError) => T | PromiseLike): Dexie.Promise; + + /** + * Attaches a callback to be executed when promise is settled no matter if it was rejected + * or resolved. + * + * @param onFinally The callback to execute when promise is settled. + * @returns A Promise for the completion of the callback. + */ + finally(onFinally: () => void): Dexie.Promise; + + /** + * Apply a timeout limit for the promise. If timeout is reached before promise is settled, + * the returned promise will reject with an Error object where name='TimeoutError'. + * + * @param milliseconds Number of milliseconds for the timeout. + * @returns A Promise that will resolve or reject identically to current Promise, but if timeout is reached, + * it will reject with TimeoutError. + */ + timeout(milliseconds: number): Dexie.Promise; + } + + interface DexiePromiseConstructor { + // From lib.es6.d.ts: + all(values: Iterable>): Dexie.Promise; + race(values: Iterable>): Dexie.Promise; + readonly prototype: Dexie.Promise; + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Dexie.Promise; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Dexie.Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Dexie.Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Dexie.Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Dexie.Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Dexie.Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Dexie.Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Dexie.Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Dexie.Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Dexie.Promise<[T1, T2]>; + all(values: (T | PromiseLike)[]): Dexie.Promise; + reject(reason: any): Dexie.Promise; + reject(reason: any): Dexie.Promise; + resolve(value: T | PromiseLike): Dexie.Promise; + resolve(): Dexie.Promise; + } + + + var Promise: DexiePromiseConstructor; + + interface Version { + stores(schema: { [key: string]: string | null }): Version; + upgrade(fn: (trans: Transaction) => void): Version; + } + + interface Transaction { + active: boolean; + db: Dexie; + mode: string; + idbtrans: IDBTransaction; + tables: { [type: string]: Table }; + storeNames: Array; + on: TransactionEvents; + abort(): void; + table(tableName: string): Table; + table(tableName: string): Table; + table(tableName: string): Table; + } + + interface DexieEvent { + subscribers: Function[]; + fire(...args:any[]): any; + subscribe(fn: (...args:any[]) => any): void; + unsubscribe(fn: (...args:any[]) => any): void; + } + + interface DexieErrorEvent { + subscribe(fn: (error: any) => any): void; + unsubscribe(fn: (error: any) => any): void; + fire(error: any): any; + } + + interface DexieVersionChangeEvent { + subscribe(fn: (event: IDBVersionChangeEvent) => any): void; + unsubscribe(fn: (event: IDBVersionChangeEvent) => any): void; + fire(event: IDBVersionChangeEvent): any; + } + + interface DexieOnReadyEvent { + subscribe(fn: () => any, bSticky: boolean): void; + unsubscribe(fn: () => any): void; + fire(): any; + } + + interface DexieEventSet { + (eventName: string): DexieEvent; // To be able to unsubscribe. + + addEventType ( + eventName: string, + chainFunction?: (f1:Function,f2:Function)=>Function, + defaultFunction?: Function):Dexie.DexieEvent; + addEventType ( + events: {[eventName:string]: ('asap' | [(f1:Function,f2:Function)=>Function, Function])}) + : Dexie.DexieEvent; + } + + interface DbEvents extends DexieEventSet { + (eventName: 'ready', subscriber: () => any, bSticky?: boolean): void; + (eventName: 'populate', subscriber: () => any): void; + (eventName: 'blocked', subscriber: () => any): void; + (eventName: 'versionchange', subscriber: (event: IDBVersionChangeEvent) => any): void; + ready: Dexie.DexieOnReadyEvent; + populate: Dexie.DexieEvent; + blocked: Dexie.DexieEvent; + versionchange: Dexie.DexieVersionChangeEvent; + } + + interface CreatingHookContext { + onsuccess?: (primKey: Key) => void; + onerror?: (err: any) => void; + } + + interface UpdatingHookContext { + onsuccess?: (updatedObj: T) => void; + onerror?: (err: any) => void; + } + + interface DeletingHookContext { + onsuccess?: () => void; + onerror?: (err: any) => void; + } + + interface TableHooks extends DexieEventSet { + (eventName: 'creating', subscriber: (this: CreatingHookContext, primKey:Key, obj:T, transaction:Transaction) => any): void; + (eventName: 'reading', subscriber: (obj:T) => T | any): void; + (eventName: 'updating', subscriber: (this: UpdatingHookContext, modifications:Object, primKey:Key, obj:T, transaction:Transaction) => any): void; + (eventName: 'deleting', subscriber: (this: DeletingHookContext, primKey:Key, obj:T, transaction:Transaction) => any): void; + creating: DexieEvent; + reading: DexieEvent; + updating: DexieEvent; + deleting: DexieEvent; + } + + interface TransactionEvents extends DexieEventSet { + (eventName: 'complete', subscriber: () => any): void; + (eventName: 'abort', subscriber: () => any): void; + (eventName: 'error', subscriber: (error:any) => any): void; + complete: DexieEvent; + abort: DexieEvent; + error: DexieEvent; + } + + interface Table { + name: string; + schema: TableSchema; + hook: TableHooks; + + get(key: Key): Promise; + get(key: Key, thenShortcut: ThenShortcut): Promise; + get(equalityCriterias: {[key:string]:IndexableType}): Promise; + get(equalityCriterias: {[key:string]:IndexableType}, thenShortcut: ThenShortcut): Promise; + where(index: string | string[]): WhereClause; + where(equalityCriterias: {[key:string]:IndexableType}): Collection; + + filter(fn: (obj: T) => boolean): Collection; + + count(): Promise; + count(thenShortcut: ThenShortcut): Promise; + + offset(n: number): Collection; + + limit(n: number): Collection; + + each(callback: (obj: T, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + + toArray(): Promise>; + toArray(thenShortcut: ThenShortcut): Promise; + + toCollection(): Collection; + orderBy(index: string | string[]): Collection; + reverse(): Collection; + mapToClass(constructor: Function): Function; + add(item: T, key?: Key): Promise; + update(key: Key, changes: { [keyPath: string]: any }): Promise; + put(item: T, key?: Key): Promise; + delete(key: Key): Promise; + clear(): Promise; + bulkAdd(items: T[], keys?: IndexableTypeArrayReadonly): Promise; + bulkPut(items: T[], keys?: IndexableTypeArrayReadonly): Promise; + bulkDelete(keys: IndexableTypeArrayReadonly) : Promise; + } + + interface WhereClause { + above(key: IndexableType): Collection; + aboveOrEqual(key: IndexableType): Collection; + anyOf(keys: IndexableTypeArrayReadonly): Collection; + anyOf(...keys: IndexableTypeArray): Collection; + anyOfIgnoreCase(keys: string[]): Collection; + anyOfIgnoreCase(...keys: string[]): Collection; + below(key: IndexableType): Collection; + belowOrEqual(key: IndexableType): Collection; + between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean): Collection; + equals(key: IndexableType): Collection; + equalsIgnoreCase(key: string): Collection; + inAnyRange(ranges: Array): Collection; + startsWith(key: string): Collection; + startsWithAnyOf(prefixes: string[]): Collection; + startsWithAnyOf(...prefixes: string[]): Collection; + startsWithIgnoreCase(key: string): Collection; + startsWithAnyOfIgnoreCase(prefixes: string[]): Collection; + startsWithAnyOfIgnoreCase(...prefixes: string[]): Collection; + noneOf(keys: Array): Collection; + notEqual(key: IndexableType): Collection; + } + + interface Collection { + and(filter: (x: T) => boolean): Collection; + clone(props?: Object): Collection; + count(): Promise; + count(thenShortcut: ThenShortcut): Promise; + distinct(): Collection; + each(callback: (obj: T, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + eachKey(callback: (key: IndexableType, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + eachPrimaryKey(callback: (key: Key, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + eachUniqueKey(callback: (key: IndexableType, cursor: {key: IndexableType, primaryKey: Key}) => any): Promise; + filter(filter: (x: T) => boolean): Collection; + first(): Promise; + first(thenShortcut: ThenShortcut): Promise; + keys(): Promise; + keys(thenShortcut: ThenShortcut): Promise; + primaryKeys(): Promise; + primaryKeys(thenShortcut: ThenShortcut): Promise; + last(): Promise; + last(thenShortcut: ThenShortcut): Promise; + limit(n: number): Collection; + offset(n: number): Collection; + or(indexOrPrimayKey: string): WhereClause; + raw(): Collection; + reverse(): Collection; + sortBy(keyPath: string): Promise; + sortBy(keyPath: string, thenShortcut: ThenShortcut) : Promise; + toArray(): Promise>; + toArray(thenShortcut: ThenShortcut) : Promise; + uniqueKeys(): Promise; + uniqueKeys(thenShortcut: ThenShortcut): Promise; + until(filter: (value: T) => boolean, includeStopEntry?: boolean): Collection; + // Mutating methods + delete(): Promise; + modify(changeCallback: (obj: T, ctx:{value: T}) => void): Promise; + modify(changes: { [keyPath: string]: any } ): Promise; + } + + interface TableSchema { + name: string; + primKey: IndexSpec; + indexes: IndexSpec[]; + mappedClass: Function; + } + + interface IndexSpec { + name: string; + keyPath: string | Array; + unique: boolean; + multi: boolean; + auto: boolean; + compound: boolean; + src: string; + } + + // Make it possible to touch physical classes as they are + var TableSchema: new()=>TableSchema, + IndexSpec: new()=>IndexSpec, + Events: any; // Too complex to define correctly right now. + + // errnames - handy spellcheck in switch (error.name) {} cases. + var errnames: { + // Error names generated by indexedDB: + Unknown: 'UnknownError'; + Constraint: 'ConstraintError'; + Data: 'DataError'; + TransactionInactive: 'TransactionInactiveError'; + ReadOnly: 'ReadOnlyError'; + Version: 'VersionError'; + NotFound: 'NotFoundError'; + InvalidState: 'InvalidStateError'; + InvalidAccess: 'InvalidAccessError'; + Abort: 'AbortError'; + Timeout: 'TimeoutError'; + QuotaExceeded: 'QuotaExceededError'; + Syntax: 'SyntaxError'; + DataClone: 'DataCloneError'; + + // Dexie-specific error names: + Modify: 'ModifyError'; + OpenFailed: 'OpenFailedError'; + VersionChange: 'VersionChangeError'; + Schema: 'SchemaError'; + Upgrade: 'UpgradeError'; + InvalidTable: 'InvalidTableError'; + MissingAPI: 'MissingAPIError'; + NoSuchDatabase: 'NoSuchDatabaseError'; + InvalidArgument: 'InvalidArgumentError'; + SubTransaction: 'Error'; + Unsupported: 'UnsupportedError'; + Internal: 'InternalError'; + DatabaseClosed: 'DatabaseClosedError'; + }; + + class DexieError extends Error { + name: string; + message: string; + stack: string; + inner: any; + + constructor (name?:string, message?:string); + toString(): string; + } + + class ModifyError extends DexieError{ + constructor (msg?:string, failures?: any[], successCount?: number, failedKeys?: IndexableTypeArrayReadonly); + failures: Array; + failedKeys: IndexableTypeArrayReadonly; + successCount: number; + } + + class BulkError extends DexieError{ + constructor (msg?:string, failures?: any[]); + failures: Array; + } + + class OpenFailedError extends DexieError {constructor (msg?: string, inner?: Object);constructor (inner: Object);} + class VersionChangeError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class SchemaError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class UpgradeError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidTableError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class MissingAPIError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class NoSuchDatabaseError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidArgumentError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class SubTransactionError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class UnsupportedError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InternalError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class DatabaseClosedError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class UnknownError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class ConstraintError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class DataError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class TransactionInactiveError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class ReadOnlyError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class VersionError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class NotFoundError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidStateError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class InvalidAccessError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class AbortError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class TimeoutError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class QuotaExceededError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class SyntaxError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} + class DataCloneError extends DexieError {constructor (msg?: string, inner?: Object); constructor (inner: Object);} +} + +export default Dexie; diff --git a/dist/dexie.es.js b/dist/dexie.es.js new file mode 100644 index 000000000..66ab3a0af --- /dev/null +++ b/dist/dexie.es.js @@ -0,0 +1,4464 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +var keys = Object.keys; +var isArray = Array.isArray; +var _global = typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; +function extend(obj, extension) { + if (typeof extension !== 'object') + return obj; + keys(extension).forEach(function (key) { + obj[key] = extension[key]; + }); + return obj; +} +var getProto = Object.getPrototypeOf; +var _hasOwn = {}.hasOwnProperty; +function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); +} +function props(proto, extension) { + if (typeof extension === 'function') + extension = extension(getProto(proto)); + keys(extension).forEach(function (key) { + setProp(proto, key, extension[key]); + }); +} +var defineProperty = Object.defineProperty; +function setProp(obj, prop, functionOrGetSet, options) { + defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? + { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : + { value: functionOrGetSet, configurable: true, writable: true }, options)); +} +function derive(Child) { + return { + from: function (Parent) { + Child.prototype = Object.create(Parent.prototype); + setProp(Child.prototype, "constructor", Child); + return { + extend: props.bind(null, Child.prototype) + }; + } + }; +} +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +function getPropertyDescriptor(obj, prop) { + var pd = getOwnPropertyDescriptor(obj, prop), proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); +} +var _slice = [].slice; +function slice(args, start, end) { + return _slice.call(args, start, end); +} +function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); +} +function assert(b) { + if (!b) + throw new Error("Assertion Failed"); +} +function asap(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); +} + +/** Generate an object (hash map) based on given array. + * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to + * instert on the resulting object for each item in the array. If this function returns a falsy value, the + * current item wont affect the resulting object. + */ +function arrayToObject(array, extractor) { + return array.reduce(function (result, item, i) { + var nameAndValue = extractor(item, i); + if (nameAndValue) + result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); +} +function trycatcher(fn, reject) { + return function () { + try { + fn.apply(this, arguments); + } + catch (e) { + reject(e); + } + }; +} +function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } +} +function getByKeyPath(obj, keyPath) { + // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path + if (hasOwn(obj, keyPath)) + return obj[keyPath]; // This line is moved from last to first for optimization purpose. + if (!keyPath) + return obj; + if (typeof keyPath !== 'string') { + var rv = []; + for (var i = 0, l = keyPath.length; i < l; ++i) { + var val = getByKeyPath(obj, keyPath[i]); + rv.push(val); + } + return rv; + } + var period = keyPath.indexOf('.'); + if (period !== -1) { + var innerObj = obj[keyPath.substr(0, period)]; + return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); + } + return undefined; +} +function setByKeyPath(obj, keyPath, value) { + if (!obj || keyPath === undefined) + return; + if ('isFrozen' in Object && Object.isFrozen(obj)) + return; + if (typeof keyPath !== 'string' && 'length' in keyPath) { + assert(typeof value !== 'string' && 'length' in value); + for (var i = 0, l = keyPath.length; i < l; ++i) { + setByKeyPath(obj, keyPath[i], value[i]); + } + } + else { + var period = keyPath.indexOf('.'); + if (period !== -1) { + var currentKeyPath = keyPath.substr(0, period); + var remainingKeyPath = keyPath.substr(period + 1); + if (remainingKeyPath === "") + if (value === undefined) + delete obj[currentKeyPath]; + else + obj[currentKeyPath] = value; + else { + var innerObj = obj[currentKeyPath]; + if (!innerObj) + innerObj = (obj[currentKeyPath] = {}); + setByKeyPath(innerObj, remainingKeyPath, value); + } + } + else { + if (value === undefined) + delete obj[keyPath]; + else + obj[keyPath] = value; + } + } +} +function delByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string') + setByKeyPath(obj, keyPath, undefined); + else if ('length' in keyPath) + [].map.call(keyPath, function (kp) { + setByKeyPath(obj, kp, undefined); + }); +} +function shallowClone(obj) { + var rv = {}; + for (var m in obj) { + if (hasOwn(obj, m)) + rv[m] = obj[m]; + } + return rv; +} +var concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} +//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm +var intrinsicTypes = "Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set" + .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return ["Int", "Uint", "Float"].map(function (t) { return t + num + "Array"; }); }))).filter(function (t) { return _global[t]; }).map(function (t) { return _global[t]; }); +function deepClone(any) { + if (!any || typeof any !== 'object') + return any; + var rv; + if (isArray(any)) { + rv = []; + for (var i = 0, l = any.length; i < l; ++i) { + rv.push(deepClone(any[i])); + } + } + else if (intrinsicTypes.indexOf(any.constructor) >= 0) { + rv = any; + } + else { + rv = any.constructor ? Object.create(any.constructor.prototype) : {}; + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = deepClone(any[prop]); + } + } + } + return rv; +} +function getObjectDiff(a, b, rv, prfx) { + // Compares objects a and b and produces a diff object. + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) + rv[prfx + prop] = undefined; // Property removed + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && + ap && bp && + // Now compare constructors are same (not equal because wont work in Safari) + ('' + ap.constructor) === ('' + bp.constructor)) + // Same type of object but its properties may have changed + getObjectDiff(ap, bp, rv, prfx + prop + "."); + else if (ap !== bp) + rv[prfx + prop] = b[prop]; // Primitive value changed + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; // Property added + } + }); + return rv; +} +// If first argument is iterable or array-like, return it as an array +var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; +var getIteratorOf = iteratorSymbol ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); +} : function () { return null; }; +var NO_CHAR_ARRAY = {}; +// Takes one or several arguments and returns an array based on the following criteras: +// * If several arguments provided, return arguments converted to an array in a way that +// still allows javascript engine to optimize the code. +// * If single argument is an array, return a clone of it. +// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special +// case to the two bullets below. +// * If single argument is an iterable, convert it to an array and return the resulting array. +// * If single argument is array-like (has length of type number), convert it to an array. +function getArrayOf(arrayLike) { + var i, a, x, it; + if (arguments.length === 1) { + if (isArray(arrayLike)) + return arrayLike.slice(); + if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') + return [arrayLike]; + if ((it = getIteratorOf(arrayLike))) { + a = []; + while ((x = it.next()), !x.done) + a.push(x.value); + return a; + } + if (arrayLike == null) + return [arrayLike]; + i = arrayLike.length; + if (typeof i === 'number') { + a = new Array(i); + while (i--) + a[i] = arrayLike[i]; + return a; + } + return [arrayLike]; + } + i = arguments.length; + a = new Array(i); + while (i--) + a[i] = arguments[i]; + return a; +} + +// By default, debug will be true only if platform is a web platform and its page is served from localhost. +// When debug = true, error's stacks will contain asyncronic long stacks. +var debug = typeof location !== 'undefined' && + // By default, use debug mode if served from localhost. + /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); +function setDebug(value, filter) { + debug = value; + libraryFilter = filter; +} +var libraryFilter = function () { return true; }; +var NEEDS_THROW_FOR_STACK = !new Error("").stack; +function getErrorWithStack() { + "use strict"; + if (NEEDS_THROW_FOR_STACK) + try { + // Doing something naughty in strict mode here to trigger a specific error + // that can be explicitely ignored in debugger's exception settings. + // If we'd just throw new Error() here, IE's debugger's exception settings + // will just consider it as "exception thrown by javascript code" which is + // something you wouldn't want it to ignore. + getErrorWithStack.arguments; + throw new Error(); // Fallback if above line don't throw. + } + catch (e) { + return e; + } + return new Error(); +} +function prettyStack(exception, numIgnoredFrames) { + var stack = exception.stack; + if (!stack) + return ""; + numIgnoredFrames = (numIgnoredFrames || 0); + if (stack.indexOf(exception.name) === 0) + numIgnoredFrames += (exception.name + exception.message).split('\n').length; + return stack.split('\n') + .slice(numIgnoredFrames) + .filter(libraryFilter) + .map(function (frame) { return "\n" + frame; }) + .join(''); +} +function deprecated(what, fn) { + return function () { + console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1)); + return fn.apply(this, arguments); + }; +} + +var dexieErrorNames = [ + 'Modify', + 'Bulk', + 'OpenFailed', + 'VersionChange', + 'Schema', + 'Upgrade', + 'InvalidTable', + 'MissingAPI', + 'NoSuchDatabase', + 'InvalidArgument', + 'SubTransaction', + 'Unsupported', + 'Internal', + 'DatabaseClosed', + 'PrematureCommit', + 'ForeignAwait' +]; +var idbDomErrorNames = [ + 'Unknown', + 'Constraint', + 'Data', + 'TransactionInactive', + 'ReadOnly', + 'Version', + 'NotFound', + 'InvalidState', + 'InvalidAccess', + 'Abort', + 'Timeout', + 'QuotaExceeded', + 'Syntax', + 'DataClone' +]; +var errorList = dexieErrorNames.concat(idbDomErrorNames); +var defaultTexts = { + VersionChanged: "Database version changed by other database connection", + DatabaseClosed: "Database has been closed", + Abort: "Transaction aborted", + TransactionInactive: "Transaction has already completed or failed" +}; +// +// DexieError - base class of all out exceptions. +// +function DexieError(name, msg) { + // Reason we don't use ES6 classes is because: + // 1. It bloats transpiled code and increases size of minified code. + // 2. It doesn't give us much in this case. + // 3. It would require sub classes to call super(), which + // is not needed when deriving from Error. + this._e = getErrorWithStack(); + this.name = name; + this.message = msg; +} +derive(DexieError).from(Error).extend({ + stack: { + get: function () { + return this._stack || + (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); + } + }, + toString: function () { return this.name + ": " + this.message; } +}); +function getMultiErrorMessage(msg, failures) { + return msg + ". Errors: " + failures + .map(function (f) { return f.toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) // Only unique error strings + .join('\n'); +} +// +// ModifyError - thrown in Collection.modify() +// Specific constructor because it contains members failures and failedKeys. +// +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; +} +derive(ModifyError).from(DexieError); +function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = failures; + this.message = getMultiErrorMessage(msg, failures); +} +derive(BulkError).from(DexieError); +// +// +// Dynamically generate error names and exception classes based +// on the names in errorList. +// +// +// Map of {ErrorName -> ErrorName + "Error"} +var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); +// Need an alias for DexieError because we're gonna create subclasses with the same name. +var BaseException = DexieError; +// Map of {ErrorName -> exception constructor} +var exceptions = errorList.reduce(function (obj, name) { + // Let the name be "DexieError" because this name may + // be shown in call stack and when debugging. DexieError is + // the most true name because it derives from DexieError, + // and we cannot change Function.name programatically without + // dynamically create a Function object, which would be considered + // 'eval-evil'. + var fullName = name + "Error"; + function DexieError(msgOrInner, inner) { + this._e = getErrorWithStack(); + this.name = fullName; + if (!msgOrInner) { + this.message = defaultTexts[name] || fullName; + this.inner = null; + } + else if (typeof msgOrInner === 'string') { + this.message = msgOrInner; + this.inner = inner || null; + } + else if (typeof msgOrInner === 'object') { + this.message = msgOrInner.name + " " + msgOrInner.message; + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name] = DexieError; + return obj; +}, {}); +// Use ECMASCRIPT standard exceptions where applicable: +exceptions.Syntax = SyntaxError; +exceptions.Type = TypeError; +exceptions.Range = RangeError; +var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); +function mapError(domError, message) { + if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) + return domError; + var rv = new exceptionMap[domError.name](message || domError.message, domError); + if ("stack" in domError) { + // Derive stack from inner exception if it has a stack + setProp(rv, "stack", { get: function () { + return this.inner.stack; + } }); + } + return rv; +} +var fullNameExceptions = errorList.reduce(function (obj, name) { + if (["Syntax", "Type", "Range"].indexOf(name) === -1) + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); +fullNameExceptions.ModifyError = ModifyError; +fullNameExceptions.DexieError = DexieError; +fullNameExceptions.BulkError = BulkError; + +function nop() { } +function mirror(val) { return val; } +function pureFunctionChain(f1, f2) { + // Enables chained events that takes ONE argument and returns it to the next function in chain. + // This pattern is used in the hook("reading") event. + if (f1 == null || f1 === mirror) + return f2; + return function (val) { + return f2(f1(val)); + }; +} +function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; +} +function hookCreatingChain(f1, f2) { + // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. + // This pattern is used in the hook("creating") event. + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res2 !== undefined ? res2 : res; + }; +} +function hookDeletingChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + f1.apply(this, arguments); + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = this.onerror = null; + f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + }; +} +function hookUpdatingChain(f1, f2) { + if (f1 === nop) + return f2; + return function (modifications) { + var res = f1.apply(this, arguments); + extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res === undefined ? + (res2 === undefined ? undefined : res2) : + (extend(res, res2)); + }; +} +function reverseStoppableEventChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + if (f2.apply(this, arguments) === false) + return false; + return f1.apply(this, arguments); + }; +} + +function promisableChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} + +/* + * Copyright (c) 2014-2017 David Fahlander + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + */ +// +// Promise and Zone (PSD) for Dexie library +// +// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by +// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. +// +// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another +// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use +// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task +// engine that is indexedDB compliant across all browsers. +// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. +// Also with inspiration from bluebird, asyncronic stacks in debug mode. +// +// Specific non-standard features of this Promise class: +// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as +// native async / await. +// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame +// and below + all promises that those promises creates or awaits. +// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). +// +// David Fahlander, https://github.com/dfahlander +// +// Just a pointer that only this module knows about. +// Used in Promise constructor to emulate a private constructor. +var INTERNAL = {}; +// Async stacks (long stacks) must not grow infinitely. +var LONG_STACKS_CLIP_LIMIT = 100; +var MAX_LONG_STACKS = 20; +var ZONE_ECHO_LIMIT = 7; +var nativePromiseInstanceAndProto = (function () { + try { + // Be able to patch native async functions + return new Function("let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];")(); + } + catch (e) { + var P = _global.Promise; + return P ? + [P.resolve(), P.prototype, P.resolve()] : + []; + } +})(); +var resolvedNativePromise = nativePromiseInstanceAndProto[0]; +var nativePromiseProto = nativePromiseInstanceAndProto[1]; +var resolvedGlobalPromise = nativePromiseInstanceAndProto[2]; +var nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +var AsyncFunction = nativePromiseInstanceAndProto[3]; +var patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +/* The default function used only for the very first promise in a promise chain. + As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks + emulated in this module. For indexedDB compatibility, this means that every method needs to + execute at least one promise before doing an indexedDB operation. Dexie will always call + db.ready().then() for every operation to make sure the indexedDB event is started in an + indexedDB-compatible emulated micro task loop. +*/ +var schedulePhysicalTick = resolvedGlobalPromise ? + function () { resolvedGlobalPromise.then(physicalTick); } + : + _global.setImmediate ? + // setImmediate supported. Those modern platforms also supports Function.bind(). + setImmediate.bind(null, physicalTick) : + _global.MutationObserver ? + // MutationObserver supported + function () { + var hiddenDiv = document.createElement("div"); + (new MutationObserver(function () { + physicalTick(); + hiddenDiv = null; + })).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + // No support for setImmediate or MutationObserver. No worry, setTimeout is only called + // once time. Every tick that follows will be our emulated micro tick. + // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug + function () { setTimeout(physicalTick, 0); }; +// Configurable through Promise.scheduler. +// Don't export because it would be unsafe to let unknown +// code call it unless they do try..catch within their callback. +// This function can be retrieved through getter of Promise.scheduler though, +// but users must not do Promise.scheduler = myFuncThatThrowsException +var asap$1 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; +var isOutsideMicroTick = true; +var needsNewPhysicalTick = true; +var unhandledErrors = []; +var rejectingErrors = []; +var currentFulfiller = null; +var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + finalize: function () { + this.unhandleds.forEach(function (uh) { + try { + globalError(uh[0], uh[1]); + } + catch (e) { } + }); + } +}; +var PSD = globalPSD; +var microtickQueue = []; // Callbacks to call in this or next physical tick. +var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. +var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. +function Promise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. + // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() + // execute the microtask engine implicitely within the call to resolve() or reject(). + // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack + // only contains library code when calling resolve() or reject(). + // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from + // global scope (event handler, timer etc)! + this._lib = false; + // Current async scope + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; // Number of previous promises (for long stacks) + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + // Private constructor (INTERNAL, state, value). + // Used internally by Promise.resolve() and Promise.reject(). + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). + return; + } + this._state = null; // null (=pending), false (=rejected) or true (=resolved) + this._value = null; // error or result + ++psd.ref; // Refcounting current scope + executePromiseTask(this, fn); +} +// Prepare a property descriptor to put onto Promise.prototype.then +var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + if (possibleAwait) + decrementExpectedAwaits(); + var rv = new Promise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; // For idempotense, see setter below. + return then; + }, + // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then + // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor. + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : // Restore to original property descriptor. + { + get: function () { + return value; // Getter returning provided value (behaves like value is just changed) + }, + set: thenProp.set // Keep a setter that is prepared to restore original. + }); + } +}; +props(Promise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + // A little tinier version of then() that don't have to create a resulting promise. + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + // First argument is the Error type to catch + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + // Catching errors by its constructor type (similar to java / c++ / c#) + // Sample: promise.catch(TypeError, function (e) { ... }); + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (err) { + // Catching errors by the error.name property. Makes sense for indexedDB where error type + // is always DOMError but where e.name tells the actual error type. + // Sample: promise.catch('ConstraintError', function (e) { ... }); + return err && err.name === type ? handler(err) : PromiseReject(err); + }); + }, + finally: function (onFinally) { + return this.then(function (value) { + onFinally(); + return value; + }, function (err) { + onFinally(); + return PromiseReject(err); + }); + }, + stack: { + get: function () { + if (this._stack) + return this._stack; + try { + stack_being_generated = true; + var stacks = getStack(this, [], MAX_LONG_STACKS); + var stack = stacks.join("\nFrom previous: "); + if (this._state !== null) + this._stack = stack; // Stack may be updated on reject. + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new Promise(function (resolve, reject) { + var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } +}); +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) + setProp(Promise.prototype, Symbol.toStringTag, 'Promise'); +// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env. +// Environment globals snapshotted on leaving global zone +globalPSD.env = snapShot(); +function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; +} +// Promise Static Properties +props(Promise, { + all: function () { + var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like. + .map(onPossibleParallellAsync); // Handle parallell async/awaits + return new Promise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return Promise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof Promise) + return value; + if (value && typeof value.then === 'function') + return new Promise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new Promise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new Promise(function (resolve, reject) { + values.map(function (value) { return Promise.resolve(value).then(resolve, reject); }); + }); + }, + PSD: { + get: function () { return PSD; }, + set: function (value) { return PSD = value; } + }, + //totalEchoes: {get: ()=>totalEchoes}, + //task: {get: ()=>task}, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap$1; }, + set: function (value) { asap$1 = value; } + }, + rejectionMapper: { + get: function () { return rejectionMapper; }, + set: function (value) { rejectionMapper = value; } // Map reject failures + }, + follow: function (fn, zoneProps) { + return new Promise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() + psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. + psd.finalize = callBoth(function () { + var _this = this; + // Unhandled standard or 3rd part promises are put in PSD.unhandleds and + // examined upon scope completion while unhandled rejections in this Promise + // will trigger directly through psd.onunhandled + run_at_end_of_this_or_next_physical_tick(function () { + _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +/** +* Take a potentially misbehaving resolver function and make sure +* onFulfilled and onRejected are only called once. +* +* Makes no guarantees about asynchrony. +*/ +function executePromiseTask(promise, fn) { + // Promise Resolution Procedure: + // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + try { + fn(function (value) { + if (promise._state !== null) + return; // Already settled + if (value === promise) + throw new TypeError('A promise cannot be resolved with itself.'); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === 'function') { + executePromiseTask(promise, function (resolve, reject) { + value instanceof Promise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below + } + catch (ex) { + handleRejection(promise, ex); + } +} +function handleRejection(promise, reason) { + rejectingErrors.push(reason); + if (promise._state !== null) + return; + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + reason = rejectionMapper(reason); + promise._state = false; + promise._value = reason; + debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () { + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: function () { + return stack_being_generated ? + origProp && (origProp.get ? + origProp.get.apply(reason) : + origProp.value) : + promise.stack; + } + }); + }); + // Add the failure to a list of possibly uncaught errors + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); +} +function propagateAllListeners(promise) { + //debug && linkToPreviousPromise(promise); + var listeners = promise._listeners; + promise._listeners = []; + for (var i = 0, len = listeners.length; i < len; ++i) { + propagateToListener(promise, listeners[i]); + } + var psd = promise._PSD; + --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); + if (numScheduledCalls === 0) { + // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, + // and that no deferreds where listening to this rejection or success. + // Since there is a risk that our stack can contain application code that may + // do stuff after this code is finished that may generate new calls, we cannot + // call finalizers here. + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); // Will detect unhandled errors + }, []); + } +} +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap$1(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + // Set static variable currentFulfiller to the promise that is being fullfilled, + // so that we connect the chain of promises (for long stacks support) + currentFulfiller = promise; + // Call callback and resolve our listener with it's return value. + var ret, value = promise._value; + if (promise._state) { + // cb is onResolved + ret = cb(value); + } + else { + // cb is onRejected + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. + } + listener.resolve(ret); + } + catch (e) { + // Exception thrown in callback. Reject our listener. + listener.reject(e); + } + finally { + // Restore env and currentFulfiller. + currentFulfiller = null; + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + --listener.psd.ref || listener.psd.finalize(); + } +} +function getStack(promise, stacks, limit) { + if (stacks.length === limit) + return stacks; + var stack = ""; + if (promise._state === false) { + var failure = promise._value, errorName, message; + if (failure != null) { + errorName = failure.name || "Error"; + message = failure.message || failure; + stack = prettyStack(failure, 0); + } + else { + errorName = failure; // If error is undefined or null, show that. + message = ""; + } + stacks.push(errorName + (message ? ": " + message : "") + stack); + } + if (debug) { + stack = prettyStack(promise._stackHolder, 2); + if (stack && stacks.indexOf(stack) === -1) + stacks.push(stack); + if (promise._prev) + getStack(promise._prev, stacks, limit); + } + return stacks; +} +function linkToPreviousPromise(promise, prev) { + // Support long stacks by linking to previous completed promise. + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } +} +/* The callback to schedule with setImmediate() or setTimeout(). + It runs a virtual microtick and executes any callback registered in microtickQueue. + */ +function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); +} +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} +/* Executes micro-ticks without doing try..catch. + This can be possible because we only use this internally and + the registered functions are exception-safe (they do try..catch + internally before calling any external method). If registering + functions in the microtickQueue that are not exception-safe, this + would destroy the framework and make it instable. So we don't export + our asap method. +*/ +function endMicroTickScope() { + var callbacks, i, l; + do { + while (microtickQueue.length > 0) { + callbacks = microtickQueue; + microtickQueue = []; + l = callbacks.length; + for (i = 0; i < l; ++i) { + var item = callbacks[i]; + item[0].apply(null, item[1]); + } + } + } while (microtickQueue.length > 0); + isOutsideMicroTick = true; + needsNewPhysicalTick = true; +} +function finalizePhysicalTick() { + var unhandledErrs = unhandledErrors; + unhandledErrors = []; + unhandledErrs.forEach(function (p) { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. + var i = finalizers.length; + while (i) + finalizers[--i](); +} +function run_at_end_of_this_or_next_physical_tick(fn) { + function finalizer() { + fn(); + tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); + } + tickFinalizers.push(finalizer); + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); +} +function addPossiblyUnhandledError(promise) { + // Only add to unhandledErrors if not already there. The first one to add to this list + // will be upon the first rejection so that the root cause (first promise in the + // rejection chain) is the one listed. + if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) + unhandledErrors.push(promise); +} +function markErrorAsHandled(promise) { + // Called when a reject handled is actually being called. + // Search in unhandledErrors for any promise whos _value is this promise_value (list + // contains only rejected promises, and only one item per error) + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + // Found a promise that failed with this same error object pointer, + // Remove that since there is a listener that actually takes care of it. + unhandledErrors.splice(i, 1); + return; + } +} +function PromiseReject(reason) { + return new Promise(INTERNAL, false, reason); +} +function wrap(fn, errorCatcher) { + var psd = PSD; + return function () { + var wasRootExec = beginMicroTickScope(), outerScope = PSD; + try { + switchToZone(psd, true); + return fn.apply(this, arguments); + } + catch (e) { + errorCatcher && errorCatcher(e); + } + finally { + switchToZone(outerScope, false); + if (wasRootExec) + endMicroTickScope(); + } + }; +} +// +// variables used for native await support +// +var task = { awaits: 0, echoes: 0, id: 0 }; // The ongoing macro-task when using zone-echoing. +var taskCounter = 0; // ID counter for macro tasks. +var zoneStack = []; // Stack of left zones to restore asynchronically. +var zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions. +var totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then. +var zone_id_counter = 0; +function newScope(fn, props$$1, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + // Prepare for promise patching (done in usePSD): + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: Promise, + PromiseProp: { value: Promise, configurable: true, writable: true }, + all: Promise.all, + race: Promise.race, + resolve: Promise.resolve, + reject: Promise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) // global then + } : {}; + if (props$$1) + extend(psd, props$$1); + // unhandleds and onunhandled should not be specifically set here. + // Leave them on parent prototype. + // unhandleds.push(err) will push to parent's prototype + // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2); + if (psd.ref === 0) + psd.finalize(); + return rv; +} +// Function to call if scopeFunc returns NativePromise +// Also for each NativePromise in the arguments to Promise.all() +function incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called. +// Also call this when a native await calls then method on a promise. In that case, don't supply +// sourceTaskId because we already know it refers to current task. +function decrementExpectedAwaits(sourceTaskId) { + if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) + return; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0. +} +// Call from Promise.all() and Promise.race() +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; +} +function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; // Cancel zone echoing. + } + zoneStack.push(PSD); + switchToZone(targetZone, true); +} +function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); +} +function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { + // Enter or leave zone asynchronically as well, so that tasks initiated during current tick + // will be surrounded by the zone when they are invoked. + enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; // The actual zone switch occurs at this line. + // Snapshot on every leave from global zone. + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + // Let's patch the global and native Promises (may be same or may be different) + var GlobalPromise = globalPSD.env.Promise; + // Swich environments (may be PSD-zone or the global zone. Both apply.) + var targetEnv = targetZone.env; + // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed) + // Must be done on each zone change because the patched method contains targetZone in its closure. + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + // Leaving or entering global zone. It's time to patch / restore global Promise. + // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular. + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might + // not be accessing global.Promise but a local reference to it) + GlobalPromise.all = targetEnv.all; + GlobalPromise.race = targetEnv.race; + GlobalPromise.resolve = targetEnv.resolve; + GlobalPromise.reject = targetEnv.reject; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject, + nthen: nativePromiseProto.then, + gthen: GlobalPromise.prototype.then + } : {}; +} +function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } + finally { + switchToZone(outerScope, false); + } +} +function enqueueNativeMicroTask(job) { + // + // Precondition: nativePromiseThen !== undefined + // + nativePromiseThen.call(resolvedNativePromise, job); +} +function nativeAwaitCompatibleWrap(fn, zone, possibleAwait) { + return typeof fn !== 'function' ? fn : function () { + var outerZone = PSD; + if (possibleAwait) + incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } + finally { + switchToZone(outerZone, false); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone, false), nativeAwaitCompatibleWrap(onRejected, zone, false)); + }; +} +var UNHANDLEDREJECTION = "unhandledrejection"; +function globalError(err, promise) { + var rv; + try { + rv = promise.onuncatched(err); + } + catch (e) { } + if (rv !== false) + try { + var event, eventData = { promise: promise, reason: err }; + if (_global.document && document.createEvent) { + event = document.createEvent('Event'); + event.initEvent(UNHANDLEDREJECTION, true, true); + extend(event, eventData); + } + else if (_global.CustomEvent) { + event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); + extend(event, eventData); + } + if (event && _global.dispatchEvent) { + dispatchEvent(event); + if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) + // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. + try { + _global.onunhandledrejection(event); + } + catch (_) { } + } + if (!event.defaultPrevented) { + console.warn("Unhandled rejection: " + (err.stack || err)); + } + } + catch (e) { } +} +var rejection = Promise.reject; + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. + var i = arguments.length, args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + evs[eventName].subscribe.apply(null, args); + return ctx; + } + else if (typeof (eventName) === 'string') { + // Return interface allowing to fire or unsubscribe from event + return evs[eventName]; + } + }; + rv.addEventType = add; + for (var i = 1, l = arguments.length; i < l; ++i) { + add(arguments[i]); + } + return rv; + function add(eventName, chainFunction, defaultFunction) { + if (typeof eventName === 'object') + return addConfiguredEvents(eventName); + if (!chainFunction) + chainFunction = reverseStoppableEventChain; + if (!defaultFunction) + defaultFunction = nop; + var context = { + subscribers: [], + fire: defaultFunction, + subscribe: function (cb) { + if (context.subscribers.indexOf(cb) === -1) { + context.subscribers.push(cb); + context.fire = chainFunction(context.fire, cb); + } + }, + unsubscribe: function (cb) { + context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); + context.fire = context.subscribers.reduce(chainFunction, defaultFunction); + } + }; + evs[eventName] = rv[eventName] = context; + return context; + } + function addConfiguredEvents(cfg) { + // events(this, {reading: [functionChain, nop]}); + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack + // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. + var context = add(eventName, mirror, function fire() { + // Optimazation-safe cloning of arguments into args. + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + // All each subscriber: + context.subscribers.forEach(function (fn) { + asap(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * Copyright (c) 2014-2017 David Fahlander + * + * Version {version}, {date} + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + * + */ +var DEXIE_VERSION = '{version}'; +var maxString = String.fromCharCode(65535); +var maxKey = (function () { try { + IDBKeyRange.only([[]]); + return [[]]; +} +catch (e) { + return maxString; +} })(); +var minKey = -Infinity; +var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; +var STRING_EXPECTED = "String expected."; +var connections = []; +var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); +var hasIEDeleteObjectStoreBug = isIEOrEdge; +var hangsOnDeleteLargeKeyRange = isIEOrEdge; +var dexieStackFrameFilter = function (frame) { return !/(dexie\.js|dexie\.min\.js)/.test(frame); }; +var dbNamesDB; // Global database for backing Dexie.getDatabaseNames() on browser without indexedDB.webkitGetDatabaseNames() +// Init debug +setDebug(debug, dexieStackFrameFilter); +function Dexie(dbName, options) { + /// Specify only if you wich to control which addons that should run on this instance + var deps = Dexie.dependencies; + var opts = extend({ + // Default Options + addons: Dexie.addons, + autoOpen: true, + indexedDB: deps.indexedDB, + IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to browser env. + }, options); + var addons = opts.addons, autoOpen = opts.autoOpen, indexedDB = opts.indexedDB, IDBKeyRange = opts.IDBKeyRange; + var globalSchema = this._dbSchema = {}; + var versions = []; + var dbStoreNames = []; + var allTables = {}; + /// + var idbdb = null; // Instance of IDBDatabase + var dbOpenError = null; + var isBeingOpened = false; + var onReadyBeingFired = null; + var openComplete = false; + var READONLY = "readonly", READWRITE = "readwrite"; + var db = this; + var dbReadyResolve, dbReadyPromise = new Promise(function (resolve) { + dbReadyResolve = resolve; + }), cancelOpen, openCanceller = new Promise(function (_, reject) { + cancelOpen = reject; + }); + var autoSchema = true; + var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), hasGetAll; + function init() { + // Default subscribers to "versionchange" and "blocked". + // Can be overridden by custom handlers. If custom handlers return false, these default + // behaviours will be prevented. + db.on("versionchange", function (ev) { + // Default behavior for versionchange event is to close database connection. + // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); + // Let's not block the other window from making it's delete() or open() call. + // NOTE! This event is never fired in IE,Edge or Safari. + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '" + db.name + "'. Closing db now to resume the upgrade."); + else + console.warn("Another connection wants to delete database '" + db.name + "'. Closing db now to resume the delete request."); + db.close(); + // In many web applications, it would be recommended to force window.reload() + // when this event occurs. To do that, subscribe to the versionchange event + // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) + // The reason for this is that your current web app obviously has old schema code that needs + // to be updated. Another window got a newer version of the app and needs to upgrade DB but + // your window is blocking it unless we close it here. + }); + db.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('" + db.name + "') was blocked"); + else + console.warn("Upgrade '" + db.name + "' blocked by other connection holding version " + ev.oldVersion / 10); + }); + } + // + // + // + // ------------------------- Versioning Framework--------------------------- + // + // + // + this.version = function (versionNumber) { + /// + /// + if (idbdb || isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + // Disable autoschema mode, as at least one version is specified. + autoSchema = false; + return versionInstance; + }; + function Version(versionNumber) { + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + this.stores({}); // Derive earlier schemas by default. + } + extend(Version.prototype, { + stores: function (stores) { + /// + /// Defines the schema for a particular version + /// + /// + /// Example:
+ /// {users: "id++,first,last,&username,*email",
+ /// passwords: "id++,&username"}
+ ///
+ /// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}

+ /// Special characters:
+ /// "&" means unique key,
+ /// "*" means value is multiEntry,
+ /// "++" means auto-increment and only applicable for primary key
+ /// + this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; + // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. + var storesSpec = {}; + versions.forEach(function (version) { + extend(storesSpec, version._cfg.storesSource); + }); + var dbschema = (this._cfg.dbschema = {}); + this._parseStoresSpec(storesSpec, dbschema); + // Update the latest schema to this version + // Update API + globalSchema = db._dbSchema = dbschema; + removeTablesApi([allTables, db, Transaction.prototype]); // Keep Transaction.prototype even though it should be depr. + setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + dbStoreNames = keys(dbschema); + return this; + }, + upgrade: function (upgradeFunction) { + /// Function that performs upgrading actions. + var self = this; + this._cfg.contentUpgrade = upgradeFunction; + return this; + }, + _parseStoresSpec: function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var instanceTemplate = {}; + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + if (primKey.keyPath) + setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); + indexes.forEach(function (idx) { + if (idx.auto) + throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); + if (!idx.keyPath) + throw new exceptions.Schema("Index must have a name and cannot be an empty string"); + setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : ""); + }); + outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); + } + }); + } + }); + function runUpgraders(oldVersion, idbtrans, reject) { + var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); + trans.create(idbtrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + newScope(function () { + PSD.trans = trans; + if (oldVersion === 0) { + // Create tables: + keys(globalSchema).forEach(function (tableName) { + createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + Promise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); + } + else + updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); + }); + } + function updateTablesAndIndexes(oldVersion, trans, idbtrans) { + // Upgrade version to version, step-by-step from oldest to newest version. + // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) + var queue = []; + var oldVersionStruct = versions.filter(function (version) { return version._cfg.version === oldVersion; })[0]; + if (!oldVersionStruct) + throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); + globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; + var anyContentUpgraderHasRun = false; + var versToRun = versions.filter(function (v) { return v._cfg.version > oldVersion; }); + versToRun.forEach(function (version) { + /// + queue.push(function () { + var oldSchema = globalSchema; + var newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(oldSchema, idbtrans); + adjustToExistingIndexNames(newSchema, idbtrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + // Add tables + diff.add.forEach(function (tuple) { + createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + // Change tables + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + var store = idbtrans.objectStore(change.name); + // Add indexes + change.add.forEach(function (idx) { + addIndex(store, idx); + }); + // Update indexes + change.change.forEach(function (idx) { + store.deleteIndex(idx.name); + addIndex(store, idx); + }); + // Delete indexes + change.del.forEach(function (idxName) { + store.deleteIndex(idxName); + }); + } + }); + if (version._cfg.contentUpgrade) { + anyContentUpgraderHasRun = true; + return Promise.follow(function () { + version._cfg.contentUpgrade(trans); + }); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + var newSchema = version._cfg.dbschema; + // Delete old tables + deleteRemovedTables(newSchema, idbtrans); + } + }); + }); + // Now, create a queue execution engine + function runQueue() { + return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + Promise.resolve(); + } + return runQueue().then(function () { + createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) + }); + } + function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} + }; + for (var table in oldSchema) { + if (!newSchema[table]) + diff.del.push(table); + } + for (table in newSchema) { + var oldDef = oldSchema[table], newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } + else { + var change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if (oldDef.primKey.src !== newDef.primKey.src) { + // Primary key has changed. Remove and re-add table. + change.recreate = true; + diff.change.push(change); + } + else { + // Same primary key. Just find out what differs: + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + for (var idxName in oldIndexes) { + if (!newIndexes[idxName]) + change.del.push(idxName); + } + for (idxName in newIndexes) { + var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; + if (!oldIdx) + change.add.push(newIdx); + else if (oldIdx.src !== newIdx.src) + change.change.push(newIdx); + } + if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { + diff.change.push(change); + } + } + } + } + return diff; + } + function createTable(idbtrans, tableName, primKey, indexes) { + /// + var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); + indexes.forEach(function (idx) { addIndex(store, idx); }); + return store; + } + function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(function (tableName) { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); + } + function deleteRemovedTables(newSchema, idbtrans) { + for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { + var storeName = idbtrans.db.objectStoreNames[i]; + if (newSchema[storeName] == null) { + idbtrans.db.deleteObjectStore(storeName); + } + } + } + function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); + } + // + // + // Dexie Protected API + // + // + this._allTables = allTables; + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { + return new Transaction(mode, storeNames, dbschema, parentTransaction); + }; + /* Generate a temporary transaction when db operations are done outside a transaction scope. + */ + function tempTransaction(mode, storeNames, fn) { + if (!openComplete && (!PSD.letThrough)) { + if (!isBeingOpened) { + if (!autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + return dbReadyPromise.then(function () { return tempTransaction(mode, storeNames, fn); }); + } + else { + var trans = db._createTransaction(mode, storeNames, globalSchema); + try { + trans.create(); + } + catch (ex) { + return rejection(ex); + } + return trans._promise(mode, function (resolve, reject) { + return newScope(function () { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function (result) { + // Instead of resolving value directly, wait with resolving it until transaction has completed. + // Otherwise the data would not be in the DB if requesting it in the then() operation. + // Specifically, to ensure that the following expression will work: + // + // db.friends.put({name: "Arne"}).then(function () { + // db.friends.where("name").equals("Arne").count(function(count) { + // assert (count === 1); + // }); + // }); + // + return trans._completion.then(function () { return result; }); + }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. + trans._reject(err); + return rejection(err); + });*/ + } + } + this._whenReady = function (fn) { + return openComplete || PSD.letThrough ? fn() : new Promise(function (resolve, reject) { + if (!isBeingOpened) { + if (!autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + // + // + // + // + // Dexie API + // + // + // + this.verno = 0; + this.open = function () { + if (isBeingOpened || idbdb) + return dbReadyPromise.then(function () { return dbOpenError ? rejection(dbOpenError) : db; }); + debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. + isBeingOpened = true; + dbOpenError = null; + openComplete = false; + // Function pointers to call when the core opening process completes. + var resolveDbReady = dbReadyResolve, + // upgradeTransaction to abort on failure. + upgradeTransaction = null; + return Promise.race([openCanceller, new Promise(function (resolve, reject) { + // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: + // IE fails when deleting objectStore after reading from it. + // A future version of Dexie.js will stopover an intermediate version to workaround this. + // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. + // If no API, throw! + if (!indexedDB) + throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); + var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (autoSchema && !db._allowEmptyDB) { + // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. + // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we + // do not create a new database by accident here. + req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! + upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) + // Close database and delete it. + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase("Database " + dbName + " doesnt exist")); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. + runUpgraders(oldVer / 10, upgradeTransaction, reject, req); + } + }, reject); + req.onsuccess = wrap(function () { + // Core opening procedure complete. Now let's just record some stuff. + upgradeTransaction = null; + idbdb = req.result; + connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. + if (autoSchema) + readGlobalSchema(); + else if (idbdb.objectStoreNames.length > 0) { + try { + adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); + } + catch (e) { + // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. + } + } + idbdb.onversionchange = wrap(function (ev) { + db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) + db.on("versionchange").fire(ev); + }); + if (!hasNativeGetDatabaseNames && dbName !== '__dbnames') { + dbNamesDB.dbnames.put({ name: dbName }).catch(nop); + } + resolve(); + }, reject); + })]).then(function () { + // Before finally resolving the dbReadyPromise and this promise, + // call and await all on('ready') subscribers: + // Dexie.vip() makes subscribers able to use the database while being opened. + // This is a must since these subscribers take part of the opening procedure. + onReadyBeingFired = []; + return Promise.resolve(Dexie.vip(db.on.ready.fire)).then(function fireRemainders() { + if (onReadyBeingFired.length > 0) { + // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed. + var remainders = onReadyBeingFired.reduce(promisableChain, nop); + onReadyBeingFired = []; + return Promise.resolve(Dexie.vip(remainders)).then(fireRemainders); + } + }); + }).finally(function () { + onReadyBeingFired = null; + }).then(function () { + // Resolve the db.open() with the db instance. + isBeingOpened = false; + return db; + }).catch(function (err) { + try { + // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. + upgradeTransaction && upgradeTransaction.abort(); + } + catch (e) { } + isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). + db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. + // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. + dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. + return rejection(dbOpenError); + }).finally(function () { + openComplete = true; + resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. + }); + }; + this.close = function () { + var idx = connections.indexOf(db); + if (idx >= 0) + connections.splice(idx, 1); + if (idbdb) { + try { + idbdb.close(); + } + catch (e) { } + idbdb = null; + } + autoOpen = false; + dbOpenError = new exceptions.DatabaseClosed(); + if (isBeingOpened) + cancelOpen(dbOpenError); + // Reset dbReadyPromise promise: + dbReadyPromise = new Promise(function (resolve) { + dbReadyResolve = resolve; + }); + openCanceller = new Promise(function (_, reject) { + cancelOpen = reject; + }); + }; + this.delete = function () { + var hasArguments = arguments.length > 0; + return new Promise(function (resolve, reject) { + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (isBeingOpened) { + dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + function doDelete() { + db.close(); + var req = indexedDB.deleteDatabase(dbName); + req.onsuccess = wrap(function () { + if (!hasNativeGetDatabaseNames) { + dbNamesDB.dbnames.delete(dbName).catch(nop); + } + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = fireOnBlocked; + } + }); + }; + this.backendDB = function () { + return idbdb; + }; + this.isOpen = function () { + return idbdb !== null; + }; + this.hasBeenClosed = function () { + return dbOpenError && (dbOpenError instanceof exceptions.DatabaseClosed); + }; + this.hasFailed = function () { + return dbOpenError !== null; + }; + this.dynamicallyOpened = function () { + return autoSchema; + }; + // + // Properties + // + this.name = dbName; + // db.tables - an array of all Table instances. + props(this, { + tables: { + get: function () { + /// + return keys(allTables).map(function (name) { return allTables[name]; }); + } + } + }); + // + // Events + // + this.on = Events(this, "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + if (openComplete) { + // Database already open. Call subscriber asap. + if (!dbOpenError) + Promise.resolve().then(subscriber); + // bSticky: Also subscribe to future open sucesses (after close / reopen) + if (bSticky) + subscribe(subscriber); + } + else if (onReadyBeingFired) { + // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected + onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + // Database not yet open. Subscribe to it. + subscribe(subscriber); + // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. + if (!bSticky) + subscribe(function unsubscribe() { + db.on.ready.unsubscribe(subscriber); + db.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.transaction = function () { + /// + /// + /// + /// "r" for readonly, or "rw" for readwrite + /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction + /// Function to execute with transaction + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + // Let table arguments be all arguments between mode and last argument. + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) + // and clone arguments except the first one into local var 'args'. + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. + scopeFunc = args.pop(); + var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. + return [mode, tables, scopeFunc]; + } + this._transaction = function (mode, tables, scopeFunc) { + var parentTransaction = PSD.trans; + // Check if parent transactions is bound to this db instance, and if caller wants to reuse it + if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. + try { + // + // Get storeNames from arguments. Either through given table instances, or through given table names. + // + var storeNames = tables.map(function (table) { + var storeName = table instanceof Table ? table.name : table; + if (typeof storeName !== 'string') + throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); + return storeName; + }); + // + // Resolve mode. Allow shortcuts "r" and "rw". + // + if (mode == "r" || mode == READONLY) + mode = READONLY; + else if (mode == "rw" || mode == READWRITE) + mode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + // Basic checks + if (parentTransaction.mode === READONLY && mode === READWRITE) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); + } + if (parentTransaction) { + storeNames.forEach(function (storeName) { + if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + // '?' mode should not keep using an inactive transaction. + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, function (_, reject) { reject(e); }) : + rejection(e); + } + // If this is a sub-transaction, lock the parent and then launch the sub-transaction. + return (parentTransaction ? + parentTransaction._promise(mode, enterTransactionScope, "lock") : + PSD.trans ? + // no parent transaction despite PSD.trans exists. Make sure also + // that the zone we create is not a sub-zone of current, because + // Promise.follow() should not wait for it if so. + usePSD(PSD.transless, function () { return db._whenReady(enterTransactionScope); }) : + db._whenReady(enterTransactionScope)); + function enterTransactionScope() { + return Promise.resolve().then(function () { + // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). + var transless = PSD.transless || PSD; + // Our transaction. + //return new Promise((resolve, reject) => { + var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); + // Let the transaction instance be part of a Promise-specific data (PSD) value. + var zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) + trans.idbtrans = parentTransaction.idbtrans; + } + else { + trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. + } + // Support for native async await. + if (scopeFunc.constructor === AsyncFunction) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = Promise.follow(function () { + // Finally, call the scope function with our table and transaction arguments. + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (returnValue.constructor === NativePromise) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + // scopeFunc returned an iterator with throw-support. Handle yield as await. + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + // Promise returned. User uses promise-style transactions. + Promise.resolve(returnValue).then(function (x) { return trans.active ? + x // Transaction still active. Continue. + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) + // No promise returned. Wait for all outstanding promises before continuing. + : promiseFollowed.then(function () { return returnValue; })).then(function (x) { + // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion: + if (parentTransaction) + trans._resolve(); + // wait for trans._completion + // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves) + return trans._completion.then(function () { return x; }); + }).catch(function (e) { + trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! + return rejection(e); + }); + }); + } + }; + this.table = function (tableName) { + /// + if (!hasOwn(allTables, tableName)) { + throw new exceptions.InvalidTable("Table " + tableName + " does not exist"); + } + return allTables[tableName]; + }; + // + // + // + // Table Class + // + // + // + function Table(name, tableSchema, optionalTrans) { + /// + this.name = name; + this.schema = tableSchema; + this._tx = optionalTrans; + this.hook = allTables[name] ? allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + } + function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { + return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) { + errorList.push(e); + done && done(); + }); + } + function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { + // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], + // else keysOrTuples must be just an array of keys: [key1, key2, ...]. + return new Promise(function (resolve, reject) { + var len = keysOrTuples.length, lastItem = len - 1; + if (len === 0) + return resolve(); + if (!hasDeleteHook) { + for (var i = 0; i < len; ++i) { + var req = idbstore.delete(keysOrTuples[i]); + req.onerror = eventRejectHandler(reject); + if (i === lastItem) + req.onsuccess = wrap(function () { return resolve(); }); + } + } + else { + var hookCtx, errorHandler = hookedEventRejectHandler(reject), successHandler = hookedEventSuccessHandler(null); + tryCatch(function () { + for (var i = 0; i < len; ++i) { + hookCtx = { onsuccess: null, onerror: null }; + var tuple = keysOrTuples[i]; + deletingHook.call(hookCtx, tuple[0], tuple[1], trans); + var req = idbstore.delete(tuple[0]); + req._hookCtx = hookCtx; + req.onerror = errorHandler; + if (i === lastItem) + req.onsuccess = hookedEventSuccessHandler(resolve); + else + req.onsuccess = successHandler; + } + }, function (err) { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + } + }); + } + props(Table.prototype, { + // + // Table Protected Methods + // + _trans: function getTransaction(mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + return trans && trans.db === db ? + trans === PSD.trans ? + trans._promise(mode, fn, writeLocked) : + newScope(function () { return trans._promise(mode, fn, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(mode, [this.name], fn); + }, + _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { + var tableName = this.name; + function supplyIdbStore(resolve, reject, trans) { + if (trans.storeNames.indexOf(tableName) === -1) + throw new exceptions.NotFound("Table" + tableName + " not part of transaction"); + return fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); + } + return this._trans(mode, supplyIdbStore, writeLocked); + }, + // + // Table Public Methods + // + get: function (keyOrCrit, cb) { + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + var self = this; + return this._idbstore(READONLY, function (resolve, reject, idbstore) { + var req = idbstore.get(keyOrCrit); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(self.hook.reading.fire(req.result)); + }, reject); + }).then(cb); + }, + where: function (indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new WhereClause(this, "[" + indexOrCrit.join('+') + "]"); + // indexOrCrit is an object map of {[keyPath]:value} + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + // Only one critera. This was the easy case: + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + // Multiple criterias. + // Let's try finding a compound index that matches all keyPaths in + // arbritary order: + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { + return ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; }) && + ix.keyPath.every(function (keyPath) { return keyPaths.indexOf(keyPath) >= 0; }); + })[0]; + if (compoundIndex && maxKey !== maxString) + // Cool! We found such compound index + // and this browser supports compound indexes (maxKey !== maxString)! + return this + .where(compoundIndex.name) + .equals(compoundIndex.keyPath.map(function (kp) { return indexOrCrit[kp]; })); + if (!compoundIndex) + console.warn("The query " + JSON.stringify(indexOrCrit) + " on " + this.name + " would benefit of a " + + ("compound index [" + keyPaths.join('+') + "]")); + // Ok, now let's fallback to finding at least one matching index + // and filter the rest. + var idxByName = this.schema.idxByName; + var simpleIndex = keyPaths.reduce(function (r, keyPath) { return [ + r[0] || idxByName[keyPath], + r[0] || !idxByName[keyPath] ? + combine(r[1], function (x) { return '' + getByKeyPath(x, keyPath) == + '' + indexOrCrit[keyPath]; }) + : r[1] + ]; }, [null, null]); + var idx = simpleIndex[0]; + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(simpleIndex[1]) : + compoundIndex ? + this.filter(simpleIndex[1]) : // Has compound but browser bad. Allow filter. + this.where(keyPaths).equals(''); // No index at all. Fail lazily. + }, + count: function (cb) { + return this.toCollection().count(cb); + }, + offset: function (offset) { + return this.toCollection().offset(offset); + }, + limit: function (numRows) { + return this.toCollection().limit(numRows); + }, + reverse: function () { + return this.toCollection().reverse(); + }, + filter: function (filterFunction) { + return this.toCollection().and(filterFunction); + }, + each: function (fn) { + return this.toCollection().each(fn); + }, + toArray: function (cb) { + return this.toCollection().toArray(cb); + }, + orderBy: function (index) { + return new Collection(new WhereClause(this, isArray(index) ? + "[" + index.join('+') + "]" : + index)); + }, + toCollection: function () { + return new Collection(new WhereClause(this)); + }, + mapToClass: function (constructor, structure) { + /// + /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making + /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. + /// + /// Constructor function representing the class. + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], password} + this.schema.mappedClass = constructor; + var instanceTemplate = Object.create(constructor.prototype); + if (structure) { + // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. + applyStructure(instanceTemplate, structure); + } + this.schema.instanceTemplate = instanceTemplate; + // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class + // no matter which method to use for reading (Table.get() or Table.where(...)... ) + var readHook = function (obj) { + if (!obj) + return obj; // No valid object. (Value is null). Return as is. + // Create a new object that derives from constructor: + var res = Object.create(constructor.prototype); + // Clone members: + for (var m in obj) + if (hasOwn(obj, m)) + try { + res[m] = obj[m]; + } + catch (_) { } + return res; + }; + if (this.schema.readHook) { + this.hook.reading.unsubscribe(this.schema.readHook); + } + this.schema.readHook = readHook; + this.hook("reading", readHook); + return constructor; + }, + defineClass: function (structure) { + /// + /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database + /// as well as making it possible to extend the prototype of the returned constructor function. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + return this.mapToClass(Dexie.defineClass(structure), structure); + }, + bulkDelete: function (keys$$1) { + if (this.hook.deleting.fire === nop) { + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + resolve(bulkDelete(idbstore, trans, keys$$1, false, nop)); + }); + } + else { + return this + .where(':id') + .anyOf(keys$$1) + .delete() + .then(function () { }); // Resolve with undefined. + } + }, + bulkPut: function (objects, keys$$1) { + var _this = this; + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys$$1) + throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) + return resolve(); // Caller provided empty list. + var done = function (result) { + if (errorList.length === 0) + resolve(result); + else + reject(new BulkError(_this.name + ".bulkPut(): " + errorList.length + " of " + numObjs + " operations failed", errorList)); + }; + var req, errorList = [], errorHandler, numObjs = objects.length, table = _this; + if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) { + // + // Standard Bulk (no 'creating' or 'updating' hooks to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } + else { + var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(function (o) { return getByKeyPath(o, idbstore.keyPath); }); + // Generate map of {[key]: object} + var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) { return key != null && [key, objects[i]]; }); + var promise = !effectiveKeys ? + // Auto-incremented key-less objects only without any keys argument. + table.bulkAdd(objects) : + // Keys provided. Either as inbound in provided objects, or as a keys argument. + // Begin with updating those that exists in DB: + table.where(':id').anyOf(effectiveKeys.filter(function (key) { return key != null; })).modify(function () { + this.value = objectLookup[this.primKey]; + objectLookup[this.primKey] = null; // Mark as "don't add this" + }).catch(ModifyError, function (e) { + errorList = e.failures; // No need to concat here. These are the first errors added. + }).then(function () { + // Now, let's examine which items didnt exist so we can add them: + var objsToAdd = [], keysToAdd = keys$$1 && []; + // Iterate backwards. Why? Because if same key was used twice, just add the last one. + for (var i = effectiveKeys.length - 1; i >= 0; --i) { + var key = effectiveKeys[i]; + if (key == null || objectLookup[key]) { + objsToAdd.push(objects[i]); + keys$$1 && keysToAdd.push(key); + if (key != null) + objectLookup[key] = null; // Mark as "dont add again" + } + } + // The items are in reverse order so reverse them before adding. + // Could be important in order to get auto-incremented keys the way the caller + // would expect. Could have used unshift instead of push()/reverse(), + // but: http://jsperf.com/unshift-vs-reverse + objsToAdd.reverse(); + keys$$1 && keysToAdd.reverse(); + return table.bulkAdd(objsToAdd, keysToAdd); + }).then(function (lastAddedKey) { + // Resolve with key of the last object in given arguments to bulkPut(): + var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. + return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; + }); + promise.then(done).catch(BulkError, function (e) { + // Concat failure from ModifyError and reject using our 'done' method. + errorList = errorList.concat(e.failures); + done(); + }).catch(reject); + } + }, "locked"); // If called from transaction scope, lock transaction til all steps are done. + }, + bulkAdd: function (objects, keys$$1) { + var self = this, creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) + throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) + return resolve(); // Caller provided empty list. + function done(result) { + if (errorList.length === 0) + resolve(result); + else + reject(new BulkError(self.name + ".bulkAdd(): " + errorList.length + " of " + numObjs + " operations failed", errorList)); + } + var req, errorList = [], errorHandler, successHandler, numObjs = objects.length; + if (creatingHook !== nop) { + // + // There are subscribers to hook('creating') + // Must behave as documented. + // + var keyPath = idbstore.keyPath, hookCtx; + errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); + successHandler = hookedEventSuccessHandler(null); + tryCatch(function () { + for (var i = 0, l = objects.length; i < l; ++i) { + hookCtx = { onerror: null, onsuccess: null }; + var key = keys$$1 && keys$$1[i]; + var obj = objects[i], effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); + if (effectiveKey == null && keyToUse != null) { + if (keyPath) { + obj = deepClone(obj); + setByKeyPath(obj, keyPath, keyToUse); + } + else { + key = keyToUse; + } + } + req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + if (i < l - 1) { + req.onerror = errorHandler; + if (hookCtx.onsuccess) + req.onsuccess = successHandler; + } + } + }, function (err) { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); + req.onsuccess = hookedEventSuccessHandler(done); + } + else { + // + // Standard Bulk (no 'creating' hook to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } + }); + }, + add: function (obj, key) { + /// + /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. + /// + /// A javascript object to insert + /// Primary key + var creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + var hookCtx = { onsuccess: null, onerror: null }; + if (creatingHook !== nop) { + var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined); + var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. + if (effectiveKey == null && keyToUse != null) { + if (idbstore.keyPath) + setByKeyPath(obj, idbstore.keyPath, keyToUse); + else + key = keyToUse; + } + } + try { + var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + req.onerror = hookedEventRejectHandler(reject); + req.onsuccess = hookedEventSuccessHandler(function (result) { + // TODO: Remove these two lines in next major release (2.0?) + // It's no good practice to have side effects on provided parameters + var keyPath = idbstore.keyPath; + if (keyPath) + setByKeyPath(obj, keyPath, result); + resolve(result); + }); + } + catch (e) { + if (hookCtx.onerror) + hookCtx.onerror(e); + throw e; + } + }); + }, + put: function (obj, key) { + var _this = this; + /// + /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. + /// + /// A javascript object to insert or update + /// Primary key + var creatingHook = this.hook.creating.fire, updatingHook = this.hook.updating.fire; + if (creatingHook !== nop || updatingHook !== nop) { + // + // People listens to when("creating") or when("updating") events! + // We must know whether the put operation results in an CREATE or UPDATE. + // + var keyPath = this.schema.primKey.keyPath; + var effectiveKey = (key !== undefined) ? key : (keyPath && getByKeyPath(obj, keyPath)); + if (effectiveKey == null) + return this.add(obj); + // Since key is optional, make sure we get it from obj if not provided + // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). + // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. + obj = deepClone(obj); + return this._trans(READWRITE, function () { + return _this.where(":id").equals(effectiveKey).modify(function () { + // Replace extisting value with our object + // CRUD event firing handled in Collection.modify() + this.value = obj; + }).then(function (count) { return count === 0 ? _this.add(obj, key) : effectiveKey; }); + }, "locked"); // Lock needed because operation is splitted into modify() and add(). + } + else { + // Use the standard IDB put() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function (ev) { + var keyPath = idbstore.keyPath; + if (keyPath) + setByKeyPath(obj, keyPath, ev.target.result); + resolve(req.result); + }); + }); + } + }, + 'delete': function (key) { + /// Primary key of the object to delete + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using Collection.delete() that will + // call the CRUD event. Only Collection.delete() will know whether an object was actually deleted. + return this.where(":id").equals(key).delete(); + } + else { + // No one listens. Use standard IDB delete() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.delete(key); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(req.result); + }); + }); + } + }, + clear: function () { + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using Collection.delete() that will + // call the CRUD event. Only Collection.delete() will knows which objects that are actually deleted. + return this.toCollection().delete(); + } + else { + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.clear(); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(req.result); + }); + }); + } + }, + update: function (keyOrObject, modifications) { + if (typeof modifications !== 'object' || isArray(modifications)) + throw new exceptions.InvalidArgument("Modifications must be an object."); + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + // object to modify. Also modify given object with the modifications: + keys(modifications).forEach(function (keyPath) { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) + return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); + return this.where(":id").equals(key).modify(modifications); + } + else { + // key to modify + return this.where(":id").equals(keyOrObject).modify(modifications); + } + } + }); + // + // + // + // Transaction Class + // + // + // + function Transaction(mode, storeNames, dbschema, parent) { + var _this = this; + /// + /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. + /// + /// Any of "readwrite" or "readonly" + /// Array of table names to operate on + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._reculock = 0; + this._blockedFuncs = []; + this._resolve = null; + this._reject = null; + this._waitingFor = null; + this._waitingQueue = null; + this._spinCount = 0; // Just for debugging waitFor() + this._completion = new Promise(function (resolve, reject) { + _this._resolve = resolve; + _this._reject = reject; + }); + this._completion.then(function () { + _this.active = false; + _this.on.complete.fire(); + }, function (e) { + var wasActive = _this.active; + _this.active = false; + _this.on.error.fire(e); + _this.parent ? + _this.parent._reject(e) : + wasActive && _this.idbtrans && _this.idbtrans.abort(); + return rejection(e); // Indicate we actually DO NOT catch this error. + }); + } + props(Transaction.prototype, { + // + // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) + // + _lock: function () { + assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + // Temporary set all requests into a pending queue if they are called before database is ready. + ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }, + _unlock: function () { + assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + if (--this._reculock === 0) { + if (!PSD.global) + PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fnAndPSD = this._blockedFuncs.shift(); + try { + usePSD(fnAndPSD[1], fnAndPSD[0]); + } + catch (e) { } + } + } + return this; + }, + _locked: function () { + // Checks if any write-lock is applied on this transaction. + // To simplify the Dexie API for extension implementations, we support recursive locks. + // This is accomplished by using "Promise Specific Data" (PSD). + // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). + // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): + // * callback given to the Promise() constructor (function (resolve, reject){...}) + // * callbacks given to then()/catch()/finally() methods (function (value){...}) + // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. + // Derivation is done so that the inner PSD __proto__ points to the outer PSD. + // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. + return this._reculock && PSD.lockOwnerFor !== this; + }, + create: function (idbtrans) { + var _this = this; + if (!this.mode) + return this; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) + throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); + idbtrans.onerror = wrap(function (ev) { + preventDefault(ev); // Prohibit default bubbling to window.error + _this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(function (ev) { + preventDefault(ev); + _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); + _this.active = false; + _this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(function () { + _this.active = false; + _this._resolve(); + }); + return this; + }, + _promise: function (mode, fn, bWriteLock) { + var _this = this; + if (mode === READWRITE && this.mode !== READWRITE) + return rejection(new exceptions.ReadOnly("Transaction is readonly")); + if (!this.active) + return rejection(new exceptions.TransactionInactive()); + if (this._locked()) { + return new Promise(function (resolve, reject) { + _this._blockedFuncs.push([function () { + _this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, PSD]); + }); + } + else if (bWriteLock) { + return newScope(function () { + var p = new Promise(function (resolve, reject) { + _this._lock(); + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p.finally(function () { return _this._unlock(); }); + p._lib = true; + return p; + }); + } + else { + var p = new Promise(function (resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }, + _root: function () { + return this.parent ? this.parent._root() : this; + }, + waitFor: function (promise) { + // Always operate on the root transaction (in case this is a sub stransaction) + var root = this._root(); + // For stability reasons, convert parameter to promise no matter what type is passed to waitFor(). + // (We must be able to call .then() on it.) + promise = Promise.resolve(promise); + if (root._waitingFor) { + // Already called waitFor(). Wait for both to complete. + root._waitingFor = root._waitingFor.then(function () { return promise; }); + } + else { + // We're not in waiting state. Start waiting state. + root._waitingFor = promise; + root._waitingQueue = []; + // Start interacting with indexedDB until promise completes: + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; // For debugging only + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new Promise(function (resolve, reject) { + promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () { + if (root._waitingFor === currentWaitPromise) { + // No one added a wait after us. Safe to stop the spinning. + root._waitingFor = null; + } + }); + }); + }, + // + // Transaction Public Properties and Methods + // + abort: function () { + this.active && this._reject(new exceptions.Abort()); + this.active = false; + }, + tables: { + get: deprecated("Transaction.tables", function () { return allTables; }) + }, + table: function (name) { + var table = db.table(name); // Don't check that table is part of transaction. It must fail lazily! + return new Table(name, table.schema, this); + } + }); + // + // + // + // WhereClause + // + // + // + function WhereClause(table, index, orCollection) { + /// + /// + /// + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + } + props(WhereClause.prototype, function () { + // WhereClause private methods + function fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; + } + function emptyCollection(whereClause) { + return new Collection(whereClause, function () { return IDBKeyRange.only(""); }).limit(0); + } + function upperFactory(dir) { + return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); }; + } + function lowerFactory(dir) { + return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); }; + } + function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { + var length = Math.min(key.length, lowerNeedle.length); + var llp = -1; + for (var i = 0; i < length; ++i) { + var lwrKeyChar = lowerKey[i]; + if (lwrKeyChar !== lowerNeedle[i]) { + if (cmp(key[i], upperNeedle[i]) < 0) + return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); + if (cmp(key[i], lowerNeedle[i]) < 0) + return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); + if (llp >= 0) + return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); + return null; + } + if (cmp(key[i], lwrKeyChar) < 0) + llp = i; + } + if (length < lowerNeedle.length && dir === "next") + return key + upperNeedle.substr(key.length); + if (length < key.length && dir === "prev") + return key.substr(0, upperNeedle.length); + return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); + } + function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { + /// + var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; + if (!needles.every(function (s) { return typeof s === 'string'; })) { + return fail(whereClause, STRING_EXPECTED); + } + function initDirection(dir) { + upper = upperFactory(dir); + lower = lowerFactory(dir); + compare = (dir === "next" ? simpleCompare : simpleCompareReverse); + var needleBounds = needles.map(function (needle) { + return { lower: lower(needle), upper: upper(needle) }; + }).sort(function (a, b) { + return compare(a.lower, b.lower); + }); + upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); + lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); + direction = dir; + nextKeySuffix = (dir === "next" ? "" : suffix); + } + initDirection("next"); + var c = new Collection(whereClause, function () { + return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); + }); + c._ondirectionchange = function (direction) { + // This event onlys occur before filter is called the first time. + initDirection(direction); + }; + var firstPossibleNeedle = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + /// + /// + /// + var key = cursor.key; + if (typeof key !== 'string') + return false; + var lowerKey = lower(key); + if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { + return true; + } + else { + var lowestPossibleCasing = null; + for (var i = firstPossibleNeedle; i < needlesLen; ++i) { + var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); + if (casing === null && lowestPossibleCasing === null) + firstPossibleNeedle = i + 1; + else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { + lowestPossibleCasing = casing; + } + } + if (lowestPossibleCasing !== null) { + advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); + } + else { + advance(resolve); + } + return false; + } + }); + return c; + } + // + // WhereClause public methods + // + return { + between: function (lower, upper, includeLower, includeUpper) { + /// + /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. + /// + /// + /// + /// Whether items that equals lower should be included. Default true. + /// Whether items that equals upper should be included. Default false. + /// + includeLower = includeLower !== false; // Default to true + includeUpper = includeUpper === true; // Default to false + try { + if ((cmp(lower, upper) > 0) || + (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. + return new Collection(this, function () { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); }); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }, + equals: function (value) { + return new Collection(this, function () { return IDBKeyRange.only(value); }); + }, + above: function (value) { + return new Collection(this, function () { return IDBKeyRange.lowerBound(value, true); }); + }, + aboveOrEqual: function (value) { + return new Collection(this, function () { return IDBKeyRange.lowerBound(value); }); + }, + below: function (value) { + return new Collection(this, function () { return IDBKeyRange.upperBound(value, true); }); + }, + belowOrEqual: function (value) { + return new Collection(this, function () { return IDBKeyRange.upperBound(value); }); + }, + startsWith: function (str) { + /// + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }, + startsWithIgnoreCase: function (str) { + /// + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }, + equalsIgnoreCase: function (str) { + /// + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }, + anyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); + }, + startsWithAnyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { + return a.some(function (n) { + return x.indexOf(n) === 0; + }); + }, set, maxString); + }, + anyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = ascending; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new Collection(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); }); + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? ascending : descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } + else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }, + notEqual: function (value) { + return this.inAnyRange([[minKey, value], [value, maxKey]], { includeLowers: false, includeUppers: false }); + }, + noneOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new Collection(this); // Return entire collection. + try { + set.sort(ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + // Transform ["a","b","c"] to a set of ranges for between/above/below: [[minKey,"a"], ["a","b"], ["b","c"], ["c",maxKey]] + var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; }, null); + ranges.push([set[set.length - 1], maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }, + /** Filter out values withing given set of ranges. + * Example, give children and elders a rebate of 50%: + * + * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); + * + * @param {(string|number|Date|Array)[][]} ranges + * @param {{includeLowers: boolean, includeUppers: boolean}} options + */ + inAnyRange: function (ranges, options) { + if (ranges.length === 0) + return emptyCollection(this); + if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0; })) { + return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); + } + var includeLowers = !options || options.includeLowers !== false; // Default to true + var includeUppers = options && options.includeUppers === true; // Default to false + function addRange(ranges, newRange) { + for (var i = 0, l = ranges.length; i < l; ++i) { + var range = ranges[i]; + if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { + range[0] = min(range[0], newRange[0]); + range[1] = max(range[1], newRange[1]); + break; + } + } + if (i === l) + ranges.push(newRange); + return ranges; + } + var sortDirection = ascending; + function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } + // Join overlapping ranges + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var i = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function (key) { return ascending(key, set[i][1]) > 0; } : + function (key) { return ascending(key, set[i][1]) >= 0; }; + var keyIsBeforeCurrentEntry = includeLowers ? + function (key) { return descending(key, set[i][0]) > 0; } : + function (key) { return descending(key, set[i][0]) >= 0; }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new Collection(this, function () { + return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); + }); + c._ondirectionchange = function (direction) { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } + else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (checkKey(key)) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } + else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) { + // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. + // Continue to next key but don't include this one. + return false; + } + else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { + if (sortDirection === ascending) + cursor.continue(set[i][0]); + else + cursor.continue(set[i][1]); + }); + return false; + } + }); + return c; + }, + startsWithAnyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (!set.every(function (s) { return typeof s === 'string'; })) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) + return emptyCollection(this); + return this.inAnyRange(set.map(function (str) { + return [str, str + maxString]; + })); + } + }; + }); + // + // + // + // Collection Class + // + // + // + function Collection(whereClause, keyRangeGenerator) { + /// + /// + /// + /// Where clause instance + /// + var keyRange = null, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx, table = whereCtx.table; + this._ctx = { + table: table, + index: whereCtx.index, + isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)), + range: keyRange, + keysOnly: false, + dir: "next", + unique: "", + algorithm: null, + filter: null, + replayFilter: null, + justLimit: true, + isMatch: null, + offset: 0, + limit: Infinity, + error: error, + or: whereCtx.or, + valueMapper: table.hook.reading.fire + }; + } + function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); + } + props(Collection.prototype, function () { + // + // Collection Private Functions + // + function addFilter(ctx, fn) { + ctx.filter = combine(ctx.filter, fn); + } + function addReplayFilter(ctx, factory, isLimitFilter) { + var curr = ctx.replayFilter; + ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory; + ctx.justLimit = isLimitFilter && !curr; + } + function addMatchFilter(ctx, fn) { + ctx.isMatch = combine(ctx.isMatch, fn); + } + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string + * } + * @param store IDBObjectStore + **/ + function getIndexOrStore(ctx, store) { + if (ctx.isPrimKey) + return store; + var indexSpec = ctx.table.schema.idxByName[ctx.index]; + if (!indexSpec) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); + return store.index(indexSpec.name); + } + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string, + * keysOnly: boolean, + * range?: IDBKeyRange, + * dir: "next" | "prev" + * } + */ + function openCursor(ctx, store) { + var idxOrStore = getIndexOrStore(ctx, store); + return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? + idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : + idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); + } + function iter(ctx, fn, resolve, reject, idbstore) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); + } + else + (function () { + var set = {}; + var resolved = 0; + function resolveboth() { + if (++resolved === 2) + resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. + } + function union(item, cursor, advance) { + if (!filter || filter(cursor, advance, resolveboth, reject)) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set, key)) { + set[key] = true; + fn(item, cursor, advance); + } + } + } + ctx.or._iterate(union, resolveboth, reject, idbstore); + iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); + })(); + } + return { + // + // Collection Protected Functions + // + _read: function (fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._idbstore(READONLY, fn).then(cb); + }, + _write: function (fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. + }, + _addAlgorithm: function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }, + _iterate: function (fn, resolve, reject, idbstore) { + return iter(this._ctx, fn, resolve, reject, idbstore); + }, + clone: function (props$$1) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props$$1) + extend(ctx, props$$1); + rv._ctx = ctx; + return rv; + }, + raw: function () { + this._ctx.valueMapper = null; + return this; + }, + // + // Collection Public methods + // + each: function (fn) { + var ctx = this._ctx; + return this._read(function (resolve, reject, idbstore) { + iter(ctx, fn, resolve, reject, idbstore); + }); + }, + count: function (cb) { + var ctx = this._ctx; + if (isPlainKeyRange(ctx, true)) { + // This is a plain key range. We can use the count() method if the index. + return this._read(function (resolve, reject, idbstore) { + var idx = getIndexOrStore(ctx, idbstore); + var req = (ctx.range ? idx.count(ctx.range) : idx.count()); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function (e) { + resolve(Math.min(e.target.result, ctx.limit)); + }; + }, cb); + } + else { + // Algorithms, filters or expressions are applied. Need to count manually. + var count = 0; + return this._read(function (resolve, reject, idbstore) { + iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore); + }, cb); + } + }, + sortBy: function (keyPath, cb) { + /// + var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; + function getval(obj, i) { + if (i) + return getval(obj[parts[i]], i - 1); + return obj[lastPart]; + } + var order = this._ctx.dir === "next" ? 1 : -1; + function sorter(a, b) { + var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); + return aVal < bVal ? -order : aVal > bVal ? order : 0; + } + return this.toArray(function (a) { + return a.sort(sorter); + }).then(cb); + }, + toArray: function (cb) { + var ctx = this._ctx; + return this._read(function (resolve, reject, idbstore) { + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAll() or + // IDBKeyRange.getAll(): + var readingHook = ctx.table.hook.reading.fire; + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? + idxOrStore.getAll(ctx.range, ctx.limit) : + idxOrStore.getAll(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = readingHook === mirror ? + eventSuccessHandler(resolve) : + eventSuccessHandler(function (res) { + try { + resolve(res.map(readingHook)); + } + catch (e) { + reject(e); + } + }); + } + else { + // Getting array through a cursor. + var a = []; + iter(ctx, function (item) { a.push(item); }, function arrayComplete() { + resolve(a); + }, reject, idbstore); + } + }, cb); + }, + offset: function (offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; // For count() + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, function () { + var offsetLeft = offset; + return function (cursor, advance) { + if (offsetLeft === 0) + return true; + if (offsetLeft === 1) { + --offsetLeft; + return false; + } + advance(function () { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } + else { + addReplayFilter(ctx, function () { + var offsetLeft = offset; + return function () { return (--offsetLeft < 0); }; + }); + } + return this; + }, + limit: function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); // Stop after this item has been included + return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. + }; + }, true); + return this; + }, + until: function (filterFunction, bIncludeStopEntry) { + var ctx = this._ctx; + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + }, + first: function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }, + last: function (cb) { + return this.reverse().first(cb); + }, + filter: function (filterFunction) { + /// function(val){return true/false} + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + // match filters not used in Dexie.js but can be used by 3rd part libraries to test a + // collection for a match without querying DB. Used by Dexie.Observable. + addMatchFilter(this._ctx, filterFunction); + return this; + }, + and: function (filterFunction) { + return this.filter(filterFunction); + }, + or: function (indexName) { + return new WhereClause(this._ctx.table, indexName, this); + }, + reverse: function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }, + desc: function () { + return this.reverse(); + }, + eachKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }, + eachUniqueKey: function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }, + eachPrimaryKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }, + keys: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.key); + }).then(function () { + return a; + }).then(cb); + }, + primaryKeys: function (cb) { + var ctx = this._ctx; + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAllKeys() or + // IDBKeyRange.getAllKeys(): + return this._read(function (resolve, reject, idbstore) { + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? + idxOrStore.getAllKeys(ctx.range, ctx.limit) : + idxOrStore.getAllKeys(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = eventSuccessHandler(resolve); + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }, + uniqueKeys: function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }, + firstKey: function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }, + lastKey: function (cb) { + return this.reverse().firstKey(cb); + }, + distinct: function () { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; // distinct() only makes differencies on multiEntry indexes. + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }, + // + // Methods that mutate storage + // + modify: function (changes) { + var self = this, ctx = this._ctx, hook = ctx.table.hook, updatingHook = hook.updating.fire, deletingHook = hook.deleting.fire; + return this._write(function (resolve, reject, idbstore, trans) { + var modifyer; + if (typeof changes === 'function') { + // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) + if (updatingHook === nop && deletingHook === nop) { + // Noone cares about what is being changed. Just let the modifier function be the given argument as is. + modifyer = changes; + } + else { + // People want to know exactly what is being modified or deleted. + // Let modifyer be a proxy function that finds out what changes the caller is actually doing + // and call the hooks accordingly! + modifyer = function (item) { + var origItem = deepClone(item); // Clone the item first so we can compare laters. + if (changes.call(this, item, this) === false) + return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) + if (!hasOwn(this, "value")) { + // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. + deletingHook.call(this, this.primKey, item, trans); + } + else { + // No deletion. Check what was changed + var objectDiff = getObjectDiff(origItem, this.value); + var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); + if (additionalChanges) { + // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. + item = this.value; + keys(additionalChanges).forEach(function (keyPath) { + setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + }); + } + } + }; + } + } + else if (updatingHook === nop) { + // changes is a set of {keyPath: value} and no one is listening to the updating hook. + var keyPaths = keys(changes); + var numKeys = keyPaths.length; + modifyer = function (item) { + var anythingModified = false; + for (var i = 0; i < numKeys; ++i) { + var keyPath = keyPaths[i], val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + anythingModified = true; + } + } + return anythingModified; + }; + } + else { + // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and + // allow it to add additional modifications to make. + var origChanges = changes; + changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. + modifyer = function (item) { + var anythingModified = false; + var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); + if (additionalChanges) + extend(changes, additionalChanges); + keys(changes).forEach(function (keyPath) { + var val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); + anythingModified = true; + } + }); + if (additionalChanges) + changes = shallowClone(origChanges); // Restore original changes for next iteration + return anythingModified; + }; + } + var count = 0; + var successCount = 0; + var iterationComplete = false; + var failures = []; + var failKeys = []; + var currentKey = null; + function modifyItem(item, cursor) { + currentKey = cursor.primaryKey; + var thisContext = { + primKey: cursor.primaryKey, + value: item, + onsuccess: null, + onerror: null + }; + function onerror(e) { + failures.push(e); + failKeys.push(thisContext.primKey); + checkFinished(); + return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction + } + if (modifyer.call(thisContext, item, thisContext) !== false) { + var bDelete = !hasOwn(thisContext, "value"); + ++count; + tryCatch(function () { + var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value)); + req._hookCtx = thisContext; + req.onerror = hookedEventRejectHandler(onerror); + req.onsuccess = hookedEventSuccessHandler(function () { + ++successCount; + checkFinished(); + }); + }, onerror); + } + else if (thisContext.onsuccess) { + // Hook will expect either onerror or onsuccess to always be called! + thisContext.onsuccess(thisContext.value); + } + } + function doReject(e) { + if (e) { + failures.push(e); + failKeys.push(currentKey); + } + return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); + } + function checkFinished() { + if (iterationComplete && successCount + failures.length === count) { + if (failures.length > 0) + doReject(); + else + resolve(successCount); + } + } + self.clone().raw()._iterate(modifyItem, function () { + iterationComplete = true; + checkFinished(); + }, doReject, idbstore); + }); + }, + 'delete': function () { + var _this = this; + var ctx = this._ctx, range = ctx.range, deletingHook = ctx.table.hook.deleting.fire, hasDeleteHook = deletingHook !== nop; + if (!hasDeleteHook && + isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) { + // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) + // For chromium, this is the way most optimized version. + // For IE/Edge, this could hang the indexedDB engine and make operating system instable + // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) + return this._write(function (resolve, reject, idbstore) { + // Our API contract is to return a count of deleted items, so we have to count() before delete(). + var onerror = eventRejectHandler(reject), countReq = (range ? idbstore.count(range) : idbstore.count()); + countReq.onerror = onerror; + countReq.onsuccess = function () { + var count = countReq.result; + tryCatch(function () { + var delReq = (range ? idbstore.delete(range) : idbstore.clear()); + delReq.onerror = onerror; + delReq.onsuccess = function () { return resolve(count); }; + }, function (err) { return reject(err); }); + }; + }); + } + // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. + // Divide into chunks to not starve RAM. + // If has delete hook, we will have to collect not just keys but also objects, so it will use + // more memory and need lower chunk size. + var CHUNKSIZE = hasDeleteHook ? 2000 : 10000; + return this._write(function (resolve, reject, idbstore, trans) { + var totalCount = 0; + // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. + var collection = _this + .clone({ + keysOnly: !ctx.isMatch && !hasDeleteHook + }) // load just keys (unless filter() or and() or deleteHook has subscribers) + .distinct() // In case multiEntry is used, never delete same key twice because resulting count + .limit(CHUNKSIZE) + .raw(); // Don't filter through reading-hooks (like mapped classes etc) + var keysOrTuples = []; + // We're gonna do things on as many chunks that are needed. + // Use recursion of nextChunk function: + var nextChunk = function () { return collection.each(hasDeleteHook ? function (val, cursor) { + // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, + // so that the hook can be called with its values in bulkDelete(). + keysOrTuples.push([cursor.primaryKey, cursor.value]); + } : function (val, cursor) { + // No one subscribes to hook('deleting'). Collect only primary keys: + keysOrTuples.push(cursor.primaryKey); + }).then(function () { + // Chromium deletes faster when doing it in sort order. + hasDeleteHook ? + keysOrTuples.sort(function (a, b) { return ascending(a[0], b[0]); }) : + keysOrTuples.sort(ascending); + return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); + }).then(function () { + var count = keysOrTuples.length; + totalCount += count; + keysOrTuples = []; + return count < CHUNKSIZE ? totalCount : nextChunk(); + }); }; + resolve(nextChunk()); + }); + } + }; + }); + // + // + // + // ------------------------- Help functions --------------------------- + // + // + // + function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; + } + function setApiOnPlace(objs, tableNames, dbschema) { + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + if (!(tableName in obj)) { + if (obj === Transaction.prototype || obj instanceof Transaction) { + // obj is a Transaction prototype (or prototype of a subclass to Transaction) + // Make the API a getter that returns this.table(tableName) + setProp(obj, tableName, { get: function () { return this.table(tableName); } }); + } + else { + // Table will not be bound to a transaction (will use Dexie.currentTransaction) + obj[tableName] = new Table(tableName, schema); + } + } + }); + }); + } + function removeTablesApi(objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof Table) + delete obj[key]; + } + }); + } + function iterate(req, filter, fn, resolve, reject, valueMapper) { + // Apply valueMapper (hook('reading') or mappped class) + var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; + // Wrap fn with PSD and microtick stuff from Promise. + var wrappedFn = wrap(mappedFn, reject); + if (!req.onerror) + req.onerror = eventRejectHandler(reject); + if (filter) { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { cursor.continue(); }; + if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject)) + wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); + c(); + } + else { + resolve(); + } + }, reject); + } + else { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { cursor.continue(); }; + wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); + c(); + } + else { + resolve(); + } + }, reject); + } + } + function parseIndexSyntax(indexes) { + /// + /// + var rv = []; + indexes.split(',').forEach(function (index) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" + // Let keyPath of "[a+b]" be ["a","b"]: + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index))); + }); + return rv; + } + function cmp(key1, key2) { + return indexedDB.cmp(key1, key2); + } + function min(a, b) { + return cmp(a, b) < 0 ? a : b; + } + function max(a, b) { + return cmp(a, b) > 0 ? a : b; + } + function ascending(a, b) { + return indexedDB.cmp(a, b); + } + function descending(a, b) { + return indexedDB.cmp(b, a); + } + function simpleCompare(a, b) { + return a < b ? -1 : a === b ? 0 : 1; + } + function simpleCompareReverse(a, b) { + return a > b ? -1 : a === b ? 0 : 1; + } + function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; + } + function readGlobalSchema() { + db.verno = idbdb.version / 10; + db._dbSchema = globalSchema = {}; + dbStoreNames = slice(idbdb.objectStoreNames, 0); + if (dbStoreNames.length === 0) + return; // Database contains no stores. + var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); + dbStoreNames.forEach(function (storeName) { + var store = trans.objectStore(storeName), keyPath = store.keyPath, dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); + indexes.push(index); + } + globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); + }); + setApiOnPlace([allTables], keys(globalSchema), globalSchema); + } + function adjustToExistingIndexNames(schema, idbtrans) { + /// + /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db + /// + /// Map between name and TableSchema + /// + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + hasGetAll = 'getAll' in store; + for (var j = 0; j < store.indexNames.length; ++j) { + var indexName = store.indexNames[j]; + var keyPath = store.index(indexName).keyPath; + var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; + if (schema[storeName]) { + var indexSpec = schema[storeName].idxByName[dexieName]; + if (indexSpec) + indexSpec.name = indexName; + } + } + } + // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579 + if (/Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + hasGetAll = false; + } + } + function fireOnBlocked(ev) { + db.on("blocked").fire(ev); + // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: + connections + .filter(function (c) { return c.name === db.name && c !== db && !c._vcFired; }) + .map(function (c) { return c.on("versionchange").fire(ev); }); + } + extend(this, { + Collection: Collection, + Table: Table, + Transaction: Transaction, + Version: Version, + WhereClause: WhereClause + }); + init(); + addons.forEach(function (fn) { + fn(db); + }); +} +function parseType(type) { + if (typeof type === 'function') { + return new type(); + } + else if (isArray(type)) { + return [parseType(type[0])]; + } + else if (type && typeof type === 'object') { + var rv = {}; + applyStructure(rv, type); + return rv; + } + else { + return type; + } +} +function applyStructure(obj, structure) { + keys(structure).forEach(function (member) { + var value = parseType(structure[member]); + obj[member] = value; + }); + return obj; +} +function hookedEventSuccessHandler(resolve) { + // wrap() is needed when calling hooks because the rare scenario of: + // * hook does a db operation that fails immediately (IDB throws exception) + // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. + // wrap() will also execute in a virtual tick. + // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. + // * If this was the last event in the bulk, the promise will resolve after a physical tick + // and the transaction will have committed already. + // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, + // because it is always marked with _lib = true when created using Transaction._promise(). + return wrap(function (event) { + var req = event.target, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. + result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key. + hookSuccessHandler = ctx && ctx.onsuccess; + hookSuccessHandler && hookSuccessHandler(result); + resolve && resolve(result); + }, resolve); +} +function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); +} +function eventSuccessHandler(resolve) { + return wrap(function (event) { + resolve(event.target.result); + }); +} +function hookedEventRejectHandler(reject) { + return wrap(function (event) { + // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. + var req = event.target, err = req.error, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. + hookErrorHandler = ctx && ctx.onerror; + hookErrorHandler && hookErrorHandler(err); + preventDefault(event); + reject(err); + return false; + }); +} +function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); +} +function awaitIterator(iterator) { + var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow); + function step(getNext) { + return function (val) { + var next = getNext(val), value = next.value; + return next.done ? value : + (!value || typeof value.then !== 'function' ? + isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : + value.then(onSuccess, onError)); + }; + } + return step(callNext)(); +} +// +// IndexSpec struct +// +function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { + /// + /// + /// + /// + /// + /// + /// + this.name = name; + this.keyPath = keyPath; + this.unique = unique; + this.multi = multi; + this.auto = auto; + this.compound = compound; + this.dotted = dotted; + var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']'); + this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; +} +// +// TableSchema struct +// +function TableSchema(name, primKey, indexes, instanceTemplate) { + /// + /// + /// + /// + this.name = name; + this.primKey = primKey || new IndexSpec(); + this.indexes = indexes || [new IndexSpec()]; + this.instanceTemplate = instanceTemplate; + this.mappedClass = null; + this.idxByName = arrayToObject(indexes, function (index) { return [index.name, index]; }); +} +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} +function getNativeGetDatabaseNamesFn(indexedDB) { + var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); + return fn && fn.bind(indexedDB); +} +// Export Error classes +props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; +// +// Static methods and properties +// +props(Dexie, { + // + // Static delete() method. + // + delete: function (databaseName) { + var db = new Dexie(databaseName), promise = db.delete(); + promise.onblocked = function (fn) { + db.on("blocked", fn); + return this; + }; + return promise; + }, + // + // Static exists() method. + // + exists: function (name) { + return new Dexie(name).open().then(function (db) { + db.close(); + return true; + }).catch(Dexie.NoSuchDatabaseError, function () { return false; }); + }, + // + // Static method for retrieving a list of all existing databases at current host. + // + getDatabaseNames: function (cb) { + var getDatabaseNames = getNativeGetDatabaseNamesFn(Dexie.dependencies.indexedDB); + return getDatabaseNames ? new Promise(function (resolve, reject) { + var req = getDatabaseNames(); + req.onsuccess = function (event) { + resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array + }; + req.onerror = eventRejectHandler(reject); + }).then(cb) : dbNamesDB.dbnames.toCollection().primaryKeys(cb); + }, + defineClass: function (structure) { + /// + /// Create a javascript constructor based on given template for which properties to expect in the class. + /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + // Default constructor able to copy given properties into this object. + function Class(properties) { + /// Properties to initialize object with. + /// + if (properties) + extend(this, properties); + } + return Class; + }, + applyStructure: applyStructure, + ignoreTransaction: function (scopeFunc) { + // In case caller is within a transaction but needs to create a separate transaction. + // Example of usage: + // + // Let's say we have a logger function in our app. Other application-logic should be unaware of the + // logger function and not need to include the 'logentries' table in all transaction it performs. + // The logging should always be done in a separate transaction and not be dependant on the current + // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. + // + // Dexie.ignoreTransaction(function() { + // db.logentries.add(newLogEntry); + // }); + // + // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction + // in current Promise-scope. + // + // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an + // API for this because + // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). + // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). + // 3) setImmediate() is not supported in the ES standard. + // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. + scopeFunc(); // No need to change scope because there is no ongoing transaction. + }, + vip: function (fn) { + // To be used by subscribers to the on('ready') event. + // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. + // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD + // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since + // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. + // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() + // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by + // the caller will not resolve until database is opened. + return newScope(function () { + PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. + return fn(); + }); + }, + async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return Promise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }; + }, + spawn: function (generatorFn, args, thiz) { + try { + var rv = awaitIterator(generatorFn.apply(thiz, args || [])); + if (!rv || typeof rv.then !== 'function') + return Promise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + // Dexie.currentTransaction property + currentTransaction: { + get: function () { return PSD.trans || null; } + }, + waitFor: function (promiseOrFunction, optionalTimeout) { + // If a function is provided, invoke it and pass the returning value to Transaction.waitFor() + var promise = Promise.resolve(typeof promiseOrFunction === 'function' ? Dexie.ignoreTransaction(promiseOrFunction) : promiseOrFunction) + .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. + // Run given promise on current transaction. If no current transaction, just return a Dexie promise based + // on given value. + return PSD.trans ? PSD.trans.waitFor(promise) : promise; + }, + // Export our Promise implementation since it can be handy as a standalone Promise implementation + Promise: Promise, + // Dexie.debug proptery: + // Dexie.debug = false + // Dexie.debug = true + // Dexie.debug = "dexie" - don't hide dexie's stack frames. + debug: { + get: function () { return debug; }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); + } + }, + // Export our derive/extend/override methodology + derive: derive, + extend: extend, + props: props, + override: override, + // Export our Events() function - can be handy as a toolkit + Events: Events, + // Utilities + getByKeyPath: getByKeyPath, + setByKeyPath: setByKeyPath, + delByKeyPath: delByKeyPath, + shallowClone: shallowClone, + deepClone: deepClone, + getObjectDiff: getObjectDiff, + asap: asap, + maxKey: maxKey, + minKey: minKey, + // Addon registry + addons: [], + // Global DB connection list + connections: connections, + MultiModifyError: exceptions.Modify, + errnames: errnames, + // Export other static classes + IndexSpec: IndexSpec, + TableSchema: TableSchema, + // + // Dependencies + // + // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. + // + // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). + // For node.js, you need to require indexeddb-js or similar and then set these deps. + // + dependencies: { + // Required: + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }, + // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split('.') + .map(function (n) { return parseInt(n); }) + .reduce(function (p, c, i) { return p + (c / Math.pow(10, i * 2)); }), + // https://github.com/dfahlander/Dexie.js/issues/186 + // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return + // x.default. Workaround: Set Dexie.default = Dexie. + default: Dexie, + // Make it possible to import {Dexie} (non-default import) + // Reason 1: May switch to that in future. + // Reason 2: We declare it both default and named exported in d.ts to make it possible + // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely + // exporting the symbol, not just default exporting) + Dexie: Dexie +}); +// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. +Promise.rejectionMapper = mapError; +// Initialize dbNamesDB (won't ever be opened on chromium browsers') +dbNamesDB = new Dexie('__dbnames'); +dbNamesDB.version(1).stores({ dbnames: 'name' }); +(function () { + // Migrate from Dexie 1.x database names stored in localStorage: + var DBNAMES = 'Dexie.DatabaseNames'; + if (typeof localStorage !== undefined && _global.document !== undefined) + try { + // Have localStorage and is not executing in a worker. Lets migrate from Dexie 1.x. + JSON.parse(localStorage.getItem(DBNAMES) || "[]") + .forEach(function (name) { return dbNamesDB.dbnames.put({ name: name }).catch(nop); }); + localStorage.removeItem(DBNAMES); + } + catch (_e) { } +})(); + +export default Dexie; +//# sourceMappingURL=dexie.es.js.map diff --git a/dist/dexie.es.js.map b/dist/dexie.es.js.map new file mode 100644 index 000000000..027a53fb9 --- /dev/null +++ b/dist/dexie.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.es.js","sources":["../src/utils.js","../src/debug.js","../src/errors.js","../src/chaining-functions.js","../src/Promise.js","../src/Events.js","../src/Dexie.js"],"sourcesContent":["export var keys = Object.keys;\nexport var isArray = Array.isArray;\nexport var _global =\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n\nexport function extend(obj, extension) {\n if (typeof extension !== 'object') return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n keys(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n var pd = getOwnPropertyDescriptor(obj, prop),\n proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nvar _slice = [].slice;\nexport function slice(args, start, end) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array, extractor) {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn, onerror, args) {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a) {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nvar intrinsicTypes =\n \"Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]).map(t=>_global[t])\n\nexport function deepClone(any) {\n if (!any || typeof any !== 'object') return any;\n var rv;\n if (isArray(any)) {\n rv = [];\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(deepClone(any[i]));\n }\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n } else {\n rv = any.constructor ? Object.create(any.constructor.prototype) : {};\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = deepClone(any[prop]);\n }\n }\n }\n return rv;\n}\n\nexport function getObjectDiff(a, b, rv, prfx) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach(prop => {\n if (!hasOwn(b, prop))\n rv[prfx+prop] = undefined; // Property removed\n else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' &&\n ap && bp &&\n // Now compare constructors are same (not equal because wont work in Safari)\n (''+ap.constructor) === (''+bp.constructor))\n // Same type of object but its properties may have changed\n getObjectDiff (ap, bp, rv, prfx + prop + \".\");\n else if (ap !== bp)\n rv[prfx + prop] = b[prop];// Primitive value changed\n }\n });\n keys(b).forEach(prop => {\n if (!hasOwn(a, prop)) {\n rv[prfx+prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\nexport const getIteratorOf = iteratorSymbol ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch(e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\nexport function deprecated (what, fn) {\n return function () {\n console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n }\n}\n","import { derive, setProp } from './utils';\nimport { getErrorWithStack, prettyStack } from './debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function() {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + failures\n .map(f=>f.toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = failures;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = msgOrInner;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend} from './utils';\nimport {nop, callBoth, mirror} from './chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from './errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 7,\n nativePromiseInstanceAndProto = (()=>{\n try {\n // Be able to patch native async functions\n return new Function(`let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];`)();\n } catch(e) {\n var P = _global.Promise;\n return P ?\n [P.resolve(), P.prototype, P.resolve()] :\n []; \n }\n })(),\n resolvedNativePromise = nativePromiseInstanceAndProto[0],\n nativePromiseProto = nativePromiseInstanceAndProto[1],\n resolvedGlobalPromise = nativePromiseInstanceAndProto[2],\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nexport const AsyncFunction = nativePromiseInstanceAndProto[3];\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => {resolvedGlobalPromise.then(physicalTick);}\n :\n _global.setImmediate ? \n // setImmediate supported. Those modern platforms also supports Function.bind().\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n // MutationObserver supported\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\n physicalTick();\n hiddenDiv = null;\n })).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n } :\n // No support for setImmediate or MutationObserver. No worry, setTimeout is only called\n // once time. Every tick that follows will be our emulated micro tick.\n // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \n ()=>{setTimeout(physicalTick,0);};\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(uh => {\n try {\n globalError(uh[0], uh[1]);\n } catch (e) {}\n });\n }\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n }\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n if (possibleAwait) decrementExpectedAwaits();\n var rv = new Promise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(Promise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n \n stack: {\n get: function() {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack (this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new Promise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(Promise.prototype, Symbol.toStringTag, 'Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (Promise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new Promise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => Promise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof Promise) return value;\n if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new Promise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new Promise((resolve, reject) => {\n values.map(value => Promise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n //totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new Promise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof Promise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n \n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\nfunction getStack (promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n \n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with setImmediate() or setTimeout().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new Promise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: Promise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: Promise, configurable: true, writable: true},\n all: Promise.all,\n race: Promise.race,\n resolve: Promise.resolve,\n reject: Promise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits(sourceTaskId) {\n if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) return;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction enqueueNativeMicroTask (job) {\n //\n // Precondition: nativePromiseThen !== undefined\n //\n nativePromiseThen.call(resolvedNativePromise, job);\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone, false),\n nativeAwaitCompatibleWrap(onRejected, zone, false));\n };\n}\n\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\n\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n } catch (e) {}\n if (rv !== false) try {\n var event, eventData = {promise: promise, reason: err};\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n } else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData});\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\n try {_global.onunhandledrejection(event);} catch (_) {}\n }\n if (!event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n } catch (e) {}\n}\n\nexport var rejection = Promise.reject;\n","import {keys, isArray, asap} from './utils';\nimport {nop, mirror, reverseStoppableEventChain} from './chaining-functions';\nimport {exceptions} from './errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","/*\n * Dexie.js - a minimalistic wrapper for IndexedDB\n * ===============================================\n *\n * Copyright (c) 2014-2017 David Fahlander\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n * \n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n * \n */\n\nimport {\n keys,\n setProp,\n isArray,\n extend,\n props,\n derive,\n slice,\n override,\n _global,\n asap,\n trycatcher,\n tryCatch,\n getByKeyPath,\n setByKeyPath,\n delByKeyPath,\n shallowClone,\n deepClone,\n getObjectDiff,\n assert,\n NO_CHAR_ARRAY,\n getArrayOf,\n arrayToObject,\n hasOwn,\n flatten\n} from './utils';\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\nimport Promise, {wrap, PSD, newScope, usePSD, rejection, NativePromise,\n incrementExpectedAwaits, decrementExpectedAwaits, AsyncFunction} from './Promise';\nimport Events from './Events';\nimport {\n nop,\n mirror,\n pureFunctionChain,\n hookCreatingChain,\n hookUpdatingChain,\n hookDeletingChain,\n promisableChain\n} from './chaining-functions';\nimport * as Debug from './debug';\n\nvar DEXIE_VERSION = '{version}',\n maxString = String.fromCharCode(65535),\n // maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\n // Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\n maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(),\n minKey = -Infinity,\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\n STRING_EXPECTED = \"String expected.\",\n connections = [],\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\n hasIEDeleteObjectStoreBug = isIEOrEdge,\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\n dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame),\n dbNamesDB;// Global database for backing Dexie.getDatabaseNames() on browser without indexedDB.webkitGetDatabaseNames() \n\n// Init debug\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default function Dexie(dbName, options) {\n /// Specify only if you wich to control which addons that should run on this instance\n var deps = Dexie.dependencies;\n var opts = extend({\n // Default Options\n addons: Dexie.addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to browser env.\n }, options);\n var addons = opts.addons,\n autoOpen = opts.autoOpen,\n indexedDB = opts.indexedDB,\n IDBKeyRange = opts.IDBKeyRange;\n\n var globalSchema = this._dbSchema = {};\n var versions = [];\n var dbStoreNames = [];\n var allTables = {};\n ///\n var idbdb = null; // Instance of IDBDatabase\n var dbOpenError = null;\n var isBeingOpened = false;\n var onReadyBeingFired = null;\n var openComplete = false;\n var READONLY = \"readonly\", READWRITE = \"readwrite\";\n var db = this;\n var dbReadyResolve,\n dbReadyPromise = new Promise(resolve => {\n dbReadyResolve = resolve;\n }),\n cancelOpen,\n openCanceller = new Promise((_, reject) => {\n cancelOpen = reject;\n });\n var autoSchema = true;\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\n hasGetAll;\n\n function init() {\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n db.on(\"versionchange\", function (ev) {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`);\n db.close();\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n db.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${db.name}') was blocked`);\n else\n console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`);\n });\n }\n\n //\n //\n //\n // ------------------------- Versioning Framework---------------------------\n //\n //\n //\n\n this.version = function (versionNumber) {\n /// \n /// \n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];\n if (versionInstance) return versionInstance;\n versionInstance = new Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n // Disable autoschema mode, as at least one version is specified.\n autoSchema = false;\n return versionInstance;\n };\n\n function Version(versionNumber) {\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n this.stores({}); // Derive earlier schemas by default.\n }\n\n extend(Version.prototype, {\n stores: function (stores) {\n /// \n /// Defines the schema for a particular version\n /// \n /// \n /// Example:
\n /// {users: \"id++,first,last,&username,*email\",
\n /// passwords: \"id++,&username\"}
\n ///
\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

\n /// Special characters:
\n /// \"&\" means unique key,
\n /// \"*\" means value is multiEntry,
\n /// \"++\" means auto-increment and only applicable for primary key
\n /// \n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n var storesSpec = {};\n versions.forEach(function (version) { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n });\n\n var dbschema = (this._cfg.dbschema = {});\n this._parseStoresSpec(storesSpec, dbschema);\n // Update the latest schema to this version\n // Update API\n globalSchema = db._dbSchema = dbschema;\n removeTablesApi([allTables, db, Transaction.prototype]); // Keep Transaction.prototype even though it should be depr.\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n dbStoreNames = keys(dbschema);\n return this;\n },\n upgrade: function (upgradeFunction) {\n /// Function that performs upgrading actions.\n var self = this;\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n },\n _parseStoresSpec: function (stores, outSchema) {\n keys(stores).forEach(function (tableName) {\n if (stores[tableName] !== null) {\n var instanceTemplate = {};\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\n indexes.forEach(function (idx) {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return \"\"; }) : \"\");\n });\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\n }\n });\n }\n });\n \n function runUpgraders (oldVersion, idbtrans, reject) {\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\n trans.create(idbtrans);\n trans._completion.catch(reject);\n var rejectTransaction = trans._reject.bind(trans);\n newScope(function () {\n PSD.trans = trans;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(function (tableName) {\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\n });\n }\n\n function updateTablesAndIndexes (oldVersion, trans, idbtrans) {\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n var queue = [];\n var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0];\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\n var anyContentUpgraderHasRun = false;\n\n var versToRun = versions.filter(v => v._cfg.version > oldVersion);\n versToRun.forEach(function (version) {\n /// \n queue.push(()=>{\n var oldSchema = globalSchema;\n var newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(oldSchema, idbtrans);\n adjustToExistingIndexNames(newSchema, idbtrans);\n globalSchema = db._dbSchema = newSchema;\n var diff = getSchemaDiff(oldSchema, newSchema); \n // Add tables \n diff.add.forEach(function (tuple) {\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(function (change) {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n var store = idbtrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(function (idx) {\n addIndex(store, idx);\n });\n // Update indexes\n change.change.forEach(function (idx) {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(function (idxName) {\n store.deleteIndex(idxName);\n });\n }\n });\n if (version._cfg.contentUpgrade) {\n anyContentUpgraderHasRun = true;\n return Promise.follow(()=>{\n version._cfg.contentUpgrade(trans);\n });\n }\n });\n queue.push(function (idbtrans) {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n var newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n });\n });\n\n // Now, create a queue execution engine\n function runQueue () {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n \n return runQueue().then(()=>{\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n }\n\n function getSchemaDiff(oldSchema, newSchema) {\n var diff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n for (var table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n var oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n var change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (oldDef.primKey.src !== newDef.primKey.src) {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n var oldIndexes = oldDef.idxByName;\n var newIndexes = newDef.idxByName;\n for (var idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n var oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n }\n\n function createTable(idbtrans, tableName, primKey, indexes) {\n /// \n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\n indexes.forEach(function (idx) { addIndex(store, idx); });\n return store;\n }\n\n function createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(function (tableName) {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n }\n\n function deleteRemovedTables(newSchema, idbtrans) {\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\n var storeName = idbtrans.db.objectStoreNames[i];\n if (newSchema[storeName] == null) {\n idbtrans.db.deleteObjectStore(storeName);\n }\n }\n }\n\n function addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n }\n\n //\n //\n // Dexie Protected API\n //\n //\n\n this._allTables = allTables;\n\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\n };\n\n /* Generate a temporary transaction when db operations are done outside a transaction scope.\n */\n function tempTransaction(mode, storeNames, fn) { // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n if (!openComplete && (!PSD.letThrough)) {\n if (!isBeingOpened) {\n if (!autoOpen)\n return rejection (new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, globalSchema);\n try { trans.create(); } catch (ex) { return rejection(ex); }\n return trans._promise(mode, function (resolve, reject) {\n return newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n return trans._completion.then(()=>result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n }\n\n this._whenReady = function (fn) {\n return openComplete || PSD.letThrough ? fn() : new Promise ((resolve, reject) => {\n if (!isBeingOpened) {\n if (!autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n dbReadyPromise.then(resolve, reject);\n }).then(fn);\n };\n \n //\n //\n //\n //\n // Dexie API\n //\n //\n //\n\n this.verno = 0;\n\n this.open = function () {\n if (isBeingOpened || idbdb)\n return dbReadyPromise.then(()=> dbOpenError ? rejection (dbOpenError) : db);\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n isBeingOpened = true;\n dbOpenError = null;\n openComplete = false;\n \n // Function pointers to call when the core opening process completes.\n var resolveDbReady = dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction = null;\n \n return Promise.race([openCanceller, new Promise((resolve, reject) => {\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n \n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI(\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n \n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(\"IndexedDB API not available\"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(fireOnBlocked);\n req.onupgradeneeded = wrap (function (e) {\n upgradeTransaction = req.transaction;\n if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(function () {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\n }\n }, reject);\n \n req.onsuccess = wrap (function () {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n idbdb = req.result;\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n\n if (autoSchema) readGlobalSchema();\n else if (idbdb.objectStoreNames.length > 0) {\n try {\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\n } catch (e) {\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n }\n }\n \n idbdb.onversionchange = wrap(ev => {\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n if (!hasNativeGetDatabaseNames && dbName !== '__dbnames') {\n dbNamesDB.dbnames.put({name: dbName}).catch(nop);\n }\n\n resolve();\n\n }, reject);\n })]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n onReadyBeingFired = [];\n return Promise.resolve(Dexie.vip(db.on.ready.fire)).then(function fireRemainders() {\n if (onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = onReadyBeingFired.reduce(promisableChain, nop);\n onReadyBeingFired = [];\n return Promise.resolve(Dexie.vip(remainders)).then(fireRemainders)\n }\n });\n }).finally(()=>{\n onReadyBeingFired = null;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n isBeingOpened = false;\n return db;\n }).catch(err => {\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch (e) { }\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection (dbOpenError);\n }).finally(()=>{\n openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n };\n \n this.close = function () {\n var idx = connections.indexOf(db);\n if (idx >= 0) connections.splice(idx, 1); \n if (idbdb) {\n try {idbdb.close();} catch(e){}\n idbdb = null;\n }\n autoOpen = false;\n dbOpenError = new exceptions.DatabaseClosed();\n if (isBeingOpened)\n cancelOpen(dbOpenError);\n // Reset dbReadyPromise promise:\n dbReadyPromise = new Promise(resolve => {\n dbReadyResolve = resolve;\n });\n openCanceller = new Promise((_, reject) => {\n cancelOpen = reject;\n });\n };\n \n this.delete = function () {\n var hasArguments = arguments.length > 0;\n return new Promise(function (resolve, reject) {\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (isBeingOpened) {\n dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n function doDelete() {\n db.close();\n var req = indexedDB.deleteDatabase(dbName);\n req.onsuccess = wrap(function () {\n if (!hasNativeGetDatabaseNames) {\n dbNamesDB.dbnames.delete(dbName).catch(nop);\n }\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = fireOnBlocked;\n }\n });\n };\n\n this.backendDB = function () {\n return idbdb;\n };\n\n this.isOpen = function () {\n return idbdb !== null;\n };\n this.hasBeenClosed = function () {\n return dbOpenError && (dbOpenError instanceof exceptions.DatabaseClosed);\n }\n this.hasFailed = function () {\n return dbOpenError !== null;\n };\n this.dynamicallyOpened = function() {\n return autoSchema;\n };\n\n //\n // Properties\n //\n this.name = dbName;\n\n // db.tables - an array of all Table instances.\n props(this, {\n tables: {\n get () {\n /// \n return keys(allTables).map(function (name) { return allTables[name]; });\n }\n }\n });\n\n //\n // Events\n //\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", {ready: [promisableChain, nop]});\n\n this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) {\n return (subscriber, bSticky) => {\n Dexie.vip(()=>{\n if (openComplete) {\n // Database already open. Call subscriber asap.\n if (!dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n this.transaction = function () {\n /// \n ///\n /// \n /// \"r\" for readonly, or \"rw\" for readwrite\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\n /// Function to execute with transaction\n\n var args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n \n function extractTransactionArgs (mode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i-1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n }\n\n this._transaction = function (mode, tables, scopeFunc) {\n var parentTransaction = PSD.trans;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\n var onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n \n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n var storeNames = tables.map(table => {\n var storeName = table instanceof Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode == READONLY)\n mode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n mode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(function (storeName) {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n return (parentTransaction ?\n parentTransaction._promise(mode, enterTransactionScope, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>db._whenReady(enterTransactionScope)) :\n db._whenReady (enterTransactionScope));\n \n function enterTransactionScope() {\n return Promise.resolve().then(()=>{\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n var transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n var zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\n }\n\n // Support for native async await.\n if (scopeFunc.constructor === AsyncFunction) {\n incrementExpectedAwaits();\n }\n\n var returnValue;\n var promiseFollowed = Promise.follow(()=>{\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (returnValue.constructor === NativePromise) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(()=>returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(()=>x);\n }).catch (e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n }\n };\n\n this.table = function (tableName) {\n /// \n if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return allTables[tableName];\n };\n\n //\n //\n //\n // Table Class\n //\n //\n //\n function Table(name, tableSchema, optionalTrans) {\n /// \n this.name = name;\n this.schema = tableSchema;\n this._tx = optionalTrans;\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n }\n\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n }\n\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\n return new Promise((resolve, reject)=>{\n var len = keysOrTuples.length,\n lastItem = len - 1;\n if (len === 0) return resolve();\n if (!hasDeleteHook) {\n for (var i=0; i < len; ++i) {\n var req = idbstore.delete(keysOrTuples[i]);\n req.onerror = eventRejectHandler(reject);\n if (i === lastItem) req.onsuccess = wrap(()=>resolve());\n }\n } else {\n var hookCtx,\n errorHandler = hookedEventRejectHandler(reject),\n successHandler = hookedEventSuccessHandler(null);\n tryCatch(()=> {\n for (var i = 0; i < len; ++i) {\n hookCtx = {onsuccess: null, onerror: null};\n var tuple = keysOrTuples[i];\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\n var req = idbstore.delete(tuple[0]);\n req._hookCtx = hookCtx;\n req.onerror = errorHandler;\n if (i === lastItem)\n req.onsuccess = hookedEventSuccessHandler(resolve);\n else\n req.onsuccess = successHandler;\n }\n }, err=>{\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n }\n });\n } \n\n props(Table.prototype, {\n\n //\n // Table Protected Methods\n //\n\n _trans: function getTransaction(mode, fn, writeLocked) {\n var trans = this._tx || PSD.trans;\n return trans && trans.db === db ?\n trans === PSD.trans ?\n trans._promise (mode, fn, writeLocked) :\n newScope(()=>trans._promise(mode, fn, writeLocked), {trans: trans, transless: PSD.transless || PSD}) :\n tempTransaction (mode, [this.name], fn);\n },\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\n var tableName = this.name;\n function supplyIdbStore (resolve, reject, trans) {\n if (trans.storeNames.indexOf(tableName) === -1)\n throw new exceptions.NotFound(\"Table\" + tableName + \" not part of transaction\");\n return fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\n }\n return this._trans(mode, supplyIdbStore, writeLocked);\n },\n\n //\n // Table Public Methods\n //\n get: function (keyOrCrit, cb) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit).first(cb);\n var self = this;\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\n var req = idbstore.get(keyOrCrit);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(self.hook.reading.fire(req.result));\n }, reject);\n }).then(cb);\n },\n where: function (indexOrCrit) {\n if (typeof indexOrCrit === 'string')\n return new WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n var keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n \n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix =>\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n ix.keyPath.every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n\n if (compoundIndex && maxKey !== maxString)\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n return this\n .where(compoundIndex.name)\n .equals(compoundIndex.keyPath.map(kp => indexOrCrit[kp]));\n\n if (!compoundIndex) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n \n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n var idxByName = this.schema.idxByName;\n var simpleIndex = keyPaths.reduce((r,keyPath)=>[\n r[0] || idxByName[keyPath],\n r[0] || !idxByName[keyPath] ?\n combine(\n r[1],\n x =>''+getByKeyPath(x, keyPath) ==\n ''+indexOrCrit[keyPath])\n : r[1]\n ], [null, null]);\n \n var idx = simpleIndex[0];\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(simpleIndex[1]) :\n compoundIndex ?\n this.filter(simpleIndex[1]) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily.\n },\n count: function (cb) {\n return this.toCollection().count(cb);\n },\n offset: function (offset) {\n return this.toCollection().offset(offset);\n },\n limit: function (numRows) {\n return this.toCollection().limit(numRows);\n },\n reverse: function () {\n return this.toCollection().reverse();\n },\n filter: function (filterFunction) {\n return this.toCollection().and(filterFunction);\n },\n each: function (fn) {\n return this.toCollection().each(fn);\n },\n toArray: function (cb) {\n return this.toCollection().toArray(cb);\n },\n orderBy: function (index) {\n return new Collection(\n new WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n },\n\n toCollection: function () {\n return new Collection(new WhereClause(this));\n },\n\n mapToClass: function (constructor, structure) {\n /// \n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\n /// \n /// Constructor function representing the class.\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\n this.schema.mappedClass = constructor;\n var instanceTemplate = Object.create(constructor.prototype);\n if (structure) {\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\n applyStructure(instanceTemplate, structure);\n }\n this.schema.instanceTemplate = instanceTemplate;\n\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n var readHook = function (obj) {\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\n // Create a new object that derives from constructor:\n var res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){}\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n },\n defineClass: function (structure) {\n /// \n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\n /// as well as making it possible to extend the prototype of the returned constructor function.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n return this.mapToClass(Dexie.defineClass(structure), structure);\n },\n\n bulkDelete: function (keys) {\n if (this.hook.deleting.fire === nop) {\n return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => {\n resolve (bulkDelete(idbstore, trans, keys, false, nop));\n });\n } else {\n return this\n .where(':id')\n .anyOf(keys)\n .delete()\n .then(()=>{}); // Resolve with undefined.\n }\n },\n bulkPut: function(objects, keys) {\n return this._idbstore(READWRITE, (resolve, reject, idbstore) => {\n if (!idbstore.keyPath && !this.schema.primKey.auto && !keys)\n throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n const done = result => {\n if (errorList.length === 0) resolve(result);\n else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList));\n };\n var req,\n errorList = [],\n errorHandler,\n numObjs = objects.length,\n table = this;\n if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) {\n //\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n } else {\n var effectiveKeys = keys || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath));\n // Generate map of {[key]: object}\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); \n var promise = !effectiveKeys ?\n\n // Auto-incremented key-less objects only without any keys argument.\n table.bulkAdd(objects) :\n\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\n // Begin with updating those that exists in DB:\n table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () {\n this.value = objectLookup[this.primKey];\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\n }).catch(ModifyError, e => {\n errorList = e.failures; // No need to concat here. These are the first errors added.\n }).then(()=> {\n // Now, let's examine which items didnt exist so we can add them:\n var objsToAdd = [],\n keysToAdd = keys && [];\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\n for (var i=effectiveKeys.length-1; i>=0; --i) {\n var key = effectiveKeys[i];\n if (key == null || objectLookup[key]) {\n objsToAdd.push(objects[i]);\n keys && keysToAdd.push(key);\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\n }\n }\n // The items are in reverse order so reverse them before adding.\n // Could be important in order to get auto-incremented keys the way the caller\n // would expect. Could have used unshift instead of push()/reverse(),\n // but: http://jsperf.com/unshift-vs-reverse\n objsToAdd.reverse();\n keys && keysToAdd.reverse();\n return table.bulkAdd(objsToAdd, keysToAdd);\n }).then(lastAddedKey => {\n // Resolve with key of the last object in given arguments to bulkPut():\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\n });\n\n promise.then(done).catch(BulkError, e => {\n // Concat failure from ModifyError and reject using our 'done' method.\n errorList = errorList.concat(e.failures);\n done();\n }).catch(reject);\n }\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\n },\n bulkAdd: function(objects, keys) {\n var self = this,\n creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys)\n throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n function done(result) {\n if (errorList.length === 0) resolve(result);\n else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList));\n }\n var req,\n errorList = [],\n errorHandler,\n successHandler,\n numObjs = objects.length;\n if (creatingHook !== nop) {\n //\n // There are subscribers to hook('creating')\n // Must behave as documented.\n //\n var keyPath = idbstore.keyPath,\n hookCtx;\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\n successHandler = hookedEventSuccessHandler(null);\n\n tryCatch(() => {\n for (var i=0, l = objects.length; i < l; ++i) {\n hookCtx = { onerror: null, onsuccess: null };\n var key = keys && keys[i];\n var obj = objects[i],\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\n if (effectiveKey == null && keyToUse != null) {\n if (keyPath) {\n obj = deepClone(obj);\n setByKeyPath(obj, keyPath, keyToUse);\n } else {\n key = keyToUse;\n }\n }\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n if (i < l - 1) {\n req.onerror = errorHandler;\n if (hookCtx.onsuccess)\n req.onsuccess = successHandler;\n }\n }\n }, err => {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\n req.onsuccess = hookedEventSuccessHandler(done);\n } else {\n //\n // Standard Bulk (no 'creating' hook to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n }\n });\n },\n add: function (obj, key) {\n /// \n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\n /// \n /// A javascript object to insert\n /// Primary key\n var creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n var hookCtx = {onsuccess: null, onerror: null};\n if (creatingHook !== nop) {\n var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined);\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\n if (effectiveKey == null && keyToUse != null) { // Using \"==\" and \"!=\" to check for either null or undefined!\n if (idbstore.keyPath)\n setByKeyPath(obj, idbstore.keyPath, keyToUse);\n else\n key = keyToUse;\n }\n }\n try {\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n req.onerror = hookedEventRejectHandler(reject);\n req.onsuccess = hookedEventSuccessHandler(function (result) {\n // TODO: Remove these two lines in next major release (2.0?)\n // It's no good practice to have side effects on provided parameters\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, result);\n resolve(result);\n });\n } catch (e) {\n if (hookCtx.onerror) hookCtx.onerror(e);\n throw e;\n }\n });\n },\n\n put: function (obj, key) {\n /// \n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\n /// \n /// A javascript object to insert or update\n /// Primary key\n var creatingHook = this.hook.creating.fire,\n updatingHook = this.hook.updating.fire;\n if (creatingHook !== nop || updatingHook !== nop) {\n //\n // People listens to when(\"creating\") or when(\"updating\") events!\n // We must know whether the put operation results in an CREATE or UPDATE.\n //\n var keyPath = this.schema.primKey.keyPath;\n var effectiveKey = (key !== undefined) ? key : (keyPath && getByKeyPath(obj, keyPath));\n if (effectiveKey == null) // \"== null\" means checking for either null or undefined.\n return this.add(obj);\n \n // Since key is optional, make sure we get it from obj if not provided\n \n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\n // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.\n obj = deepClone(obj);\n return this._trans(READWRITE, () =>\n this.where(\":id\").equals(effectiveKey).modify(function () {\n // Replace extisting value with our object\n // CRUD event firing handled in Collection.modify()\n this.value = obj;\n }).then(count => count === 0 ? this.add(obj, key) : effectiveKey),\n \"locked\"); // Lock needed because operation is splitted into modify() and add().\n } else {\n // Use the standard IDB put() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function (ev) {\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\n resolve(req.result);\n });\n });\n }\n },\n\n 'delete': function (key) {\n /// Primary key of the object to delete\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\n // call the CRUD event. Only Collection.delete() will know whether an object was actually deleted.\n return this.where(\":id\").equals(key).delete();\n } else {\n // No one listens. Use standard IDB delete() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.delete(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(req.result);\n });\n });\n }\n },\n\n clear: function () {\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\n // call the CRUD event. Only Collection.delete() will knows which objects that are actually deleted.\n return this.toCollection().delete();\n } else {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.clear();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(req.result);\n });\n });\n }\n },\n\n update: function (keyOrObject, modifications) {\n if (typeof modifications !== 'object' || isArray(modifications))\n throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n // object to modify. Also modify given object with the modifications:\n keys(modifications).forEach(function (keyPath) {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection (new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n });\n \n //\n //\n //\n // Transaction Class\n //\n //\n //\n function Transaction(mode, storeNames, dbschema, parent) {\n /// \n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\n /// \n /// Any of \"readwrite\" or \"readonly\"\n /// Array of table names to operate on\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n }\n\n props(Transaction.prototype, {\n //\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n _lock: function () {\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n },\n _unlock: function () {\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n },\n _locked: function () {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n },\n create: function (idbtrans) {\n if (!this.mode) return this;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n });\n return this;\n },\n _promise: function (mode, fn, bWriteLock) {\n\n if (mode === READWRITE && this.mode !== READWRITE)\n return rejection (new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection (new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new Promise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(()=>{\n var p = new Promise((resolve, reject) => {\n this._lock();\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(()=>this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new Promise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n },\n\n _root: function () {\n return this.parent ? this.parent._root() : this;\n },\n\n waitFor (promise) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n promise = Promise.resolve(promise);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(()=>promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin(){\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new Promise ((resolve, reject) => {\n promise.then (\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n },\n\n //\n // Transaction Public Properties and Methods\n //\n abort: function () {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n },\n\n tables: {\n get: Debug.deprecated (\"Transaction.tables\", ()=>allTables)\n },\n\n table: function (name) {\n var table = db.table(name); // Don't check that table is part of transaction. It must fail lazily!\n return new Table(name, table.schema, this);\n }\n });\n\n //\n //\n //\n // WhereClause\n //\n //\n //\n function WhereClause(table, index, orCollection) {\n /// \n /// \n /// \n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n }\n\n props(WhereClause.prototype, function () {\n\n // WhereClause private methods\n\n function fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n }\n\n function emptyCollection(whereClause) {\n return new Collection (whereClause, function() { return IDBKeyRange.only(\"\"); }).limit(0);\n }\n\n function upperFactory(dir) {\n return dir === \"next\" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); };\n }\n function lowerFactory(dir) {\n return dir === \"next\" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); };\n }\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n }\n\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new Collection (whereClause, function() {\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix);\n });\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n }\n\n //\n // WhereClause public methods\n //\n return {\n between: function (lower, upper, includeLower, includeUpper) {\n /// \n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\n /// \n /// \n /// \n /// Whether items that equals lower should be included. Default true.\n /// Whether items that equals upper should be included. Default false.\n /// \n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((cmp(lower, upper) > 0) ||\n (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new Collection (this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); });\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n },\n equals: function (value) {\n return new Collection (this, function() { return IDBKeyRange.only(value); });\n },\n above: function (value) {\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value, true); });\n },\n aboveOrEqual: function (value) {\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value); });\n },\n below: function (value) {\n return new Collection (this, function() { return IDBKeyRange.upperBound(value, true); });\n },\n belowOrEqual: function (value) {\n return new Collection (this, function() { return IDBKeyRange.upperBound(value); });\n },\n startsWith: function (str) {\n /// \n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n },\n startsWithIgnoreCase: function (str) {\n /// \n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString);\n },\n equalsIgnoreCase: function (str) {\n /// \n return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], \"\");\n },\n anyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, \"\");\n },\n startsWithAnyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.some(function(n){\n return x.indexOf(n) === 0;\n });}, set, maxString);\n },\n anyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n var compare = ascending;\n try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n var c = new Collection (this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); });\n\n c._ondirectionchange = function (direction) {\n compare = (direction === \"next\" ? ascending : descending);\n set.sort(compare);\n };\n var i = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n },\n\n notEqual: function(value) {\n return this.inAnyRange([[minKey, value],[value, maxKey]], {includeLowers: false, includeUppers: false});\n },\n\n noneOf: function() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new Collection (this); // Return entire collection.\n try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);}\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; }, null);\n ranges.push([set[set.length - 1], maxKey]);\n return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false});\n },\n\n /** Filter out values withing given set of ranges.\n * Example, give children and elders a rebate of 50%:\n *\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\n *\n * @param {(string|number|Date|Array)[][]} ranges\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\n */\n inAnyRange: function (ranges, options) {\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n var includeLowers = !options || options.includeLowers !== false; // Default to true\n var includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange (ranges, newRange) {\n for (var i=0,l=ranges.length;i 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n var sortDirection = ascending;\n function rangeSorter(a,b) { return sortDirection(a[0], b[0]);}\n\n // Join overlapping ranges\n var set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch(ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n var i = 0;\n var keyIsBeyondCurrentEntry = includeUppers ?\n function(key) { return ascending(key, set[i][1]) > 0; } :\n function(key) { return ascending(key, set[i][1]) >= 0; };\n\n var keyIsBeforeCurrentEntry = includeLowers ?\n function(key) { return descending(key, set[i][0]) > 0; } :\n function(key) { return descending(key, set[i][0]) >= 0; };\n\n function keyWithinCurrentRange (key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n var checkKey = keyIsBeyondCurrentEntry;\n\n var c = new Collection (this, function () {\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\n });\n\n c._ondirectionchange = function (direction) {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function() {\n if (sortDirection === ascending) cursor.continue(set[i][0]);\n else cursor.continue(set[i][1]);\n });\n return false;\n }\n });\n return c;\n },\n startsWithAnyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(function (s) { return typeof s === 'string'; })) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map(function(str) {\n return [str, str + maxString];\n }));\n }\n };\n });\n\n\n\n\n //\n //\n //\n // Collection Class\n //\n //\n //\n function Collection(whereClause, keyRangeGenerator) {\n /// \n ///\n /// \n /// Where clause instance\n /// \n var keyRange = null, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n var whereCtx = whereClause._ctx,\n table = whereCtx.table;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: table.hook.reading.fire\n };\n }\n \n function isPlainKeyRange (ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n } \n\n props(Collection.prototype, function () {\n\n //\n // Collection Private Functions\n //\n\n function addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n }\n\n function addReplayFilter (ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n }\n\n function addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n }\n\n /** @param ctx {\n * isPrimKey: boolean,\n * table: Table,\n * index: string\n * }\n * @param store IDBObjectStore\n **/\n function getIndexOrStore(ctx, store) {\n if (ctx.isPrimKey) return store;\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\n return store.index(indexSpec.name);\n }\n\n /** @param ctx {\n * isPrimKey: boolean,\n * table: Table,\n * index: string,\n * keysOnly: boolean,\n * range?: IDBKeyRange,\n * dir: \"next\" | \"prev\"\n * }\n */\n function openCursor(ctx, store) {\n var idxOrStore = getIndexOrStore(ctx, store);\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ?\n idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) :\n idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\n }\n\n function iter(ctx, fn, resolve, reject, idbstore) {\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\n } else (()=>{\n var set = {};\n var resolved = 0;\n\n function resolveboth() {\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\n }\n\n function union(item, cursor, advance) {\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n ctx.or._iterate(union, resolveboth, reject, idbstore);\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\n })();\n }\n function getInstanceTemplate(ctx) {\n return ctx.table.schema.instanceTemplate;\n }\n \n return {\n\n //\n // Collection Protected Functions\n //\n\n _read: function (fn, cb) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._idbstore(READONLY, fn).then(cb);\n },\n _write: function (fn) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n },\n _addAlgorithm: function (fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n },\n\n _iterate: function (fn, resolve, reject, idbstore) {\n return iter(this._ctx, fn, resolve, reject, idbstore);\n },\n\n clone: function (props) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n },\n\n raw: function () {\n this._ctx.valueMapper = null;\n return this;\n },\n\n //\n // Collection Public methods\n //\n\n each: function (fn) {\n var ctx = this._ctx;\n\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, fn, resolve, reject, idbstore);\n });\n },\n\n count: function (cb) {\n var ctx = this._ctx;\n\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return this._read(function (resolve, reject, idbstore) {\n var idx = getIndexOrStore(ctx, idbstore);\n var req = (ctx.range ? idx.count(ctx.range) : idx.count());\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (e) {\n resolve(Math.min(e.target.result, ctx.limit));\n };\n }, cb);\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore);\n }, cb);\n }\n },\n\n sortBy: function (keyPath, cb) {\n /// \n var parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n },\n\n toArray: function (cb) {\n var ctx = this._ctx;\n return this._read(function (resolve, reject, idbstore) {\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n var readingHook = ctx.table.hook.reading.fire;\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ?\n idxOrStore.getAll(ctx.range, ctx.limit) :\n idxOrStore.getAll(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = readingHook === mirror ?\n eventSuccessHandler(resolve) :\n eventSuccessHandler(res => {\n try {resolve (res.map(readingHook));} catch(e) {reject(e);}\n });\n } else {\n // Getting array through a cursor.\n var a = [];\n iter(ctx, function (item) { a.push(item); }, function arrayComplete() {\n resolve(a);\n }, reject, idbstore);\n }\n }, cb);\n },\n\n offset: function (offset) {\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, ()=> {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(()=> {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, ()=> {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n },\n\n limit: function (numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, ()=> {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n },\n\n until: function (filterFunction, bIncludeStopEntry) {\n var ctx = this._ctx;\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n },\n\n first: function (cb) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n },\n\n last: function (cb) {\n return this.reverse().first(cb);\n },\n\n filter: function (filterFunction) {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction); \n return this;\n },\n \n and: function (filterFunction) {\n return this.filter(filterFunction);\n },\n\n or: function (indexName) {\n return new WhereClause(this._ctx.table, indexName, this);\n },\n\n reverse: function () {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n },\n\n desc: function () {\n return this.reverse();\n },\n\n eachKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n },\n\n eachUniqueKey: function (cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n },\n \n eachPrimaryKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n },\n\n keys: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n },\n \n primaryKeys: function (cb) {\n var ctx = this._ctx;\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read((resolve, reject, idbstore) =>{\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ?\n idxOrStore.getAllKeys(ctx.range, ctx.limit) :\n idxOrStore.getAllKeys(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = eventSuccessHandler(resolve);\n }).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n uniqueKeys: function (cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n },\n\n firstKey: function (cb) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n },\n\n lastKey: function (cb) {\n return this.reverse().firstKey(cb);\n },\n\n distinct: function () {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n },\n\n //\n // Methods that mutate storage\n //\n\n modify: function (changes) {\n var self = this,\n ctx = this._ctx,\n hook = ctx.table.hook,\n updatingHook = hook.updating.fire,\n deletingHook = hook.deleting.fire;\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var modifyer;\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n if (updatingHook === nop && deletingHook === nop) {\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\n modifyer = changes;\n } else {\n // People want to know exactly what is being modified or deleted.\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\n // and call the hooks accordingly!\n modifyer = function (item) {\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\n if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)\n if (!hasOwn(this, \"value\")) {\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\n deletingHook.call(this, this.primKey, item, trans);\n } else {\n // No deletion. Check what was changed\n var objectDiff = getObjectDiff(origItem, this.value);\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\n if (additionalChanges) {\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\n item = this.value;\n keys(additionalChanges).forEach(function (keyPath) {\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n });\n }\n }\n };\n }\n } else if (updatingHook === nop) {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n } else {\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\n // allow it to add additional modifications to make.\n var origChanges = changes;\n changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.\n modifyer = function (item) {\n var anythingModified = false;\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\n if (additionalChanges) extend(changes, additionalChanges);\n keys(changes).forEach(function (keyPath) {\n var val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n });\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\n return anythingModified;\n };\n }\n\n var count = 0;\n var successCount = 0;\n var iterationComplete = false;\n var failures = [];\n var failKeys = [];\n var currentKey = null;\n\n function modifyItem(item, cursor) {\n currentKey = cursor.primaryKey;\n var thisContext = {\n primKey: cursor.primaryKey,\n value: item,\n onsuccess: null,\n onerror: null\n };\n\n function onerror(e) {\n failures.push(e);\n failKeys.push(thisContext.primKey);\n checkFinished();\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\n }\n\n if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update!\n var bDelete = !hasOwn(thisContext, \"value\");\n ++count;\n tryCatch(function () {\n var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value));\n req._hookCtx = thisContext;\n req.onerror = hookedEventRejectHandler(onerror);\n req.onsuccess = hookedEventSuccessHandler(function () {\n ++successCount;\n checkFinished();\n });\n }, onerror);\n } else if (thisContext.onsuccess) {\n // Hook will expect either onerror or onsuccess to always be called!\n thisContext.onsuccess(thisContext.value);\n }\n }\n\n function doReject(e) {\n if (e) {\n failures.push(e);\n failKeys.push(currentKey);\n }\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\n }\n\n function checkFinished() {\n if (iterationComplete && successCount + failures.length === count) {\n if (failures.length > 0)\n doReject();\n else\n resolve(successCount);\n }\n }\n self.clone().raw()._iterate(modifyItem, function () {\n iterationComplete = true;\n checkFinished();\n }, doReject, idbstore);\n });\n },\n\n 'delete': function () {\n var ctx = this._ctx,\n range = ctx.range,\n deletingHook = ctx.table.hook.deleting.fire,\n hasDeleteHook = deletingHook !== nop;\n if (!hasDeleteHook &&\n isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write((resolve, reject, idbstore) => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n var onerror = eventRejectHandler(reject),\n countReq = (range ? idbstore.count(range) : idbstore.count());\n countReq.onerror = onerror;\n countReq.onsuccess = () => {\n var count = countReq.result;\n tryCatch(()=> {\n var delReq = (range ? idbstore.delete(range) : idbstore.clear());\n delReq.onerror = onerror;\n delReq.onsuccess = () => resolve(count);\n }, err => reject(err));\n };\n });\n }\n\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\n // Divide into chunks to not starve RAM.\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\n // more memory and need lower chunk size.\n const CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\n\n return this._write((resolve, reject, idbstore, trans) => {\n var totalCount = 0;\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\n var collection = this\n .clone({\n keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers)\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\n // would become larger than actual delete count.\n .limit(CHUNKSIZE)\n .raw(); // Don't filter through reading-hooks (like mapped classes etc)\n\n var keysOrTuples = [];\n\n // We're gonna do things on as many chunks that are needed.\n // Use recursion of nextChunk function:\n const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => {\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\n // so that the hook can be called with its values in bulkDelete().\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\n } : (val, cursor) => {\n // No one subscribes to hook('deleting'). Collect only primary keys:\n keysOrTuples.push(cursor.primaryKey);\n }).then(() => {\n // Chromium deletes faster when doing it in sort order.\n hasDeleteHook ?\n keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) :\n keysOrTuples.sort(ascending);\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\n\n }).then(()=> {\n var count = keysOrTuples.length;\n totalCount += count;\n keysOrTuples = [];\n return count < CHUNKSIZE ? totalCount : nextChunk();\n });\n\n resolve (nextChunk());\n });\n }\n };\n });\n\n\n //\n //\n //\n // ------------------------- Help functions ---------------------------\n //\n //\n //\n\n function lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n }\n\n function setApiOnPlace(objs, tableNames, dbschema) {\n tableNames.forEach(function (tableName) {\n var schema = dbschema[tableName];\n objs.forEach(obj => {\n if (!(tableName in obj)) {\n if (obj === Transaction.prototype || obj instanceof Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {get() { return this.table(tableName); }});\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new Table(tableName, schema);\n }\n }\n });\n });\n }\n\n function removeTablesApi(objs) {\n objs.forEach(function (obj) {\n for (var key in obj) {\n if (obj[key] instanceof Table) delete obj[key];\n }\n });\n }\n\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn, reject);\n \n if (!req.onerror) req.onerror = eventRejectHandler(reject);\n if (filter) {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () { cursor.continue(); };\n if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject))\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\n c();\n } else {\n resolve();\n }\n }, reject);\n } else {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () { cursor.continue(); };\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\n c();\n } else {\n resolve();\n }\n }, reject);\n }\n }\n\n function parseIndexSyntax(indexes) {\n /// \n /// \n var rv = [];\n indexes.split(',').forEach(function (index) {\n index = index.trim();\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n rv.push(new IndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n /\\./.test(index)\n ));\n });\n return rv;\n }\n\n function cmp(key1, key2) {\n return indexedDB.cmp(key1, key2);\n }\n\n function min(a, b) {\n return cmp(a, b) < 0 ? a : b;\n }\n\n function max(a, b) {\n return cmp(a, b) > 0 ? a : b;\n }\n\n function ascending(a,b) {\n return indexedDB.cmp(a,b);\n }\n\n function descending(a, b) {\n return indexedDB.cmp(b,a);\n }\n\n function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n }\n\n function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n }\n\n function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n }\n\n function readGlobalSchema() {\n db.verno = idbdb.version / 10;\n db._dbSchema = globalSchema = {};\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\n if (dbStoreNames.length === 0) return; // Database contains no stores.\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\n dbStoreNames.forEach(function (storeName) {\n var store = trans.objectStore(storeName),\n keyPath = store.keyPath,\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\n var indexes = [];\n for (var j = 0; j < store.indexNames.length; ++j) {\n var idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\n indexes.push(index);\n }\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\n });\n setApiOnPlace([allTables], keys(globalSchema), globalSchema);\n }\n\n function adjustToExistingIndexNames(schema, idbtrans) {\n /// \n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n /// \n /// Map between name and TableSchema\n /// \n var storeNames = idbtrans.db.objectStoreNames;\n\n for (var i = 0; i < storeNames.length; ++i) {\n var storeName = storeNames[i];\n var store = idbtrans.objectStore(storeName);\n hasGetAll = 'getAll' in store;\n \n for (var j = 0; j < store.indexNames.length; ++j) {\n var indexName = store.indexNames[j];\n var keyPath = store.index(indexName).keyPath;\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n var indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) indexSpec.name = indexName;\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (/Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n hasGetAll = false;\n } \n }\n\n function fireOnBlocked(ev) {\n db.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c=>c.name === db.name && c !== db && !c._vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n extend(this, {\n Collection: Collection,\n Table: Table,\n Transaction: Transaction,\n Version: Version,\n WhereClause: WhereClause\n });\n\n init();\n\n addons.forEach(function (fn) {\n fn(db);\n });\n}\n\nfunction parseType(type) {\n if (typeof type === 'function') {\n return new type();\n } else if (isArray(type)) {\n return [parseType(type[0])];\n } else if (type && typeof type === 'object') {\n var rv = {};\n applyStructure(rv, type);\n return rv;\n } else {\n return type;\n }\n}\n\nfunction applyStructure(obj, structure) {\n keys(structure).forEach(function (member) {\n var value = parseType(structure[member]);\n obj[member] = value;\n });\n return obj;\n}\n\nfunction hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\nfunction eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nfunction eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nfunction hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nfunction preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nfunction awaitIterator (iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext) {\n return val => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n\n//\n// IndexSpec struct\n//\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n this.name = name;\n this.keyPath = keyPath;\n this.unique = unique;\n this.multi = multi;\n this.auto = auto;\n this.compound = compound;\n this.dotted = dotted;\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']');\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\n}\n\n//\n// TableSchema struct\n//\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\n /// \n /// \n /// \n /// \n this.name = name;\n this.primKey = primKey || new IndexSpec();\n this.indexes = indexes || [new IndexSpec()];\n this.instanceTemplate = instanceTemplate;\n this.mappedClass = null;\n this.idxByName = arrayToObject(indexes, index => [index.name, index]);\n}\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\n// Export Error classes\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\n\n//\n// Static methods and properties\n// \nprops(Dexie, {\n \n //\n // Static delete() method.\n //\n delete: function (databaseName) {\n var db = new Dexie(databaseName),\n promise = db.delete();\n promise.onblocked = function (fn) {\n db.on(\"blocked\", fn);\n return this;\n };\n return promise;\n },\n \n //\n // Static exists() method.\n //\n exists: function(name) {\n return new Dexie(name).open().then(db=>{\n db.close();\n return true;\n }).catch(Dexie.NoSuchDatabaseError, () => false);\n },\n \n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames: function (cb) {\n var getDatabaseNames = getNativeGetDatabaseNamesFn(Dexie.dependencies.indexedDB);\n return getDatabaseNames ? new Promise((resolve, reject) => {\n var req = getDatabaseNames();\n req.onsuccess = function (event) {\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\n };\n req.onerror = eventRejectHandler(reject);\n }).then(cb) : dbNamesDB.dbnames.toCollection().primaryKeys(cb);\n },\n \n defineClass: function (structure) {\n /// \n /// Create a javascript constructor based on given template for which properties to expect in the class.\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n\n // Default constructor able to copy given properties into this object.\n function Class(properties) {\n /// Properties to initialize object with.\n /// \n if (properties) extend(this, properties);\n }\n return Class;\n },\n \n applyStructure: applyStructure,\n \n ignoreTransaction: function (scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n \n vip: function (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n },\n\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection (e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n \n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n var promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ? Dexie.ignoreTransaction(promiseOrFunction) : promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ? PSD.trans.waitFor(promise) : promise;\n },\n \n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n \n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter);\n }\n },\n \n // Export our derive/extend/override methodology\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n asap: asap,\n maxKey: maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n \n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\n errnames: errnames,\n \n // Export other static classes\n IndexSpec: IndexSpec,\n TableSchema: TableSchema,\n \n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n },\n \n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p,c,i) => p + (c/Math.pow(10,i*2))),\n \n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n default: Dexie,\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n Dexie: Dexie\n});\n\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\nPromise.rejectionMapper = mapError;\n\n// Initialize dbNamesDB (won't ever be opened on chromium browsers')\ndbNamesDB = new Dexie('__dbnames'); \ndbNamesDB.version(1).stores({dbnames: 'name'});\n\n(()=>{\n // Migrate from Dexie 1.x database names stored in localStorage:\n var DBNAMES = 'Dexie.DatabaseNames';\n if (typeof localStorage !== undefined && _global.document !== undefined) try {\n // Have localStorage and is not executing in a worker. Lets migrate from Dexie 1.x.\n JSON.parse(localStorage.getItem(DBNAMES) || \"[]\")\n .forEach(name => dbNamesDB.dbnames.put({name: name}).catch(nop));\n localStorage.removeItem(DBNAMES);\n } catch (_e) {}\n})();\n"],"names":["asap","props","Debug.setDebug","Debug.debug","Debug.getErrorWithStack","keys","Debug.deprecated"],"mappings":";;;;;;;;;;;;;AAAO,IAAI,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AAC9B,AAAO,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AACnC,AAAO,IAAI,OAAO,GACd,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI;IAClC,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM;QACtC,MAAM,CAAC;AAEX,gBAAuB,GAAG,EAAE,SAAS;IACjC,IAAI,OAAO,SAAS,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAC9C,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,UAAU,GAAG;QACjC,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;KAC7B,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;CACd;AAED,AAAO,IAAM,QAAQ,GAAG,MAAM,CAAC,cAAc,CAAC;AAC9C,AAAO,IAAM,OAAO,GAAG,EAAE,CAAC,cAAc,CAAC;AACzC,gBAAuB,GAAG,EAAE,IAAI;IAC5B,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;CAClC;AAED,eAA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 index 000000000..6cc458948 --- /dev/null +++ b/dist/dexie.js @@ -0,0 +1,4472 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 2.0.2, Thu Mar 01 2018 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Dexie = factory()); +}(this, (function () { 'use strict'; + +var keys = Object.keys; +var isArray = Array.isArray; +var _global = typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; +function extend(obj, extension) { + if (typeof extension !== 'object') + return obj; + keys(extension).forEach(function (key) { + obj[key] = extension[key]; + }); + return obj; +} +var getProto = Object.getPrototypeOf; +var _hasOwn = {}.hasOwnProperty; +function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); +} +function props(proto, extension) { + if (typeof extension === 'function') + extension = extension(getProto(proto)); + keys(extension).forEach(function (key) { + setProp(proto, key, extension[key]); + }); +} +var defineProperty = Object.defineProperty; +function setProp(obj, prop, functionOrGetSet, options) { + defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? + { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : + { value: functionOrGetSet, configurable: true, writable: true }, options)); +} +function derive(Child) { + return { + from: function (Parent) { + Child.prototype = Object.create(Parent.prototype); + setProp(Child.prototype, "constructor", Child); + return { + extend: props.bind(null, Child.prototype) + }; + } + }; +} +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +function getPropertyDescriptor(obj, prop) { + var pd = getOwnPropertyDescriptor(obj, prop), proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); +} +var _slice = [].slice; +function slice(args, start, end) { + return _slice.call(args, start, end); +} +function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); +} +function assert(b) { + if (!b) + throw new Error("Assertion Failed"); +} +function asap(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); +} + +/** Generate an object (hash map) based on given array. + * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to + * instert on the resulting object for each item in the array. If this function returns a falsy value, the + * current item wont affect the resulting object. + */ +function arrayToObject(array, extractor) { + return array.reduce(function (result, item, i) { + var nameAndValue = extractor(item, i); + if (nameAndValue) + result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); +} +function trycatcher(fn, reject) { + return function () { + try { + fn.apply(this, arguments); + } + catch (e) { + reject(e); + } + }; +} +function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } +} +function getByKeyPath(obj, keyPath) { + // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path + if (hasOwn(obj, keyPath)) + return obj[keyPath]; // This line is moved from last to first for optimization purpose. + if (!keyPath) + return obj; + if (typeof keyPath !== 'string') { + var rv = []; + for (var i = 0, l = keyPath.length; i < l; ++i) { + var val = getByKeyPath(obj, keyPath[i]); + rv.push(val); + } + return rv; + } + var period = keyPath.indexOf('.'); + if (period !== -1) { + var innerObj = obj[keyPath.substr(0, period)]; + return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1)); + } + return undefined; +} +function setByKeyPath(obj, keyPath, value) { + if (!obj || keyPath === undefined) + return; + if ('isFrozen' in Object && Object.isFrozen(obj)) + return; + if (typeof keyPath !== 'string' && 'length' in keyPath) { + assert(typeof value !== 'string' && 'length' in value); + for (var i = 0, l = keyPath.length; i < l; ++i) { + setByKeyPath(obj, keyPath[i], value[i]); + } + } + else { + var period = keyPath.indexOf('.'); + if (period !== -1) { + var currentKeyPath = keyPath.substr(0, period); + var remainingKeyPath = keyPath.substr(period + 1); + if (remainingKeyPath === "") + if (value === undefined) + delete obj[currentKeyPath]; + else + obj[currentKeyPath] = value; + else { + var innerObj = obj[currentKeyPath]; + if (!innerObj) + innerObj = (obj[currentKeyPath] = {}); + setByKeyPath(innerObj, remainingKeyPath, value); + } + } + else { + if (value === undefined) + delete obj[keyPath]; + else + obj[keyPath] = value; + } + } +} +function delByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string') + setByKeyPath(obj, keyPath, undefined); + else if ('length' in keyPath) + [].map.call(keyPath, function (kp) { + setByKeyPath(obj, kp, undefined); + }); +} +function shallowClone(obj) { + var rv = {}; + for (var m in obj) { + if (hasOwn(obj, m)) + rv[m] = obj[m]; + } + return rv; +} +var concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} +//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm +var intrinsicTypes = "Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set" + .split(',').concat(flatten([8, 16, 32, 64].map(function (num) { return ["Int", "Uint", "Float"].map(function (t) { return t + num + "Array"; }); }))).filter(function (t) { return _global[t]; }).map(function (t) { return _global[t]; }); +function deepClone(any) { + if (!any || typeof any !== 'object') + return any; + var rv; + if (isArray(any)) { + rv = []; + for (var i = 0, l = any.length; i < l; ++i) { + rv.push(deepClone(any[i])); + } + } + else if (intrinsicTypes.indexOf(any.constructor) >= 0) { + rv = any; + } + else { + rv = any.constructor ? Object.create(any.constructor.prototype) : {}; + for (var prop in any) { + if (hasOwn(any, prop)) { + rv[prop] = deepClone(any[prop]); + } + } + } + return rv; +} +function getObjectDiff(a, b, rv, prfx) { + // Compares objects a and b and produces a diff object. + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) + rv[prfx + prop] = undefined; // Property removed + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && + ap && bp && + // Now compare constructors are same (not equal because wont work in Safari) + ('' + ap.constructor) === ('' + bp.constructor)) + // Same type of object but its properties may have changed + getObjectDiff(ap, bp, rv, prfx + prop + "."); + else if (ap !== bp) + rv[prfx + prop] = b[prop]; // Primitive value changed + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; // Property added + } + }); + return rv; +} +// If first argument is iterable or array-like, return it as an array +var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; +var getIteratorOf = iteratorSymbol ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); +} : function () { return null; }; +var NO_CHAR_ARRAY = {}; +// Takes one or several arguments and returns an array based on the following criteras: +// * If several arguments provided, return arguments converted to an array in a way that +// still allows javascript engine to optimize the code. +// * If single argument is an array, return a clone of it. +// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special +// case to the two bullets below. +// * If single argument is an iterable, convert it to an array and return the resulting array. +// * If single argument is array-like (has length of type number), convert it to an array. +function getArrayOf(arrayLike) { + var i, a, x, it; + if (arguments.length === 1) { + if (isArray(arrayLike)) + return arrayLike.slice(); + if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') + return [arrayLike]; + if ((it = getIteratorOf(arrayLike))) { + a = []; + while ((x = it.next()), !x.done) + a.push(x.value); + return a; + } + if (arrayLike == null) + return [arrayLike]; + i = arrayLike.length; + if (typeof i === 'number') { + a = new Array(i); + while (i--) + a[i] = arrayLike[i]; + return a; + } + return [arrayLike]; + } + i = arguments.length; + a = new Array(i); + while (i--) + a[i] = arguments[i]; + return a; +} + +// By default, debug will be true only if platform is a web platform and its page is served from localhost. +// When debug = true, error's stacks will contain asyncronic long stacks. +var debug = typeof location !== 'undefined' && + // By default, use debug mode if served from localhost. + /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); +function setDebug(value, filter) { + debug = value; + libraryFilter = filter; +} +var libraryFilter = function () { return true; }; +var NEEDS_THROW_FOR_STACK = !new Error("").stack; +function getErrorWithStack() { + "use strict"; + if (NEEDS_THROW_FOR_STACK) + try { + // Doing something naughty in strict mode here to trigger a specific error + // that can be explicitely ignored in debugger's exception settings. + // If we'd just throw new Error() here, IE's debugger's exception settings + // will just consider it as "exception thrown by javascript code" which is + // something you wouldn't want it to ignore. + getErrorWithStack.arguments; + throw new Error(); // Fallback if above line don't throw. + } + catch (e) { + return e; + } + return new Error(); +} +function prettyStack(exception, numIgnoredFrames) { + var stack = exception.stack; + if (!stack) + return ""; + numIgnoredFrames = (numIgnoredFrames || 0); + if (stack.indexOf(exception.name) === 0) + numIgnoredFrames += (exception.name + exception.message).split('\n').length; + return stack.split('\n') + .slice(numIgnoredFrames) + .filter(libraryFilter) + .map(function (frame) { return "\n" + frame; }) + .join(''); +} +function deprecated(what, fn) { + return function () { + console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1)); + return fn.apply(this, arguments); + }; +} + +var dexieErrorNames = [ + 'Modify', + 'Bulk', + 'OpenFailed', + 'VersionChange', + 'Schema', + 'Upgrade', + 'InvalidTable', + 'MissingAPI', + 'NoSuchDatabase', + 'InvalidArgument', + 'SubTransaction', + 'Unsupported', + 'Internal', + 'DatabaseClosed', + 'PrematureCommit', + 'ForeignAwait' +]; +var idbDomErrorNames = [ + 'Unknown', + 'Constraint', + 'Data', + 'TransactionInactive', + 'ReadOnly', + 'Version', + 'NotFound', + 'InvalidState', + 'InvalidAccess', + 'Abort', + 'Timeout', + 'QuotaExceeded', + 'Syntax', + 'DataClone' +]; +var errorList = dexieErrorNames.concat(idbDomErrorNames); +var defaultTexts = { + VersionChanged: "Database version changed by other database connection", + DatabaseClosed: "Database has been closed", + Abort: "Transaction aborted", + TransactionInactive: "Transaction has already completed or failed" +}; +// +// DexieError - base class of all out exceptions. +// +function DexieError(name, msg) { + // Reason we don't use ES6 classes is because: + // 1. It bloats transpiled code and increases size of minified code. + // 2. It doesn't give us much in this case. + // 3. It would require sub classes to call super(), which + // is not needed when deriving from Error. + this._e = getErrorWithStack(); + this.name = name; + this.message = msg; +} +derive(DexieError).from(Error).extend({ + stack: { + get: function () { + return this._stack || + (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); + } + }, + toString: function () { return this.name + ": " + this.message; } +}); +function getMultiErrorMessage(msg, failures) { + return msg + ". Errors: " + failures + .map(function (f) { return f.toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) // Only unique error strings + .join('\n'); +} +// +// ModifyError - thrown in Collection.modify() +// Specific constructor because it contains members failures and failedKeys. +// +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; +} +derive(ModifyError).from(DexieError); +function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = failures; + this.message = getMultiErrorMessage(msg, failures); +} +derive(BulkError).from(DexieError); +// +// +// Dynamically generate error names and exception classes based +// on the names in errorList. +// +// +// Map of {ErrorName -> ErrorName + "Error"} +var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); +// Need an alias for DexieError because we're gonna create subclasses with the same name. +var BaseException = DexieError; +// Map of {ErrorName -> exception constructor} +var exceptions = errorList.reduce(function (obj, name) { + // Let the name be "DexieError" because this name may + // be shown in call stack and when debugging. DexieError is + // the most true name because it derives from DexieError, + // and we cannot change Function.name programatically without + // dynamically create a Function object, which would be considered + // 'eval-evil'. + var fullName = name + "Error"; + function DexieError(msgOrInner, inner) { + this._e = getErrorWithStack(); + this.name = fullName; + if (!msgOrInner) { + this.message = defaultTexts[name] || fullName; + this.inner = null; + } + else if (typeof msgOrInner === 'string') { + this.message = msgOrInner; + this.inner = inner || null; + } + else if (typeof msgOrInner === 'object') { + this.message = msgOrInner.name + " " + msgOrInner.message; + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name] = DexieError; + return obj; +}, {}); +// Use ECMASCRIPT standard exceptions where applicable: +exceptions.Syntax = SyntaxError; +exceptions.Type = TypeError; +exceptions.Range = RangeError; +var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); +function mapError(domError, message) { + if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) + return domError; + var rv = new exceptionMap[domError.name](message || domError.message, domError); + if ("stack" in domError) { + // Derive stack from inner exception if it has a stack + setProp(rv, "stack", { get: function () { + return this.inner.stack; + } }); + } + return rv; +} +var fullNameExceptions = errorList.reduce(function (obj, name) { + if (["Syntax", "Type", "Range"].indexOf(name) === -1) + obj[name + "Error"] = exceptions[name]; + return obj; +}, {}); +fullNameExceptions.ModifyError = ModifyError; +fullNameExceptions.DexieError = DexieError; +fullNameExceptions.BulkError = BulkError; + +function nop() { } +function mirror(val) { return val; } +function pureFunctionChain(f1, f2) { + // Enables chained events that takes ONE argument and returns it to the next function in chain. + // This pattern is used in the hook("reading") event. + if (f1 == null || f1 === mirror) + return f2; + return function (val) { + return f2(f1(val)); + }; +} +function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; +} +function hookCreatingChain(f1, f2) { + // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance. + // This pattern is used in the hook("creating") event. + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res2 !== undefined ? res2 : res; + }; +} +function hookDeletingChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + f1.apply(this, arguments); + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = this.onerror = null; + f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + }; +} +function hookUpdatingChain(f1, f2) { + if (f1 === nop) + return f2; + return function (modifications) { + var res = f1.apply(this, arguments); + extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain. + var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess + onerror = this.onerror; // In case event listener has set this.onerror + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res === undefined ? + (res2 === undefined ? undefined : res2) : + (extend(res, res2)); + }; +} +function reverseStoppableEventChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + if (f2.apply(this, arguments) === false) + return false; + return f1.apply(this, arguments); + }; +} + +function promisableChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} + +/* + * Copyright (c) 2014-2017 David Fahlander + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + */ +// +// Promise and Zone (PSD) for Dexie library +// +// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by +// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. +// +// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another +// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use +// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task +// engine that is indexedDB compliant across all browsers. +// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. +// Also with inspiration from bluebird, asyncronic stacks in debug mode. +// +// Specific non-standard features of this Promise class: +// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as +// native async / await. +// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame +// and below + all promises that those promises creates or awaits. +// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). +// +// David Fahlander, https://github.com/dfahlander +// +// Just a pointer that only this module knows about. +// Used in Promise constructor to emulate a private constructor. +var INTERNAL = {}; +// Async stacks (long stacks) must not grow infinitely. +var LONG_STACKS_CLIP_LIMIT = 100; +var MAX_LONG_STACKS = 20; +var ZONE_ECHO_LIMIT = 7; +var nativePromiseInstanceAndProto = (function () { + try { + // Be able to patch native async functions + return new Function("let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];")(); + } + catch (e) { + var P = _global.Promise; + return P ? + [P.resolve(), P.prototype, P.resolve()] : + []; + } +})(); +var resolvedNativePromise = nativePromiseInstanceAndProto[0]; +var nativePromiseProto = nativePromiseInstanceAndProto[1]; +var resolvedGlobalPromise = nativePromiseInstanceAndProto[2]; +var nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +var AsyncFunction = nativePromiseInstanceAndProto[3]; +var patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +/* The default function used only for the very first promise in a promise chain. + As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks + emulated in this module. For indexedDB compatibility, this means that every method needs to + execute at least one promise before doing an indexedDB operation. Dexie will always call + db.ready().then() for every operation to make sure the indexedDB event is started in an + indexedDB-compatible emulated micro task loop. +*/ +var schedulePhysicalTick = resolvedGlobalPromise ? + function () { resolvedGlobalPromise.then(physicalTick); } + : + _global.setImmediate ? + // setImmediate supported. Those modern platforms also supports Function.bind(). + setImmediate.bind(null, physicalTick) : + _global.MutationObserver ? + // MutationObserver supported + function () { + var hiddenDiv = document.createElement("div"); + (new MutationObserver(function () { + physicalTick(); + hiddenDiv = null; + })).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + // No support for setImmediate or MutationObserver. No worry, setTimeout is only called + // once time. Every tick that follows will be our emulated micro tick. + // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug + function () { setTimeout(physicalTick, 0); }; +// Configurable through Promise.scheduler. +// Don't export because it would be unsafe to let unknown +// code call it unless they do try..catch within their callback. +// This function can be retrieved through getter of Promise.scheduler though, +// but users must not do Promise.scheduler = myFuncThatThrowsException +var asap$1 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; +var isOutsideMicroTick = true; +var needsNewPhysicalTick = true; +var unhandledErrors = []; +var rejectingErrors = []; +var currentFulfiller = null; +var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + finalize: function () { + this.unhandleds.forEach(function (uh) { + try { + globalError(uh[0], uh[1]); + } + catch (e) { } + }); + } +}; +var PSD = globalPSD; +var microtickQueue = []; // Callbacks to call in this or next physical tick. +var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. +var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. +function Promise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. + // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() + // execute the microtask engine implicitely within the call to resolve() or reject(). + // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack + // only contains library code when calling resolve() or reject(). + // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from + // global scope (event handler, timer etc)! + this._lib = false; + // Current async scope + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; // Number of previous promises (for long stacks) + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + // Private constructor (INTERNAL, state, value). + // Used internally by Promise.resolve() and Promise.reject(). + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). + return; + } + this._state = null; // null (=pending), false (=rejected) or true (=resolved) + this._value = null; // error or result + ++psd.ref; // Refcounting current scope + executePromiseTask(this, fn); +} +// Prepare a property descriptor to put onto Promise.prototype.then +var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + if (possibleAwait) + decrementExpectedAwaits(); + var rv = new Promise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; // For idempotense, see setter below. + return then; + }, + // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then + // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor. + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : // Restore to original property descriptor. + { + get: function () { + return value; // Getter returning provided value (behaves like value is just changed) + }, + set: thenProp.set // Keep a setter that is prepared to restore original. + }); + } +}; +props(Promise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + // A little tinier version of then() that don't have to create a resulting promise. + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + // First argument is the Error type to catch + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + // Catching errors by its constructor type (similar to java / c++ / c#) + // Sample: promise.catch(TypeError, function (e) { ... }); + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (err) { + // Catching errors by the error.name property. Makes sense for indexedDB where error type + // is always DOMError but where e.name tells the actual error type. + // Sample: promise.catch('ConstraintError', function (e) { ... }); + return err && err.name === type ? handler(err) : PromiseReject(err); + }); + }, + finally: function (onFinally) { + return this.then(function (value) { + onFinally(); + return value; + }, function (err) { + onFinally(); + return PromiseReject(err); + }); + }, + stack: { + get: function () { + if (this._stack) + return this._stack; + try { + stack_being_generated = true; + var stacks = getStack(this, [], MAX_LONG_STACKS); + var stack = stacks.join("\nFrom previous: "); + if (this._state !== null) + this._stack = stack; // Stack may be updated on reject. + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new Promise(function (resolve, reject) { + var handle = setTimeout(function () { return reject(new exceptions.Timeout(msg)); }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } +}); +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) + setProp(Promise.prototype, Symbol.toStringTag, 'Promise'); +// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env. +// Environment globals snapshotted on leaving global zone +globalPSD.env = snapShot(); +function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; +} +// Promise Static Properties +props(Promise, { + all: function () { + var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like. + .map(onPossibleParallellAsync); // Handle parallell async/awaits + return new Promise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return Promise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof Promise) + return value; + if (value && typeof value.then === 'function') + return new Promise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new Promise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new Promise(function (resolve, reject) { + values.map(function (value) { return Promise.resolve(value).then(resolve, reject); }); + }); + }, + PSD: { + get: function () { return PSD; }, + set: function (value) { return PSD = value; } + }, + //totalEchoes: {get: ()=>totalEchoes}, + //task: {get: ()=>task}, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap$1; }, + set: function (value) { asap$1 = value; } + }, + rejectionMapper: { + get: function () { return rejectionMapper; }, + set: function (value) { rejectionMapper = value; } // Map reject failures + }, + follow: function (fn, zoneProps) { + return new Promise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() + psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. + psd.finalize = callBoth(function () { + var _this = this; + // Unhandled standard or 3rd part promises are put in PSD.unhandleds and + // examined upon scope completion while unhandled rejections in this Promise + // will trigger directly through psd.onunhandled + run_at_end_of_this_or_next_physical_tick(function () { + _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +/** +* Take a potentially misbehaving resolver function and make sure +* onFulfilled and onRejected are only called once. +* +* Makes no guarantees about asynchrony. +*/ +function executePromiseTask(promise, fn) { + // Promise Resolution Procedure: + // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + try { + fn(function (value) { + if (promise._state !== null) + return; // Already settled + if (value === promise) + throw new TypeError('A promise cannot be resolved with itself.'); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === 'function') { + executePromiseTask(promise, function (resolve, reject) { + value instanceof Promise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below + } + catch (ex) { + handleRejection(promise, ex); + } +} +function handleRejection(promise, reason) { + rejectingErrors.push(reason); + if (promise._state !== null) + return; + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + reason = rejectionMapper(reason); + promise._state = false; + promise._value = reason; + debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () { + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: function () { + return stack_being_generated ? + origProp && (origProp.get ? + origProp.get.apply(reason) : + origProp.value) : + promise.stack; + } + }); + }); + // Add the failure to a list of possibly uncaught errors + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); +} +function propagateAllListeners(promise) { + //debug && linkToPreviousPromise(promise); + var listeners = promise._listeners; + promise._listeners = []; + for (var i = 0, len = listeners.length; i < len; ++i) { + propagateToListener(promise, listeners[i]); + } + var psd = promise._PSD; + --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); + if (numScheduledCalls === 0) { + // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, + // and that no deferreds where listening to this rejection or success. + // Since there is a risk that our stack can contain application code that may + // do stuff after this code is finished that may generate new calls, we cannot + // call finalizers here. + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); // Will detect unhandled errors + }, []); + } +} +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap$1(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + // Set static variable currentFulfiller to the promise that is being fullfilled, + // so that we connect the chain of promises (for long stacks support) + currentFulfiller = promise; + // Call callback and resolve our listener with it's return value. + var ret, value = promise._value; + if (promise._state) { + // cb is onResolved + ret = cb(value); + } + else { + // cb is onRejected + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. + } + listener.resolve(ret); + } + catch (e) { + // Exception thrown in callback. Reject our listener. + listener.reject(e); + } + finally { + // Restore env and currentFulfiller. + currentFulfiller = null; + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + --listener.psd.ref || listener.psd.finalize(); + } +} +function getStack(promise, stacks, limit) { + if (stacks.length === limit) + return stacks; + var stack = ""; + if (promise._state === false) { + var failure = promise._value, errorName, message; + if (failure != null) { + errorName = failure.name || "Error"; + message = failure.message || failure; + stack = prettyStack(failure, 0); + } + else { + errorName = failure; // If error is undefined or null, show that. + message = ""; + } + stacks.push(errorName + (message ? ": " + message : "") + stack); + } + if (debug) { + stack = prettyStack(promise._stackHolder, 2); + if (stack && stacks.indexOf(stack) === -1) + stacks.push(stack); + if (promise._prev) + getStack(promise._prev, stacks, limit); + } + return stacks; +} +function linkToPreviousPromise(promise, prev) { + // Support long stacks by linking to previous completed promise. + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } +} +/* The callback to schedule with setImmediate() or setTimeout(). + It runs a virtual microtick and executes any callback registered in microtickQueue. + */ +function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); +} +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} +/* Executes micro-ticks without doing try..catch. + This can be possible because we only use this internally and + the registered functions are exception-safe (they do try..catch + internally before calling any external method). If registering + functions in the microtickQueue that are not exception-safe, this + would destroy the framework and make it instable. So we don't export + our asap method. +*/ +function endMicroTickScope() { + var callbacks, i, l; + do { + while (microtickQueue.length > 0) { + callbacks = microtickQueue; + microtickQueue = []; + l = callbacks.length; + for (i = 0; i < l; ++i) { + var item = callbacks[i]; + item[0].apply(null, item[1]); + } + } + } while (microtickQueue.length > 0); + isOutsideMicroTick = true; + needsNewPhysicalTick = true; +} +function finalizePhysicalTick() { + var unhandledErrs = unhandledErrors; + unhandledErrors = []; + unhandledErrs.forEach(function (p) { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. + var i = finalizers.length; + while (i) + finalizers[--i](); +} +function run_at_end_of_this_or_next_physical_tick(fn) { + function finalizer() { + fn(); + tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); + } + tickFinalizers.push(finalizer); + ++numScheduledCalls; + asap$1(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); +} +function addPossiblyUnhandledError(promise) { + // Only add to unhandledErrors if not already there. The first one to add to this list + // will be upon the first rejection so that the root cause (first promise in the + // rejection chain) is the one listed. + if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) + unhandledErrors.push(promise); +} +function markErrorAsHandled(promise) { + // Called when a reject handled is actually being called. + // Search in unhandledErrors for any promise whos _value is this promise_value (list + // contains only rejected promises, and only one item per error) + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + // Found a promise that failed with this same error object pointer, + // Remove that since there is a listener that actually takes care of it. + unhandledErrors.splice(i, 1); + return; + } +} +function PromiseReject(reason) { + return new Promise(INTERNAL, false, reason); +} +function wrap(fn, errorCatcher) { + var psd = PSD; + return function () { + var wasRootExec = beginMicroTickScope(), outerScope = PSD; + try { + switchToZone(psd, true); + return fn.apply(this, arguments); + } + catch (e) { + errorCatcher && errorCatcher(e); + } + finally { + switchToZone(outerScope, false); + if (wasRootExec) + endMicroTickScope(); + } + }; +} +// +// variables used for native await support +// +var task = { awaits: 0, echoes: 0, id: 0 }; // The ongoing macro-task when using zone-echoing. +var taskCounter = 0; // ID counter for macro tasks. +var zoneStack = []; // Stack of left zones to restore asynchronically. +var zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions. +var totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then. +var zone_id_counter = 0; +function newScope(fn, props$$1, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + // Prepare for promise patching (done in usePSD): + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: Promise, + PromiseProp: { value: Promise, configurable: true, writable: true }, + all: Promise.all, + race: Promise.race, + resolve: Promise.resolve, + reject: Promise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) // global then + } : {}; + if (props$$1) + extend(psd, props$$1); + // unhandleds and onunhandled should not be specifically set here. + // Leave them on parent prototype. + // unhandleds.push(err) will push to parent's prototype + // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2); + if (psd.ref === 0) + psd.finalize(); + return rv; +} +// Function to call if scopeFunc returns NativePromise +// Also for each NativePromise in the arguments to Promise.all() +function incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called. +// Also call this when a native await calls then method on a promise. In that case, don't supply +// sourceTaskId because we already know it refers to current task. +function decrementExpectedAwaits(sourceTaskId) { + if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) + return; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0. +} +// Call from Promise.all() and Promise.race() +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; +} +function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; // Cancel zone echoing. + } + zoneStack.push(PSD); + switchToZone(targetZone, true); +} +function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); +} +function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { + // Enter or leave zone asynchronically as well, so that tasks initiated during current tick + // will be surrounded by the zone when they are invoked. + enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; // The actual zone switch occurs at this line. + // Snapshot on every leave from global zone. + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + // Let's patch the global and native Promises (may be same or may be different) + var GlobalPromise = globalPSD.env.Promise; + // Swich environments (may be PSD-zone or the global zone. Both apply.) + var targetEnv = targetZone.env; + // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed) + // Must be done on each zone change because the patched method contains targetZone in its closure. + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + // Leaving or entering global zone. It's time to patch / restore global Promise. + // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular. + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might + // not be accessing global.Promise but a local reference to it) + GlobalPromise.all = targetEnv.all; + GlobalPromise.race = targetEnv.race; + GlobalPromise.resolve = targetEnv.resolve; + GlobalPromise.reject = targetEnv.reject; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject, + nthen: nativePromiseProto.then, + gthen: GlobalPromise.prototype.then + } : {}; +} +function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } + finally { + switchToZone(outerScope, false); + } +} +function enqueueNativeMicroTask(job) { + // + // Precondition: nativePromiseThen !== undefined + // + nativePromiseThen.call(resolvedNativePromise, job); +} +function nativeAwaitCompatibleWrap(fn, zone, possibleAwait) { + return typeof fn !== 'function' ? fn : function () { + var outerZone = PSD; + if (possibleAwait) + incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } + finally { + switchToZone(outerZone, false); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone, false), nativeAwaitCompatibleWrap(onRejected, zone, false)); + }; +} +var UNHANDLEDREJECTION = "unhandledrejection"; +function globalError(err, promise) { + var rv; + try { + rv = promise.onuncatched(err); + } + catch (e) { } + if (rv !== false) + try { + var event, eventData = { promise: promise, reason: err }; + if (_global.document && document.createEvent) { + event = document.createEvent('Event'); + event.initEvent(UNHANDLEDREJECTION, true, true); + extend(event, eventData); + } + else if (_global.CustomEvent) { + event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); + extend(event, eventData); + } + if (event && _global.dispatchEvent) { + dispatchEvent(event); + if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) + // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. + try { + _global.onunhandledrejection(event); + } + catch (_) { } + } + if (!event.defaultPrevented) { + console.warn("Unhandled rejection: " + (err.stack || err)); + } + } + catch (e) { } +} +var rejection = Promise.reject; + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + // Subscribe. If additional arguments than just the subscriber was provided, forward them as well. + var i = arguments.length, args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + evs[eventName].subscribe.apply(null, args); + return ctx; + } + else if (typeof (eventName) === 'string') { + // Return interface allowing to fire or unsubscribe from event + return evs[eventName]; + } + }; + rv.addEventType = add; + for (var i = 1, l = arguments.length; i < l; ++i) { + add(arguments[i]); + } + return rv; + function add(eventName, chainFunction, defaultFunction) { + if (typeof eventName === 'object') + return addConfiguredEvents(eventName); + if (!chainFunction) + chainFunction = reverseStoppableEventChain; + if (!defaultFunction) + defaultFunction = nop; + var context = { + subscribers: [], + fire: defaultFunction, + subscribe: function (cb) { + if (context.subscribers.indexOf(cb) === -1) { + context.subscribers.push(cb); + context.fire = chainFunction(context.fire, cb); + } + }, + unsubscribe: function (cb) { + context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; }); + context.fire = context.subscribers.reduce(chainFunction, defaultFunction); + } + }; + evs[eventName] = rv[eventName] = context; + return context; + } + function addConfiguredEvents(cfg) { + // events(this, {reading: [functionChain, nop]}); + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack + // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten. + var context = add(eventName, mirror, function fire() { + // Optimazation-safe cloning of arguments into args. + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + // All each subscriber: + context.subscribers.forEach(function (fn) { + asap(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * Copyright (c) 2014-2017 David Fahlander + * + * Version 2.0.2, Thu Mar 01 2018 + * + * http://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + * + */ +var DEXIE_VERSION = '2.0.2'; +var maxString = String.fromCharCode(65535); +var maxKey = (function () { try { + IDBKeyRange.only([[]]); + return [[]]; +} +catch (e) { + return maxString; +} })(); +var minKey = -Infinity; +var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; +var STRING_EXPECTED = "String expected."; +var connections = []; +var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); +var hasIEDeleteObjectStoreBug = isIEOrEdge; +var hangsOnDeleteLargeKeyRange = isIEOrEdge; +var dexieStackFrameFilter = function (frame) { return !/(dexie\.js|dexie\.min\.js)/.test(frame); }; +var dbNamesDB; // Global database for backing Dexie.getDatabaseNames() on browser without indexedDB.webkitGetDatabaseNames() +// Init debug +setDebug(debug, dexieStackFrameFilter); +function Dexie(dbName, options) { + /// Specify only if you wich to control which addons that should run on this instance + var deps = Dexie.dependencies; + var opts = extend({ + // Default Options + addons: Dexie.addons, + autoOpen: true, + indexedDB: deps.indexedDB, + IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to browser env. + }, options); + var addons = opts.addons, autoOpen = opts.autoOpen, indexedDB = opts.indexedDB, IDBKeyRange = opts.IDBKeyRange; + var globalSchema = this._dbSchema = {}; + var versions = []; + var dbStoreNames = []; + var allTables = {}; + /// + var idbdb = null; // Instance of IDBDatabase + var dbOpenError = null; + var isBeingOpened = false; + var onReadyBeingFired = null; + var openComplete = false; + var READONLY = "readonly", READWRITE = "readwrite"; + var db = this; + var dbReadyResolve, dbReadyPromise = new Promise(function (resolve) { + dbReadyResolve = resolve; + }), cancelOpen, openCanceller = new Promise(function (_, reject) { + cancelOpen = reject; + }); + var autoSchema = true; + var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB), hasGetAll; + function init() { + // Default subscribers to "versionchange" and "blocked". + // Can be overridden by custom handlers. If custom handlers return false, these default + // behaviours will be prevented. + db.on("versionchange", function (ev) { + // Default behavior for versionchange event is to close database connection. + // Caller can override this behavior by doing db.on("versionchange", function(){ return false; }); + // Let's not block the other window from making it's delete() or open() call. + // NOTE! This event is never fired in IE,Edge or Safari. + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '" + db.name + "'. Closing db now to resume the upgrade."); + else + console.warn("Another connection wants to delete database '" + db.name + "'. Closing db now to resume the delete request."); + db.close(); + // In many web applications, it would be recommended to force window.reload() + // when this event occurs. To do that, subscribe to the versionchange event + // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion) + // The reason for this is that your current web app obviously has old schema code that needs + // to be updated. Another window got a newer version of the app and needs to upgrade DB but + // your window is blocking it unless we close it here. + }); + db.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('" + db.name + "') was blocked"); + else + console.warn("Upgrade '" + db.name + "' blocked by other connection holding version " + ev.oldVersion / 10); + }); + } + // + // + // + // ------------------------- Versioning Framework--------------------------- + // + // + // + this.version = function (versionNumber) { + /// + /// + if (idbdb || isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + // Disable autoschema mode, as at least one version is specified. + autoSchema = false; + return versionInstance; + }; + function Version(versionNumber) { + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + this.stores({}); // Derive earlier schemas by default. + } + extend(Version.prototype, { + stores: function (stores) { + /// + /// Defines the schema for a particular version + /// + /// + /// Example:
+ /// {users: "id++,first,last,&username,*email",
+ /// passwords: "id++,&username"}
+ ///
+ /// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}

+ /// Special characters:
+ /// "&" means unique key,
+ /// "*" means value is multiEntry,
+ /// "++" means auto-increment and only applicable for primary key
+ /// + this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; + // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax. + var storesSpec = {}; + versions.forEach(function (version) { + extend(storesSpec, version._cfg.storesSource); + }); + var dbschema = (this._cfg.dbschema = {}); + this._parseStoresSpec(storesSpec, dbschema); + // Update the latest schema to this version + // Update API + globalSchema = db._dbSchema = dbschema; + removeTablesApi([allTables, db, Transaction.prototype]); // Keep Transaction.prototype even though it should be depr. + setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + dbStoreNames = keys(dbschema); + return this; + }, + upgrade: function (upgradeFunction) { + /// Function that performs upgrading actions. + var self = this; + this._cfg.contentUpgrade = upgradeFunction; + return this; + }, + _parseStoresSpec: function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var instanceTemplate = {}; + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + if (primKey.keyPath) + setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath); + indexes.forEach(function (idx) { + if (idx.auto) + throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); + if (!idx.keyPath) + throw new exceptions.Schema("Index must have a name and cannot be an empty string"); + setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return ""; }) : ""); + }); + outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate); + } + }); + } + }); + function runUpgraders(oldVersion, idbtrans, reject) { + var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema); + trans.create(idbtrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + newScope(function () { + PSD.trans = trans; + if (oldVersion === 0) { + // Create tables: + keys(globalSchema).forEach(function (tableName) { + createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + Promise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); + } + else + updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction); + }); + } + function updateTablesAndIndexes(oldVersion, trans, idbtrans) { + // Upgrade version to version, step-by-step from oldest to newest version. + // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version) + var queue = []; + var oldVersionStruct = versions.filter(function (version) { return version._cfg.version === oldVersion; })[0]; + if (!oldVersionStruct) + throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing"); + globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema; + var anyContentUpgraderHasRun = false; + var versToRun = versions.filter(function (v) { return v._cfg.version > oldVersion; }); + versToRun.forEach(function (version) { + /// + queue.push(function () { + var oldSchema = globalSchema; + var newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(oldSchema, idbtrans); + adjustToExistingIndexNames(newSchema, idbtrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + // Add tables + diff.add.forEach(function (tuple) { + createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + // Change tables + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + var store = idbtrans.objectStore(change.name); + // Add indexes + change.add.forEach(function (idx) { + addIndex(store, idx); + }); + // Update indexes + change.change.forEach(function (idx) { + store.deleteIndex(idx.name); + addIndex(store, idx); + }); + // Delete indexes + change.del.forEach(function (idxName) { + store.deleteIndex(idxName); + }); + } + }); + if (version._cfg.contentUpgrade) { + anyContentUpgraderHasRun = true; + return Promise.follow(function () { + version._cfg.contentUpgrade(trans); + }); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + var newSchema = version._cfg.dbschema; + // Delete old tables + deleteRemovedTables(newSchema, idbtrans); + } + }); + }); + // Now, create a queue execution engine + function runQueue() { + return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + Promise.resolve(); + } + return runQueue().then(function () { + createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version) + }); + } + function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs} + }; + for (var table in oldSchema) { + if (!newSchema[table]) + diff.del.push(table); + } + for (table in newSchema) { + var oldDef = oldSchema[table], newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } + else { + var change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if (oldDef.primKey.src !== newDef.primKey.src) { + // Primary key has changed. Remove and re-add table. + change.recreate = true; + diff.change.push(change); + } + else { + // Same primary key. Just find out what differs: + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + for (var idxName in oldIndexes) { + if (!newIndexes[idxName]) + change.del.push(idxName); + } + for (idxName in newIndexes) { + var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; + if (!oldIdx) + change.add.push(newIdx); + else if (oldIdx.src !== newIdx.src) + change.change.push(newIdx); + } + if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { + diff.change.push(change); + } + } + } + } + return diff; + } + function createTable(idbtrans, tableName, primKey, indexes) { + /// + var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); + indexes.forEach(function (idx) { addIndex(store, idx); }); + return store; + } + function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(function (tableName) { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); + } + function deleteRemovedTables(newSchema, idbtrans) { + for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) { + var storeName = idbtrans.db.objectStoreNames[i]; + if (newSchema[storeName] == null) { + idbtrans.db.deleteObjectStore(storeName); + } + } + } + function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); + } + // + // + // Dexie Protected API + // + // + this._allTables = allTables; + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { + return new Transaction(mode, storeNames, dbschema, parentTransaction); + }; + /* Generate a temporary transaction when db operations are done outside a transaction scope. + */ + function tempTransaction(mode, storeNames, fn) { + if (!openComplete && (!PSD.letThrough)) { + if (!isBeingOpened) { + if (!autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + return dbReadyPromise.then(function () { return tempTransaction(mode, storeNames, fn); }); + } + else { + var trans = db._createTransaction(mode, storeNames, globalSchema); + try { + trans.create(); + } + catch (ex) { + return rejection(ex); + } + return trans._promise(mode, function (resolve, reject) { + return newScope(function () { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function (result) { + // Instead of resolving value directly, wait with resolving it until transaction has completed. + // Otherwise the data would not be in the DB if requesting it in the then() operation. + // Specifically, to ensure that the following expression will work: + // + // db.friends.put({name: "Arne"}).then(function () { + // db.friends.where("name").equals("Arne").count(function(count) { + // assert (count === 1); + // }); + // }); + // + return trans._completion.then(function () { return result; }); + }); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major. + trans._reject(err); + return rejection(err); + });*/ + } + } + this._whenReady = function (fn) { + return openComplete || PSD.letThrough ? fn() : new Promise(function (resolve, reject) { + if (!isBeingOpened) { + if (!autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway. + } + dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + // + // + // + // + // Dexie API + // + // + // + this.verno = 0; + this.open = function () { + if (isBeingOpened || idbdb) + return dbReadyPromise.then(function () { return dbOpenError ? rejection(dbOpenError) : db; }); + debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called. + isBeingOpened = true; + dbOpenError = null; + openComplete = false; + // Function pointers to call when the core opening process completes. + var resolveDbReady = dbReadyResolve, + // upgradeTransaction to abort on failure. + upgradeTransaction = null; + return Promise.race([openCanceller, new Promise(function (resolve, reject) { + // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE: + // IE fails when deleting objectStore after reading from it. + // A future version of Dexie.js will stopover an intermediate version to workaround this. + // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number. + // If no API, throw! + if (!indexedDB) + throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill."); + var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134 + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (autoSchema && !db._allowEmptyDB) { + // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases. + // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we + // do not create a new database by accident here. + req.onerror = preventDefault; // Prohibit onabort error from firing before we're done! + upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.) + // Close database and delete it. + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here! + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase("Database " + dbName + " doesnt exist")); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix. + runUpgraders(oldVer / 10, upgradeTransaction, reject, req); + } + }, reject); + req.onsuccess = wrap(function () { + // Core opening procedure complete. Now let's just record some stuff. + upgradeTransaction = null; + idbdb = req.result; + connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari. + if (autoSchema) + readGlobalSchema(); + else if (idbdb.objectStoreNames.length > 0) { + try { + adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY)); + } + catch (e) { + // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120. + } + } + idbdb.onversionchange = wrap(function (ev) { + db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari) + db.on("versionchange").fire(ev); + }); + if (!hasNativeGetDatabaseNames && dbName !== '__dbnames') { + dbNamesDB.dbnames.put({ name: dbName }).catch(nop); + } + resolve(); + }, reject); + })]).then(function () { + // Before finally resolving the dbReadyPromise and this promise, + // call and await all on('ready') subscribers: + // Dexie.vip() makes subscribers able to use the database while being opened. + // This is a must since these subscribers take part of the opening procedure. + onReadyBeingFired = []; + return Promise.resolve(Dexie.vip(db.on.ready.fire)).then(function fireRemainders() { + if (onReadyBeingFired.length > 0) { + // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed. + var remainders = onReadyBeingFired.reduce(promisableChain, nop); + onReadyBeingFired = []; + return Promise.resolve(Dexie.vip(remainders)).then(fireRemainders); + } + }); + }).finally(function () { + onReadyBeingFired = null; + }).then(function () { + // Resolve the db.open() with the db instance. + isBeingOpened = false; + return db; + }).catch(function (err) { + try { + // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit. + upgradeTransaction && upgradeTransaction.abort(); + } + catch (e) { } + isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event). + db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh. + // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that. + dbOpenError = err; // Record the error. It will be used to reject further promises of db operations. + return rejection(dbOpenError); + }).finally(function () { + openComplete = true; + resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters. + }); + }; + this.close = function () { + var idx = connections.indexOf(db); + if (idx >= 0) + connections.splice(idx, 1); + if (idbdb) { + try { + idbdb.close(); + } + catch (e) { } + idbdb = null; + } + autoOpen = false; + dbOpenError = new exceptions.DatabaseClosed(); + if (isBeingOpened) + cancelOpen(dbOpenError); + // Reset dbReadyPromise promise: + dbReadyPromise = new Promise(function (resolve) { + dbReadyResolve = resolve; + }); + openCanceller = new Promise(function (_, reject) { + cancelOpen = reject; + }); + }; + this.delete = function () { + var hasArguments = arguments.length > 0; + return new Promise(function (resolve, reject) { + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (isBeingOpened) { + dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + function doDelete() { + db.close(); + var req = indexedDB.deleteDatabase(dbName); + req.onsuccess = wrap(function () { + if (!hasNativeGetDatabaseNames) { + dbNamesDB.dbnames.delete(dbName).catch(nop); + } + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = fireOnBlocked; + } + }); + }; + this.backendDB = function () { + return idbdb; + }; + this.isOpen = function () { + return idbdb !== null; + }; + this.hasBeenClosed = function () { + return dbOpenError && (dbOpenError instanceof exceptions.DatabaseClosed); + }; + this.hasFailed = function () { + return dbOpenError !== null; + }; + this.dynamicallyOpened = function () { + return autoSchema; + }; + // + // Properties + // + this.name = dbName; + // db.tables - an array of all Table instances. + props(this, { + tables: { + get: function () { + /// + return keys(allTables).map(function (name) { return allTables[name]; }); + } + } + }); + // + // Events + // + this.on = Events(this, "populate", "blocked", "versionchange", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + if (openComplete) { + // Database already open. Call subscriber asap. + if (!dbOpenError) + Promise.resolve().then(subscriber); + // bSticky: Also subscribe to future open sucesses (after close / reopen) + if (bSticky) + subscribe(subscriber); + } + else if (onReadyBeingFired) { + // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected + onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + // Database not yet open. Subscribe to it. + subscribe(subscriber); + // If bSticky is falsy, make sure to unsubscribe subscriber when fired once. + if (!bSticky) + subscribe(function unsubscribe() { + db.on.ready.unsubscribe(subscriber); + db.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.transaction = function () { + /// + /// + /// + /// "r" for readonly, or "rw" for readwrite + /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction + /// Function to execute with transaction + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + // Let table arguments be all arguments between mode and last argument. + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments) + // and clone arguments except the first one into local var 'args'. + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments. + scopeFunc = args.pop(); + var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays. + return [mode, tables, scopeFunc]; + } + this._transaction = function (mode, tables, scopeFunc) { + var parentTransaction = PSD.trans; + // Check if parent transactions is bound to this db instance, and if caller wants to reuse it + if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth. + try { + // + // Get storeNames from arguments. Either through given table instances, or through given table names. + // + var storeNames = tables.map(function (table) { + var storeName = table instanceof Table ? table.name : table; + if (typeof storeName !== 'string') + throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); + return storeName; + }); + // + // Resolve mode. Allow shortcuts "r" and "rw". + // + if (mode == "r" || mode == READONLY) + mode = READONLY; + else if (mode == "rw" || mode == READWRITE) + mode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + // Basic checks + if (parentTransaction.mode === READONLY && mode === READWRITE) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); + } + if (parentTransaction) { + storeNames.forEach(function (storeName) { + if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { + if (onlyIfCompatible) { + // Spawn new transaction instead. + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + // '?' mode should not keep using an inactive transaction. + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, function (_, reject) { reject(e); }) : + rejection(e); + } + // If this is a sub-transaction, lock the parent and then launch the sub-transaction. + return (parentTransaction ? + parentTransaction._promise(mode, enterTransactionScope, "lock") : + PSD.trans ? + // no parent transaction despite PSD.trans exists. Make sure also + // that the zone we create is not a sub-zone of current, because + // Promise.follow() should not wait for it if so. + usePSD(PSD.transless, function () { return db._whenReady(enterTransactionScope); }) : + db._whenReady(enterTransactionScope)); + function enterTransactionScope() { + return Promise.resolve().then(function () { + // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction(). + var transless = PSD.transless || PSD; + // Our transaction. + //return new Promise((resolve, reject) => { + var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction); + // Let the transaction instance be part of a Promise-specific data (PSD) value. + var zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing) + trans.idbtrans = parentTransaction.idbtrans; + } + else { + trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it. + } + // Support for native async await. + if (scopeFunc.constructor === AsyncFunction) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = Promise.follow(function () { + // Finally, call the scope function with our table and transaction arguments. + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (returnValue.constructor === NativePromise) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + // scopeFunc returned an iterator with throw-support. Handle yield as await. + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + // Promise returned. User uses promise-style transactions. + Promise.resolve(returnValue).then(function (x) { return trans.active ? + x // Transaction still active. Continue. + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) + // No promise returned. Wait for all outstanding promises before continuing. + : promiseFollowed.then(function () { return returnValue; })).then(function (x) { + // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion: + if (parentTransaction) + trans._resolve(); + // wait for trans._completion + // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves) + return trans._completion.then(function () { return x; }); + }).catch(function (e) { + trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc! + return rejection(e); + }); + }); + } + }; + this.table = function (tableName) { + /// + if (!hasOwn(allTables, tableName)) { + throw new exceptions.InvalidTable("Table " + tableName + " does not exist"); + } + return allTables[tableName]; + }; + // + // + // + // Table Class + // + // + // + function Table(name, tableSchema, optionalTrans) { + /// + this.name = name; + this.schema = tableSchema; + this._tx = optionalTrans; + this.hook = allTables[name] ? allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + } + function BulkErrorHandlerCatchAll(errorList, done, supportHooks) { + return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) { + errorList.push(e); + done && done(); + }); + } + function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) { + // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...], + // else keysOrTuples must be just an array of keys: [key1, key2, ...]. + return new Promise(function (resolve, reject) { + var len = keysOrTuples.length, lastItem = len - 1; + if (len === 0) + return resolve(); + if (!hasDeleteHook) { + for (var i = 0; i < len; ++i) { + var req = idbstore.delete(keysOrTuples[i]); + req.onerror = eventRejectHandler(reject); + if (i === lastItem) + req.onsuccess = wrap(function () { return resolve(); }); + } + } + else { + var hookCtx, errorHandler = hookedEventRejectHandler(reject), successHandler = hookedEventSuccessHandler(null); + tryCatch(function () { + for (var i = 0; i < len; ++i) { + hookCtx = { onsuccess: null, onerror: null }; + var tuple = keysOrTuples[i]; + deletingHook.call(hookCtx, tuple[0], tuple[1], trans); + var req = idbstore.delete(tuple[0]); + req._hookCtx = hookCtx; + req.onerror = errorHandler; + if (i === lastItem) + req.onsuccess = hookedEventSuccessHandler(resolve); + else + req.onsuccess = successHandler; + } + }, function (err) { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + } + }); + } + props(Table.prototype, { + // + // Table Protected Methods + // + _trans: function getTransaction(mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + return trans && trans.db === db ? + trans === PSD.trans ? + trans._promise(mode, fn, writeLocked) : + newScope(function () { return trans._promise(mode, fn, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(mode, [this.name], fn); + }, + _idbstore: function getIDBObjectStore(mode, fn, writeLocked) { + var tableName = this.name; + function supplyIdbStore(resolve, reject, trans) { + if (trans.storeNames.indexOf(tableName) === -1) + throw new exceptions.NotFound("Table" + tableName + " not part of transaction"); + return fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans); + } + return this._trans(mode, supplyIdbStore, writeLocked); + }, + // + // Table Public Methods + // + get: function (keyOrCrit, cb) { + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + var self = this; + return this._idbstore(READONLY, function (resolve, reject, idbstore) { + var req = idbstore.get(keyOrCrit); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(self.hook.reading.fire(req.result)); + }, reject); + }).then(cb); + }, + where: function (indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new WhereClause(this, "[" + indexOrCrit.join('+') + "]"); + // indexOrCrit is an object map of {[keyPath]:value} + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + // Only one critera. This was the easy case: + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + // Multiple criterias. + // Let's try finding a compound index that matches all keyPaths in + // arbritary order: + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { + return ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; }) && + ix.keyPath.every(function (keyPath) { return keyPaths.indexOf(keyPath) >= 0; }); + })[0]; + if (compoundIndex && maxKey !== maxString) + // Cool! We found such compound index + // and this browser supports compound indexes (maxKey !== maxString)! + return this + .where(compoundIndex.name) + .equals(compoundIndex.keyPath.map(function (kp) { return indexOrCrit[kp]; })); + if (!compoundIndex) + console.warn("The query " + JSON.stringify(indexOrCrit) + " on " + this.name + " would benefit of a " + + ("compound index [" + keyPaths.join('+') + "]")); + // Ok, now let's fallback to finding at least one matching index + // and filter the rest. + var idxByName = this.schema.idxByName; + var simpleIndex = keyPaths.reduce(function (r, keyPath) { return [ + r[0] || idxByName[keyPath], + r[0] || !idxByName[keyPath] ? + combine(r[1], function (x) { return '' + getByKeyPath(x, keyPath) == + '' + indexOrCrit[keyPath]; }) + : r[1] + ]; }, [null, null]); + var idx = simpleIndex[0]; + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(simpleIndex[1]) : + compoundIndex ? + this.filter(simpleIndex[1]) : // Has compound but browser bad. Allow filter. + this.where(keyPaths).equals(''); // No index at all. Fail lazily. + }, + count: function (cb) { + return this.toCollection().count(cb); + }, + offset: function (offset) { + return this.toCollection().offset(offset); + }, + limit: function (numRows) { + return this.toCollection().limit(numRows); + }, + reverse: function () { + return this.toCollection().reverse(); + }, + filter: function (filterFunction) { + return this.toCollection().and(filterFunction); + }, + each: function (fn) { + return this.toCollection().each(fn); + }, + toArray: function (cb) { + return this.toCollection().toArray(cb); + }, + orderBy: function (index) { + return new Collection(new WhereClause(this, isArray(index) ? + "[" + index.join('+') + "]" : + index)); + }, + toCollection: function () { + return new Collection(new WhereClause(this)); + }, + mapToClass: function (constructor, structure) { + /// + /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making + /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}. + /// + /// Constructor function representing the class. + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], password} + this.schema.mappedClass = constructor; + var instanceTemplate = Object.create(constructor.prototype); + if (structure) { + // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance. + applyStructure(instanceTemplate, structure); + } + this.schema.instanceTemplate = instanceTemplate; + // Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class + // no matter which method to use for reading (Table.get() or Table.where(...)... ) + var readHook = function (obj) { + if (!obj) + return obj; // No valid object. (Value is null). Return as is. + // Create a new object that derives from constructor: + var res = Object.create(constructor.prototype); + // Clone members: + for (var m in obj) + if (hasOwn(obj, m)) + try { + res[m] = obj[m]; + } + catch (_) { } + return res; + }; + if (this.schema.readHook) { + this.hook.reading.unsubscribe(this.schema.readHook); + } + this.schema.readHook = readHook; + this.hook("reading", readHook); + return constructor; + }, + defineClass: function (structure) { + /// + /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database + /// as well as making it possible to extend the prototype of the returned constructor function. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + return this.mapToClass(Dexie.defineClass(structure), structure); + }, + bulkDelete: function (keys$$1) { + if (this.hook.deleting.fire === nop) { + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + resolve(bulkDelete(idbstore, trans, keys$$1, false, nop)); + }); + } + else { + return this + .where(':id') + .anyOf(keys$$1) + .delete() + .then(function () { }); // Resolve with undefined. + } + }, + bulkPut: function (objects, keys$$1) { + var _this = this; + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys$$1) + throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) + return resolve(); // Caller provided empty list. + var done = function (result) { + if (errorList.length === 0) + resolve(result); + else + reject(new BulkError(_this.name + ".bulkPut(): " + errorList.length + " of " + numObjs + " operations failed", errorList)); + }; + var req, errorList = [], errorHandler, numObjs = objects.length, table = _this; + if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) { + // + // Standard Bulk (no 'creating' or 'updating' hooks to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.put(objects[i], keys$$1[i]) : idbstore.put(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } + else { + var effectiveKeys = keys$$1 || idbstore.keyPath && objects.map(function (o) { return getByKeyPath(o, idbstore.keyPath); }); + // Generate map of {[key]: object} + var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) { return key != null && [key, objects[i]]; }); + var promise = !effectiveKeys ? + // Auto-incremented key-less objects only without any keys argument. + table.bulkAdd(objects) : + // Keys provided. Either as inbound in provided objects, or as a keys argument. + // Begin with updating those that exists in DB: + table.where(':id').anyOf(effectiveKeys.filter(function (key) { return key != null; })).modify(function () { + this.value = objectLookup[this.primKey]; + objectLookup[this.primKey] = null; // Mark as "don't add this" + }).catch(ModifyError, function (e) { + errorList = e.failures; // No need to concat here. These are the first errors added. + }).then(function () { + // Now, let's examine which items didnt exist so we can add them: + var objsToAdd = [], keysToAdd = keys$$1 && []; + // Iterate backwards. Why? Because if same key was used twice, just add the last one. + for (var i = effectiveKeys.length - 1; i >= 0; --i) { + var key = effectiveKeys[i]; + if (key == null || objectLookup[key]) { + objsToAdd.push(objects[i]); + keys$$1 && keysToAdd.push(key); + if (key != null) + objectLookup[key] = null; // Mark as "dont add again" + } + } + // The items are in reverse order so reverse them before adding. + // Could be important in order to get auto-incremented keys the way the caller + // would expect. Could have used unshift instead of push()/reverse(), + // but: http://jsperf.com/unshift-vs-reverse + objsToAdd.reverse(); + keys$$1 && keysToAdd.reverse(); + return table.bulkAdd(objsToAdd, keysToAdd); + }).then(function (lastAddedKey) { + // Resolve with key of the last object in given arguments to bulkPut(): + var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided. + return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey; + }); + promise.then(done).catch(BulkError, function (e) { + // Concat failure from ModifyError and reject using our 'done' method. + errorList = errorList.concat(e.failures); + done(); + }).catch(reject); + } + }, "locked"); // If called from transaction scope, lock transaction til all steps are done. + }, + bulkAdd: function (objects, keys$$1) { + var self = this, creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + if (!idbstore.keyPath && !self.schema.primKey.auto && !keys$$1) + throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); + if (idbstore.keyPath && keys$$1) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys$$1 && keys$$1.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + if (objects.length === 0) + return resolve(); // Caller provided empty list. + function done(result) { + if (errorList.length === 0) + resolve(result); + else + reject(new BulkError(self.name + ".bulkAdd(): " + errorList.length + " of " + numObjs + " operations failed", errorList)); + } + var req, errorList = [], errorHandler, successHandler, numObjs = objects.length; + if (creatingHook !== nop) { + // + // There are subscribers to hook('creating') + // Must behave as documented. + // + var keyPath = idbstore.keyPath, hookCtx; + errorHandler = BulkErrorHandlerCatchAll(errorList, null, true); + successHandler = hookedEventSuccessHandler(null); + tryCatch(function () { + for (var i = 0, l = objects.length; i < l; ++i) { + hookCtx = { onerror: null, onsuccess: null }; + var key = keys$$1 && keys$$1[i]; + var obj = objects[i], effectiveKey = keys$$1 ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined, keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); + if (effectiveKey == null && keyToUse != null) { + if (keyPath) { + obj = deepClone(obj); + setByKeyPath(obj, keyPath, keyToUse); + } + else { + key = keyToUse; + } + } + req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + if (i < l - 1) { + req.onerror = errorHandler; + if (hookCtx.onsuccess) + req.onsuccess = successHandler; + } + } + }, function (err) { + hookCtx.onerror && hookCtx.onerror(err); + throw err; + }); + req.onerror = BulkErrorHandlerCatchAll(errorList, done, true); + req.onsuccess = hookedEventSuccessHandler(done); + } + else { + // + // Standard Bulk (no 'creating' hook to care about) + // + errorHandler = BulkErrorHandlerCatchAll(errorList); + for (var i = 0, l = objects.length; i < l; ++i) { + req = keys$$1 ? idbstore.add(objects[i], keys$$1[i]) : idbstore.add(objects[i]); + req.onerror = errorHandler; + } + // Only need to catch success or error on the last operation + // according to the IDB spec. + req.onerror = BulkErrorHandlerCatchAll(errorList, done); + req.onsuccess = eventSuccessHandler(done); + } + }); + }, + add: function (obj, key) { + /// + /// Add an object to the database. In case an object with same primary key already exists, the object will not be added. + /// + /// A javascript object to insert + /// Primary key + var creatingHook = this.hook.creating.fire; + return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) { + var hookCtx = { onsuccess: null, onerror: null }; + if (creatingHook !== nop) { + var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined); + var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key. + if (effectiveKey == null && keyToUse != null) { + if (idbstore.keyPath) + setByKeyPath(obj, idbstore.keyPath, keyToUse); + else + key = keyToUse; + } + } + try { + var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj); + req._hookCtx = hookCtx; + req.onerror = hookedEventRejectHandler(reject); + req.onsuccess = hookedEventSuccessHandler(function (result) { + // TODO: Remove these two lines in next major release (2.0?) + // It's no good practice to have side effects on provided parameters + var keyPath = idbstore.keyPath; + if (keyPath) + setByKeyPath(obj, keyPath, result); + resolve(result); + }); + } + catch (e) { + if (hookCtx.onerror) + hookCtx.onerror(e); + throw e; + } + }); + }, + put: function (obj, key) { + var _this = this; + /// + /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated. + /// + /// A javascript object to insert or update + /// Primary key + var creatingHook = this.hook.creating.fire, updatingHook = this.hook.updating.fire; + if (creatingHook !== nop || updatingHook !== nop) { + // + // People listens to when("creating") or when("updating") events! + // We must know whether the put operation results in an CREATE or UPDATE. + // + var keyPath = this.schema.primKey.keyPath; + var effectiveKey = (key !== undefined) ? key : (keyPath && getByKeyPath(obj, keyPath)); + if (effectiveKey == null) + return this.add(obj); + // Since key is optional, make sure we get it from obj if not provided + // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add(). + // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation. + obj = deepClone(obj); + return this._trans(READWRITE, function () { + return _this.where(":id").equals(effectiveKey).modify(function () { + // Replace extisting value with our object + // CRUD event firing handled in Collection.modify() + this.value = obj; + }).then(function (count) { return count === 0 ? _this.add(obj, key) : effectiveKey; }); + }, "locked"); // Lock needed because operation is splitted into modify() and add(). + } + else { + // Use the standard IDB put() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function (ev) { + var keyPath = idbstore.keyPath; + if (keyPath) + setByKeyPath(obj, keyPath, ev.target.result); + resolve(req.result); + }); + }); + } + }, + 'delete': function (key) { + /// Primary key of the object to delete + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using Collection.delete() that will + // call the CRUD event. Only Collection.delete() will know whether an object was actually deleted. + return this.where(":id").equals(key).delete(); + } + else { + // No one listens. Use standard IDB delete() method. + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.delete(key); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(req.result); + }); + }); + } + }, + clear: function () { + if (this.hook.deleting.subscribers.length) { + // People listens to when("deleting") event. Must implement delete using Collection.delete() that will + // call the CRUD event. Only Collection.delete() will knows which objects that are actually deleted. + return this.toCollection().delete(); + } + else { + return this._idbstore(READWRITE, function (resolve, reject, idbstore) { + var req = idbstore.clear(); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function () { + resolve(req.result); + }); + }); + } + }, + update: function (keyOrObject, modifications) { + if (typeof modifications !== 'object' || isArray(modifications)) + throw new exceptions.InvalidArgument("Modifications must be an object."); + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + // object to modify. Also modify given object with the modifications: + keys(modifications).forEach(function (keyPath) { + setByKeyPath(keyOrObject, keyPath, modifications[keyPath]); + }); + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === undefined) + return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); + return this.where(":id").equals(key).modify(modifications); + } + else { + // key to modify + return this.where(":id").equals(keyOrObject).modify(modifications); + } + } + }); + // + // + // + // Transaction Class + // + // + // + function Transaction(mode, storeNames, dbschema, parent) { + var _this = this; + /// + /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction. + /// + /// Any of "readwrite" or "readonly" + /// Array of table names to operate on + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._reculock = 0; + this._blockedFuncs = []; + this._resolve = null; + this._reject = null; + this._waitingFor = null; + this._waitingQueue = null; + this._spinCount = 0; // Just for debugging waitFor() + this._completion = new Promise(function (resolve, reject) { + _this._resolve = resolve; + _this._reject = reject; + }); + this._completion.then(function () { + _this.active = false; + _this.on.complete.fire(); + }, function (e) { + var wasActive = _this.active; + _this.active = false; + _this.on.error.fire(e); + _this.parent ? + _this.parent._reject(e) : + wasActive && _this.idbtrans && _this.idbtrans.abort(); + return rejection(e); // Indicate we actually DO NOT catch this error. + }); + } + props(Transaction.prototype, { + // + // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions) + // + _lock: function () { + assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + // Temporary set all requests into a pending queue if they are called before database is ready. + ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage) + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }, + _unlock: function () { + assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope. + if (--this._reculock === 0) { + if (!PSD.global) + PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fnAndPSD = this._blockedFuncs.shift(); + try { + usePSD(fnAndPSD[1], fnAndPSD[0]); + } + catch (e) { } + } + } + return this; + }, + _locked: function () { + // Checks if any write-lock is applied on this transaction. + // To simplify the Dexie API for extension implementations, we support recursive locks. + // This is accomplished by using "Promise Specific Data" (PSD). + // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ). + // PSD is local to code executing on top of the call stacks of any of any code executed by Promise(): + // * callback given to the Promise() constructor (function (resolve, reject){...}) + // * callbacks given to then()/catch()/finally() methods (function (value){...}) + // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise. + // Derivation is done so that the inner PSD __proto__ points to the outer PSD. + // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock. + return this._reculock && PSD.lockOwnerFor !== this; + }, + create: function (idbtrans) { + var _this = this; + if (!this.mode) + return this; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open() + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()! + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) + throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode); + idbtrans.onerror = wrap(function (ev) { + preventDefault(ev); // Prohibit default bubbling to window.error + _this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(function (ev) { + preventDefault(ev); + _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); + _this.active = false; + _this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(function () { + _this.active = false; + _this._resolve(); + }); + return this; + }, + _promise: function (mode, fn, bWriteLock) { + var _this = this; + if (mode === READWRITE && this.mode !== READWRITE) + return rejection(new exceptions.ReadOnly("Transaction is readonly")); + if (!this.active) + return rejection(new exceptions.TransactionInactive()); + if (this._locked()) { + return new Promise(function (resolve, reject) { + _this._blockedFuncs.push([function () { + _this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, PSD]); + }); + } + else if (bWriteLock) { + return newScope(function () { + var p = new Promise(function (resolve, reject) { + _this._lock(); + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p.finally(function () { return _this._unlock(); }); + p._lib = true; + return p; + }); + } + else { + var p = new Promise(function (resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }, + _root: function () { + return this.parent ? this.parent._root() : this; + }, + waitFor: function (promise) { + // Always operate on the root transaction (in case this is a sub stransaction) + var root = this._root(); + // For stability reasons, convert parameter to promise no matter what type is passed to waitFor(). + // (We must be able to call .then() on it.) + promise = Promise.resolve(promise); + if (root._waitingFor) { + // Already called waitFor(). Wait for both to complete. + root._waitingFor = root._waitingFor.then(function () { return promise; }); + } + else { + // We're not in waiting state. Start waiting state. + root._waitingFor = promise; + root._waitingQueue = []; + // Start interacting with indexedDB until promise completes: + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; // For debugging only + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new Promise(function (resolve, reject) { + promise.then(function (res) { return root._waitingQueue.push(wrap(resolve.bind(null, res))); }, function (err) { return root._waitingQueue.push(wrap(reject.bind(null, err))); }).finally(function () { + if (root._waitingFor === currentWaitPromise) { + // No one added a wait after us. Safe to stop the spinning. + root._waitingFor = null; + } + }); + }); + }, + // + // Transaction Public Properties and Methods + // + abort: function () { + this.active && this._reject(new exceptions.Abort()); + this.active = false; + }, + tables: { + get: deprecated("Transaction.tables", function () { return allTables; }) + }, + table: function (name) { + var table = db.table(name); // Don't check that table is part of transaction. It must fail lazily! + return new Table(name, table.schema, this); + } + }); + // + // + // + // WhereClause + // + // + // + function WhereClause(table, index, orCollection) { + /// + /// + /// + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + } + props(WhereClause.prototype, function () { + // WhereClause private methods + function fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; + } + function emptyCollection(whereClause) { + return new Collection(whereClause, function () { return IDBKeyRange.only(""); }).limit(0); + } + function upperFactory(dir) { + return dir === "next" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); }; + } + function lowerFactory(dir) { + return dir === "next" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); }; + } + function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) { + var length = Math.min(key.length, lowerNeedle.length); + var llp = -1; + for (var i = 0; i < length; ++i) { + var lwrKeyChar = lowerKey[i]; + if (lwrKeyChar !== lowerNeedle[i]) { + if (cmp(key[i], upperNeedle[i]) < 0) + return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); + if (cmp(key[i], lowerNeedle[i]) < 0) + return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); + if (llp >= 0) + return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); + return null; + } + if (cmp(key[i], lwrKeyChar) < 0) + llp = i; + } + if (length < lowerNeedle.length && dir === "next") + return key + upperNeedle.substr(key.length); + if (length < key.length && dir === "prev") + return key.substr(0, upperNeedle.length); + return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1)); + } + function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { + /// + var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; + if (!needles.every(function (s) { return typeof s === 'string'; })) { + return fail(whereClause, STRING_EXPECTED); + } + function initDirection(dir) { + upper = upperFactory(dir); + lower = lowerFactory(dir); + compare = (dir === "next" ? simpleCompare : simpleCompareReverse); + var needleBounds = needles.map(function (needle) { + return { lower: lower(needle), upper: upper(needle) }; + }).sort(function (a, b) { + return compare(a.lower, b.lower); + }); + upperNeedles = needleBounds.map(function (nb) { return nb.upper; }); + lowerNeedles = needleBounds.map(function (nb) { return nb.lower; }); + direction = dir; + nextKeySuffix = (dir === "next" ? "" : suffix); + } + initDirection("next"); + var c = new Collection(whereClause, function () { + return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); + }); + c._ondirectionchange = function (direction) { + // This event onlys occur before filter is called the first time. + initDirection(direction); + }; + var firstPossibleNeedle = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + /// + /// + /// + var key = cursor.key; + if (typeof key !== 'string') + return false; + var lowerKey = lower(key); + if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { + return true; + } + else { + var lowestPossibleCasing = null; + for (var i = firstPossibleNeedle; i < needlesLen; ++i) { + var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); + if (casing === null && lowestPossibleCasing === null) + firstPossibleNeedle = i + 1; + else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { + lowestPossibleCasing = casing; + } + } + if (lowestPossibleCasing !== null) { + advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); }); + } + else { + advance(resolve); + } + return false; + } + }); + return c; + } + // + // WhereClause public methods + // + return { + between: function (lower, upper, includeLower, includeUpper) { + /// + /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates. + /// + /// + /// + /// Whether items that equals lower should be included. Default true. + /// Whether items that equals upper should be included. Default false. + /// + includeLower = includeLower !== false; // Default to true + includeUpper = includeUpper === true; // Default to false + try { + if ((cmp(lower, upper) > 0) || + (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection. + return new Collection(this, function () { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); }); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }, + equals: function (value) { + return new Collection(this, function () { return IDBKeyRange.only(value); }); + }, + above: function (value) { + return new Collection(this, function () { return IDBKeyRange.lowerBound(value, true); }); + }, + aboveOrEqual: function (value) { + return new Collection(this, function () { return IDBKeyRange.lowerBound(value); }); + }, + below: function (value) { + return new Collection(this, function () { return IDBKeyRange.upperBound(value, true); }); + }, + belowOrEqual: function (value) { + return new Collection(this, function () { return IDBKeyRange.upperBound(value); }); + }, + startsWith: function (str) { + /// + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }, + startsWithIgnoreCase: function (str) { + /// + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }, + equalsIgnoreCase: function (str) { + /// + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }, + anyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, ""); + }, + startsWithAnyOfIgnoreCase: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function (x, a) { + return a.some(function (n) { + return x.indexOf(n) === 0; + }); + }, set, maxString); + }, + anyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = ascending; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new Collection(this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); }); + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? ascending : descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } + else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }, + notEqual: function (value) { + return this.inAnyRange([[minKey, value], [value, maxKey]], { includeLowers: false, includeUppers: false }); + }, + noneOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new Collection(this); // Return entire collection. + try { + set.sort(ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + // Transform ["a","b","c"] to a set of ranges for between/above/below: [[minKey,"a"], ["a","b"], ["b","c"], ["c",maxKey]] + var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; }, null); + ranges.push([set[set.length - 1], maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }, + /** Filter out values withing given set of ranges. + * Example, give children and elders a rebate of 50%: + * + * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2}); + * + * @param {(string|number|Date|Array)[][]} ranges + * @param {{includeLowers: boolean, includeUppers: boolean}} options + */ + inAnyRange: function (ranges, options) { + if (ranges.length === 0) + return emptyCollection(this); + if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0; })) { + return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); + } + var includeLowers = !options || options.includeLowers !== false; // Default to true + var includeUppers = options && options.includeUppers === true; // Default to false + function addRange(ranges, newRange) { + for (var i = 0, l = ranges.length; i < l; ++i) { + var range = ranges[i]; + if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) { + range[0] = min(range[0], newRange[0]); + range[1] = max(range[1], newRange[1]); + break; + } + } + if (i === l) + ranges.push(newRange); + return ranges; + } + var sortDirection = ascending; + function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } + // Join overlapping ranges + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var i = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function (key) { return ascending(key, set[i][1]) > 0; } : + function (key) { return ascending(key, set[i][1]) >= 0; }; + var keyIsBeforeCurrentEntry = includeLowers ? + function (key) { return descending(key, set[i][0]) > 0; } : + function (key) { return descending(key, set[i][0]) >= 0; }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new Collection(this, function () { + return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); + }); + c._ondirectionchange = function (direction) { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } + else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (checkKey(key)) { + // The cursor has passed beyond this key. Check next. + ++i; + if (i === set.length) { + // There is no next. Stop searching. + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set. + return true; + } + else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) { + // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border. + // Continue to next key but don't include this one. + return false; + } + else { + // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for. + advance(function () { + if (sortDirection === ascending) + cursor.continue(set[i][0]); + else + cursor.continue(set[i][1]); + }); + return false; + } + }); + return c; + }, + startsWithAnyOf: function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (!set.every(function (s) { return typeof s === 'string'; })) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) + return emptyCollection(this); + return this.inAnyRange(set.map(function (str) { + return [str, str + maxString]; + })); + } + }; + }); + // + // + // + // Collection Class + // + // + // + function Collection(whereClause, keyRangeGenerator) { + /// + /// + /// + /// Where clause instance + /// + var keyRange = null, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx, table = whereCtx.table; + this._ctx = { + table: table, + index: whereCtx.index, + isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)), + range: keyRange, + keysOnly: false, + dir: "next", + unique: "", + algorithm: null, + filter: null, + replayFilter: null, + justLimit: true, + isMatch: null, + offset: 0, + limit: Infinity, + error: error, + or: whereCtx.or, + valueMapper: table.hook.reading.fire + }; + } + function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); + } + props(Collection.prototype, function () { + // + // Collection Private Functions + // + function addFilter(ctx, fn) { + ctx.filter = combine(ctx.filter, fn); + } + function addReplayFilter(ctx, factory, isLimitFilter) { + var curr = ctx.replayFilter; + ctx.replayFilter = curr ? function () { return combine(curr(), factory()); } : factory; + ctx.justLimit = isLimitFilter && !curr; + } + function addMatchFilter(ctx, fn) { + ctx.isMatch = combine(ctx.isMatch, fn); + } + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string + * } + * @param store IDBObjectStore + **/ + function getIndexOrStore(ctx, store) { + if (ctx.isPrimKey) + return store; + var indexSpec = ctx.table.schema.idxByName[ctx.index]; + if (!indexSpec) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed"); + return store.index(indexSpec.name); + } + /** @param ctx { + * isPrimKey: boolean, + * table: Table, + * index: string, + * keysOnly: boolean, + * range?: IDBKeyRange, + * dir: "next" | "prev" + * } + */ + function openCursor(ctx, store) { + var idxOrStore = getIndexOrStore(ctx, store); + return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? + idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : + idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique); + } + function iter(ctx, fn, resolve, reject, idbstore) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper); + } + else + (function () { + var set = {}; + var resolved = 0; + function resolveboth() { + if (++resolved === 2) + resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion. + } + function union(item, cursor, advance) { + if (!filter || filter(cursor, advance, resolveboth, reject)) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set, key)) { + set[key] = true; + fn(item, cursor, advance); + } + } + } + ctx.or._iterate(union, resolveboth, reject, idbstore); + iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper); + })(); + } + return { + // + // Collection Protected Functions + // + _read: function (fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._idbstore(READONLY, fn).then(cb); + }, + _write: function (fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued. + }, + _addAlgorithm: function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }, + _iterate: function (fn, resolve, reject, idbstore) { + return iter(this._ctx, fn, resolve, reject, idbstore); + }, + clone: function (props$$1) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props$$1) + extend(ctx, props$$1); + rv._ctx = ctx; + return rv; + }, + raw: function () { + this._ctx.valueMapper = null; + return this; + }, + // + // Collection Public methods + // + each: function (fn) { + var ctx = this._ctx; + return this._read(function (resolve, reject, idbstore) { + iter(ctx, fn, resolve, reject, idbstore); + }); + }, + count: function (cb) { + var ctx = this._ctx; + if (isPlainKeyRange(ctx, true)) { + // This is a plain key range. We can use the count() method if the index. + return this._read(function (resolve, reject, idbstore) { + var idx = getIndexOrStore(ctx, idbstore); + var req = (ctx.range ? idx.count(ctx.range) : idx.count()); + req.onerror = eventRejectHandler(reject); + req.onsuccess = function (e) { + resolve(Math.min(e.target.result, ctx.limit)); + }; + }, cb); + } + else { + // Algorithms, filters or expressions are applied. Need to count manually. + var count = 0; + return this._read(function (resolve, reject, idbstore) { + iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore); + }, cb); + } + }, + sortBy: function (keyPath, cb) { + /// + var parts = keyPath.split('.').reverse(), lastPart = parts[0], lastIndex = parts.length - 1; + function getval(obj, i) { + if (i) + return getval(obj[parts[i]], i - 1); + return obj[lastPart]; + } + var order = this._ctx.dir === "next" ? 1 : -1; + function sorter(a, b) { + var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); + return aVal < bVal ? -order : aVal > bVal ? order : 0; + } + return this.toArray(function (a) { + return a.sort(sorter); + }).then(cb); + }, + toArray: function (cb) { + var ctx = this._ctx; + return this._read(function (resolve, reject, idbstore) { + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAll() or + // IDBKeyRange.getAll(): + var readingHook = ctx.table.hook.reading.fire; + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? + idxOrStore.getAll(ctx.range, ctx.limit) : + idxOrStore.getAll(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = readingHook === mirror ? + eventSuccessHandler(resolve) : + eventSuccessHandler(function (res) { + try { + resolve(res.map(readingHook)); + } + catch (e) { + reject(e); + } + }); + } + else { + // Getting array through a cursor. + var a = []; + iter(ctx, function (item) { a.push(item); }, function arrayComplete() { + resolve(a); + }, reject, idbstore); + } + }, cb); + }, + offset: function (offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; // For count() + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, function () { + var offsetLeft = offset; + return function (cursor, advance) { + if (offsetLeft === 0) + return true; + if (offsetLeft === 1) { + --offsetLeft; + return false; + } + advance(function () { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } + else { + addReplayFilter(ctx, function () { + var offsetLeft = offset; + return function () { return (--offsetLeft < 0); }; + }); + } + return this; + }, + limit: function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count() + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); // Stop after this item has been included + return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here. + }; + }, true); + return this; + }, + until: function (filterFunction, bIncludeStopEntry) { + var ctx = this._ctx; + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + }, + first: function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }, + last: function (cb) { + return this.reverse().first(cb); + }, + filter: function (filterFunction) { + /// function(val){return true/false} + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + // match filters not used in Dexie.js but can be used by 3rd part libraries to test a + // collection for a match without querying DB. Used by Dexie.Observable. + addMatchFilter(this._ctx, filterFunction); + return this; + }, + and: function (filterFunction) { + return this.filter(filterFunction); + }, + or: function (indexName) { + return new WhereClause(this._ctx.table, indexName, this); + }, + reverse: function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }, + desc: function () { + return this.reverse(); + }, + eachKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }, + eachUniqueKey: function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }, + eachPrimaryKey: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }, + keys: function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.key); + }).then(function () { + return a; + }).then(cb); + }, + primaryKeys: function (cb) { + var ctx = this._ctx; + if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + // Special optimation if we could use IDBObjectStore.getAllKeys() or + // IDBKeyRange.getAllKeys(): + return this._read(function (resolve, reject, idbstore) { + var idxOrStore = getIndexOrStore(ctx, idbstore); + var req = ctx.limit < Infinity ? + idxOrStore.getAllKeys(ctx.range, ctx.limit) : + idxOrStore.getAllKeys(ctx.range); + req.onerror = eventRejectHandler(reject); + req.onsuccess = eventSuccessHandler(resolve); + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }, + uniqueKeys: function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }, + firstKey: function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }, + lastKey: function (cb) { + return this.reverse().firstKey(cb); + }, + distinct: function () { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; // distinct() only makes differencies on multiEntry indexes. + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }, + // + // Methods that mutate storage + // + modify: function (changes) { + var self = this, ctx = this._ctx, hook = ctx.table.hook, updatingHook = hook.updating.fire, deletingHook = hook.deleting.fire; + return this._write(function (resolve, reject, idbstore, trans) { + var modifyer; + if (typeof changes === 'function') { + // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item) + if (updatingHook === nop && deletingHook === nop) { + // Noone cares about what is being changed. Just let the modifier function be the given argument as is. + modifyer = changes; + } + else { + // People want to know exactly what is being modified or deleted. + // Let modifyer be a proxy function that finds out what changes the caller is actually doing + // and call the hooks accordingly! + modifyer = function (item) { + var origItem = deepClone(item); // Clone the item first so we can compare laters. + if (changes.call(this, item, this) === false) + return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object) + if (!hasOwn(this, "value")) { + // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place. + deletingHook.call(this, this.primKey, item, trans); + } + else { + // No deletion. Check what was changed + var objectDiff = getObjectDiff(origItem, this.value); + var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans); + if (additionalChanges) { + // Hook want to apply additional modifications. Make sure to fullfill the will of the hook. + item = this.value; + keys(additionalChanges).forEach(function (keyPath) { + setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + }); + } + } + }; + } + } + else if (updatingHook === nop) { + // changes is a set of {keyPath: value} and no one is listening to the updating hook. + var keyPaths = keys(changes); + var numKeys = keyPaths.length; + modifyer = function (item) { + var anythingModified = false; + for (var i = 0; i < numKeys; ++i) { + var keyPath = keyPaths[i], val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath + anythingModified = true; + } + } + return anythingModified; + }; + } + else { + // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and + // allow it to add additional modifications to make. + var origChanges = changes; + changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it. + modifyer = function (item) { + var anythingModified = false; + var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans); + if (additionalChanges) + extend(changes, additionalChanges); + keys(changes).forEach(function (keyPath) { + var val = changes[keyPath]; + if (getByKeyPath(item, keyPath) !== val) { + setByKeyPath(item, keyPath, val); + anythingModified = true; + } + }); + if (additionalChanges) + changes = shallowClone(origChanges); // Restore original changes for next iteration + return anythingModified; + }; + } + var count = 0; + var successCount = 0; + var iterationComplete = false; + var failures = []; + var failKeys = []; + var currentKey = null; + function modifyItem(item, cursor) { + currentKey = cursor.primaryKey; + var thisContext = { + primKey: cursor.primaryKey, + value: item, + onsuccess: null, + onerror: null + }; + function onerror(e) { + failures.push(e); + failKeys.push(thisContext.primKey); + checkFinished(); + return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction + } + if (modifyer.call(thisContext, item, thisContext) !== false) { + var bDelete = !hasOwn(thisContext, "value"); + ++count; + tryCatch(function () { + var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value)); + req._hookCtx = thisContext; + req.onerror = hookedEventRejectHandler(onerror); + req.onsuccess = hookedEventSuccessHandler(function () { + ++successCount; + checkFinished(); + }); + }, onerror); + } + else if (thisContext.onsuccess) { + // Hook will expect either onerror or onsuccess to always be called! + thisContext.onsuccess(thisContext.value); + } + } + function doReject(e) { + if (e) { + failures.push(e); + failKeys.push(currentKey); + } + return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys)); + } + function checkFinished() { + if (iterationComplete && successCount + failures.length === count) { + if (failures.length > 0) + doReject(); + else + resolve(successCount); + } + } + self.clone().raw()._iterate(modifyItem, function () { + iterationComplete = true; + checkFinished(); + }, doReject, idbstore); + }); + }, + 'delete': function () { + var _this = this; + var ctx = this._ctx, range = ctx.range, deletingHook = ctx.table.hook.deleting.fire, hasDeleteHook = deletingHook !== nop; + if (!hasDeleteHook && + isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) { + // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208) + // For chromium, this is the way most optimized version. + // For IE/Edge, this could hang the indexedDB engine and make operating system instable + // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7) + return this._write(function (resolve, reject, idbstore) { + // Our API contract is to return a count of deleted items, so we have to count() before delete(). + var onerror = eventRejectHandler(reject), countReq = (range ? idbstore.count(range) : idbstore.count()); + countReq.onerror = onerror; + countReq.onsuccess = function () { + var count = countReq.result; + tryCatch(function () { + var delReq = (range ? idbstore.delete(range) : idbstore.clear()); + delReq.onerror = onerror; + delReq.onsuccess = function () { return resolve(count); }; + }, function (err) { return reject(err); }); + }; + }); + } + // Default version to use when collection is not a vanilla IDBKeyRange on the primary key. + // Divide into chunks to not starve RAM. + // If has delete hook, we will have to collect not just keys but also objects, so it will use + // more memory and need lower chunk size. + var CHUNKSIZE = hasDeleteHook ? 2000 : 10000; + return this._write(function (resolve, reject, idbstore, trans) { + var totalCount = 0; + // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance. + var collection = _this + .clone({ + keysOnly: !ctx.isMatch && !hasDeleteHook + }) // load just keys (unless filter() or and() or deleteHook has subscribers) + .distinct() // In case multiEntry is used, never delete same key twice because resulting count + .limit(CHUNKSIZE) + .raw(); // Don't filter through reading-hooks (like mapped classes etc) + var keysOrTuples = []; + // We're gonna do things on as many chunks that are needed. + // Use recursion of nextChunk function: + var nextChunk = function () { return collection.each(hasDeleteHook ? function (val, cursor) { + // Somebody subscribes to hook('deleting'). Collect all primary keys and their values, + // so that the hook can be called with its values in bulkDelete(). + keysOrTuples.push([cursor.primaryKey, cursor.value]); + } : function (val, cursor) { + // No one subscribes to hook('deleting'). Collect only primary keys: + keysOrTuples.push(cursor.primaryKey); + }).then(function () { + // Chromium deletes faster when doing it in sort order. + hasDeleteHook ? + keysOrTuples.sort(function (a, b) { return ascending(a[0], b[0]); }) : + keysOrTuples.sort(ascending); + return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook); + }).then(function () { + var count = keysOrTuples.length; + totalCount += count; + keysOrTuples = []; + return count < CHUNKSIZE ? totalCount : nextChunk(); + }); }; + resolve(nextChunk()); + }); + } + }; + }); + // + // + // + // ------------------------- Help functions --------------------------- + // + // + // + function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; + } + function setApiOnPlace(objs, tableNames, dbschema) { + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + if (!(tableName in obj)) { + if (obj === Transaction.prototype || obj instanceof Transaction) { + // obj is a Transaction prototype (or prototype of a subclass to Transaction) + // Make the API a getter that returns this.table(tableName) + setProp(obj, tableName, { get: function () { return this.table(tableName); } }); + } + else { + // Table will not be bound to a transaction (will use Dexie.currentTransaction) + obj[tableName] = new Table(tableName, schema); + } + } + }); + }); + } + function removeTablesApi(objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof Table) + delete obj[key]; + } + }); + } + function iterate(req, filter, fn, resolve, reject, valueMapper) { + // Apply valueMapper (hook('reading') or mappped class) + var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; + // Wrap fn with PSD and microtick stuff from Promise. + var wrappedFn = wrap(mappedFn, reject); + if (!req.onerror) + req.onerror = eventRejectHandler(reject); + if (filter) { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { cursor.continue(); }; + if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject)) + wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); + c(); + } + else { + resolve(); + } + }, reject); + } + else { + req.onsuccess = trycatcher(function filter_record() { + var cursor = req.result; + if (cursor) { + var c = function () { cursor.continue(); }; + wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; }); + c(); + } + else { + resolve(); + } + }, reject); + } + } + function parseIndexSyntax(indexes) { + /// + /// + var rv = []; + indexes.split(',').forEach(function (index) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*" + // Let keyPath of "[a+b]" be ["a","b"]: + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index))); + }); + return rv; + } + function cmp(key1, key2) { + return indexedDB.cmp(key1, key2); + } + function min(a, b) { + return cmp(a, b) < 0 ? a : b; + } + function max(a, b) { + return cmp(a, b) > 0 ? a : b; + } + function ascending(a, b) { + return indexedDB.cmp(a, b); + } + function descending(a, b) { + return indexedDB.cmp(b, a); + } + function simpleCompare(a, b) { + return a < b ? -1 : a === b ? 0 : 1; + } + function simpleCompareReverse(a, b) { + return a > b ? -1 : a === b ? 0 : 1; + } + function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; + } + function readGlobalSchema() { + db.verno = idbdb.version / 10; + db._dbSchema = globalSchema = {}; + dbStoreNames = slice(idbdb.objectStoreNames, 0); + if (dbStoreNames.length === 0) + return; // Database contains no stores. + var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly'); + dbStoreNames.forEach(function (storeName) { + var store = trans.objectStore(storeName), keyPath = store.keyPath, dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1; + var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted); + indexes.push(index); + } + globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {}); + }); + setApiOnPlace([allTables], keys(globalSchema), globalSchema); + } + function adjustToExistingIndexNames(schema, idbtrans) { + /// + /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db + /// + /// Map between name and TableSchema + /// + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + hasGetAll = 'getAll' in store; + for (var j = 0; j < store.indexNames.length; ++j) { + var indexName = store.indexNames[j]; + var keyPath = store.index(indexName).keyPath; + var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; + if (schema[storeName]) { + var indexSpec = schema[storeName].idxByName[dexieName]; + if (indexSpec) + indexSpec.name = indexName; + } + } + } + // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579 + if (/Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + hasGetAll = false; + } + } + function fireOnBlocked(ev) { + db.on("blocked").fire(ev); + // Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari: + connections + .filter(function (c) { return c.name === db.name && c !== db && !c._vcFired; }) + .map(function (c) { return c.on("versionchange").fire(ev); }); + } + extend(this, { + Collection: Collection, + Table: Table, + Transaction: Transaction, + Version: Version, + WhereClause: WhereClause + }); + init(); + addons.forEach(function (fn) { + fn(db); + }); +} +function parseType(type) { + if (typeof type === 'function') { + return new type(); + } + else if (isArray(type)) { + return [parseType(type[0])]; + } + else if (type && typeof type === 'object') { + var rv = {}; + applyStructure(rv, type); + return rv; + } + else { + return type; + } +} +function applyStructure(obj, structure) { + keys(structure).forEach(function (member) { + var value = parseType(structure[member]); + obj[member] = value; + }); + return obj; +} +function hookedEventSuccessHandler(resolve) { + // wrap() is needed when calling hooks because the rare scenario of: + // * hook does a db operation that fails immediately (IDB throws exception) + // For calling db operations on correct transaction, wrap makes sure to set PSD correctly. + // wrap() will also execute in a virtual tick. + // * If not wrapped in a virtual tick, direct exception will launch a new physical tick. + // * If this was the last event in the bulk, the promise will resolve after a physical tick + // and the transaction will have committed already. + // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise, + // because it is always marked with _lib = true when created using Transaction._promise(). + return wrap(function (event) { + var req = event.target, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. + result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key. + hookSuccessHandler = ctx && ctx.onsuccess; + hookSuccessHandler && hookSuccessHandler(result); + resolve && resolve(result); + }, resolve); +} +function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); +} +function eventSuccessHandler(resolve) { + return wrap(function (event) { + resolve(event.target.result); + }); +} +function hookedEventRejectHandler(reject) { + return wrap(function (event) { + // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks. + var req = event.target, err = req.error, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. + hookErrorHandler = ctx && ctx.onerror; + hookErrorHandler && hookErrorHandler(err); + preventDefault(event); + reject(err); + return false; + }); +} +function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); +} +function awaitIterator(iterator) { + var callNext = function (result) { return iterator.next(result); }, doThrow = function (error) { return iterator.throw(error); }, onSuccess = step(callNext), onError = step(doThrow); + function step(getNext) { + return function (val) { + var next = getNext(val), value = next.value; + return next.done ? value : + (!value || typeof value.then !== 'function' ? + isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : + value.then(onSuccess, onError)); + }; + } + return step(callNext)(); +} +// +// IndexSpec struct +// +function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) { + /// + /// + /// + /// + /// + /// + /// + this.name = name; + this.keyPath = keyPath; + this.unique = unique; + this.multi = multi; + this.auto = auto; + this.compound = compound; + this.dotted = dotted; + var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']'); + this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc; +} +// +// TableSchema struct +// +function TableSchema(name, primKey, indexes, instanceTemplate) { + /// + /// + /// + /// + this.name = name; + this.primKey = primKey || new IndexSpec(); + this.indexes = indexes || [new IndexSpec()]; + this.instanceTemplate = instanceTemplate; + this.mappedClass = null; + this.idxByName = arrayToObject(indexes, function (index) { return [index.name, index]; }); +} +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} +function getNativeGetDatabaseNamesFn(indexedDB) { + var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames); + return fn && fn.bind(indexedDB); +} +// Export Error classes +props(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...}; +// +// Static methods and properties +// +props(Dexie, { + // + // Static delete() method. + // + delete: function (databaseName) { + var db = new Dexie(databaseName), promise = db.delete(); + promise.onblocked = function (fn) { + db.on("blocked", fn); + return this; + }; + return promise; + }, + // + // Static exists() method. + // + exists: function (name) { + return new Dexie(name).open().then(function (db) { + db.close(); + return true; + }).catch(Dexie.NoSuchDatabaseError, function () { return false; }); + }, + // + // Static method for retrieving a list of all existing databases at current host. + // + getDatabaseNames: function (cb) { + var getDatabaseNames = getNativeGetDatabaseNamesFn(Dexie.dependencies.indexedDB); + return getDatabaseNames ? new Promise(function (resolve, reject) { + var req = getDatabaseNames(); + req.onsuccess = function (event) { + resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array + }; + req.onerror = eventRejectHandler(reject); + }).then(cb) : dbNamesDB.dbnames.toCollection().primaryKeys(cb); + }, + defineClass: function (structure) { + /// + /// Create a javascript constructor based on given template for which properties to expect in the class. + /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}. + /// + /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also + /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}} + // Default constructor able to copy given properties into this object. + function Class(properties) { + /// Properties to initialize object with. + /// + if (properties) + extend(this, properties); + } + return Class; + }, + applyStructure: applyStructure, + ignoreTransaction: function (scopeFunc) { + // In case caller is within a transaction but needs to create a separate transaction. + // Example of usage: + // + // Let's say we have a logger function in our app. Other application-logic should be unaware of the + // logger function and not need to include the 'logentries' table in all transaction it performs. + // The logging should always be done in a separate transaction and not be dependant on the current + // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction. + // + // Dexie.ignoreTransaction(function() { + // db.logentries.add(newLogEntry); + // }); + // + // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction + // in current Promise-scope. + // + // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an + // API for this because + // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout(). + // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate(). + // 3) setImmediate() is not supported in the ES standard. + // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough. + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional. + scopeFunc(); // No need to change scope because there is no ongoing transaction. + }, + vip: function (fn) { + // To be used by subscribers to the on('ready') event. + // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing. + // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD + // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since + // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that. + // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip() + // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by + // the caller will not resolve until database is opened. + return newScope(function () { + PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing. + return fn(); + }); + }, + async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return Promise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }; + }, + spawn: function (generatorFn, args, thiz) { + try { + var rv = awaitIterator(generatorFn.apply(thiz, args || [])); + if (!rv || typeof rv.then !== 'function') + return Promise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + // Dexie.currentTransaction property + currentTransaction: { + get: function () { return PSD.trans || null; } + }, + waitFor: function (promiseOrFunction, optionalTimeout) { + // If a function is provided, invoke it and pass the returning value to Transaction.waitFor() + var promise = Promise.resolve(typeof promiseOrFunction === 'function' ? Dexie.ignoreTransaction(promiseOrFunction) : promiseOrFunction) + .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. + // Run given promise on current transaction. If no current transaction, just return a Dexie promise based + // on given value. + return PSD.trans ? PSD.trans.waitFor(promise) : promise; + }, + // Export our Promise implementation since it can be handy as a standalone Promise implementation + Promise: Promise, + // Dexie.debug proptery: + // Dexie.debug = false + // Dexie.debug = true + // Dexie.debug = "dexie" - don't hide dexie's stack frames. + debug: { + get: function () { return debug; }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); + } + }, + // Export our derive/extend/override methodology + derive: derive, + extend: extend, + props: props, + override: override, + // Export our Events() function - can be handy as a toolkit + Events: Events, + // Utilities + getByKeyPath: getByKeyPath, + setByKeyPath: setByKeyPath, + delByKeyPath: delByKeyPath, + shallowClone: shallowClone, + deepClone: deepClone, + getObjectDiff: getObjectDiff, + asap: asap, + maxKey: maxKey, + minKey: minKey, + // Addon registry + addons: [], + // Global DB connection list + connections: connections, + MultiModifyError: exceptions.Modify, + errnames: errnames, + // Export other static classes + IndexSpec: IndexSpec, + TableSchema: TableSchema, + // + // Dependencies + // + // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included. + // + // In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). + // For node.js, you need to require indexeddb-js or similar and then set these deps. + // + dependencies: { + // Required: + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }, + // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc. + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split('.') + .map(function (n) { return parseInt(n); }) + .reduce(function (p, c, i) { return p + (c / Math.pow(10, i * 2)); }), + // https://github.com/dfahlander/Dexie.js/issues/186 + // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return + // x.default. Workaround: Set Dexie.default = Dexie. + default: Dexie, + // Make it possible to import {Dexie} (non-default import) + // Reason 1: May switch to that in future. + // Reason 2: We declare it both default and named exported in d.ts to make it possible + // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely + // exporting the symbol, not just default exporting) + Dexie: Dexie +}); +// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0. +Promise.rejectionMapper = mapError; +// Initialize dbNamesDB (won't ever be opened on chromium browsers') +dbNamesDB = new Dexie('__dbnames'); +dbNamesDB.version(1).stores({ dbnames: 'name' }); +(function () { + // Migrate from Dexie 1.x database names stored in localStorage: + var DBNAMES = 'Dexie.DatabaseNames'; + if (typeof localStorage !== undefined && _global.document !== undefined) + try { + // Have localStorage and is not executing in a worker. Lets migrate from Dexie 1.x. + JSON.parse(localStorage.getItem(DBNAMES) || "[]") + .forEach(function (name) { return dbNamesDB.dbnames.put({ name: name }).catch(nop); }); + localStorage.removeItem(DBNAMES); + } + catch (_e) { } +})(); + +return Dexie; + +}))); +//# sourceMappingURL=dexie.js.map diff --git a/dist/dexie.js.map b/dist/dexie.js.map new file mode 100644 index 000000000..eaa5a5a3f --- /dev/null +++ b/dist/dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.js","sources":["../src/utils.js","../src/debug.js","../src/errors.js","../src/chaining-functions.js","../src/Promise.js","../src/Events.js","../src/Dexie.js"],"sourcesContent":["export var keys = Object.keys;\nexport var isArray = Array.isArray;\nexport var _global =\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n\nexport function extend(obj, extension) {\n if (typeof extension !== 'object') return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n keys(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n var pd = getOwnPropertyDescriptor(obj, prop),\n proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nvar _slice = [].slice;\nexport function slice(args, start, end) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array, extractor) {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn, onerror, args) {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a) {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nvar intrinsicTypes =\n \"Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]).map(t=>_global[t])\n\nexport function deepClone(any) {\n if (!any || typeof any !== 'object') return any;\n var rv;\n if (isArray(any)) {\n rv = [];\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(deepClone(any[i]));\n }\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n } else {\n rv = any.constructor ? Object.create(any.constructor.prototype) : {};\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = deepClone(any[prop]);\n }\n }\n }\n return rv;\n}\n\nexport function getObjectDiff(a, b, rv, prfx) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach(prop => {\n if (!hasOwn(b, prop))\n rv[prfx+prop] = undefined; // Property removed\n else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' &&\n ap && bp &&\n // Now compare constructors are same (not equal because wont work in Safari)\n (''+ap.constructor) === (''+bp.constructor))\n // Same type of object but its properties may have changed\n getObjectDiff (ap, bp, rv, prfx + prop + \".\");\n else if (ap !== bp)\n rv[prfx + prop] = b[prop];// Primitive value changed\n }\n });\n keys(b).forEach(prop => {\n if (!hasOwn(a, prop)) {\n rv[prfx+prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\nexport const getIteratorOf = iteratorSymbol ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch(e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\nexport function deprecated (what, fn) {\n return function () {\n console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n }\n}\n","import { derive, setProp } from './utils';\nimport { getErrorWithStack, prettyStack } from './debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function() {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + failures\n .map(f=>f.toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = failures;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = msgOrInner;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend} from './utils';\nimport {nop, callBoth, mirror} from './chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from './errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 7,\n nativePromiseInstanceAndProto = (()=>{\n try {\n // Be able to patch native async functions\n return new Function(`let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];`)();\n } catch(e) {\n var P = _global.Promise;\n return P ?\n [P.resolve(), P.prototype, P.resolve()] :\n []; \n }\n })(),\n resolvedNativePromise = nativePromiseInstanceAndProto[0],\n nativePromiseProto = nativePromiseInstanceAndProto[1],\n resolvedGlobalPromise = nativePromiseInstanceAndProto[2],\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nexport const AsyncFunction = nativePromiseInstanceAndProto[3];\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => {resolvedGlobalPromise.then(physicalTick);}\n :\n _global.setImmediate ? \n // setImmediate supported. Those modern platforms also supports Function.bind().\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n // MutationObserver supported\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\n physicalTick();\n hiddenDiv = null;\n })).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n } :\n // No support for setImmediate or MutationObserver. No worry, setTimeout is only called\n // once time. Every tick that follows will be our emulated micro tick.\n // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \n ()=>{setTimeout(physicalTick,0);};\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(uh => {\n try {\n globalError(uh[0], uh[1]);\n } catch (e) {}\n });\n }\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n }\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n if (possibleAwait) decrementExpectedAwaits();\n var rv = new Promise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(Promise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n \n stack: {\n get: function() {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack (this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new Promise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(Promise.prototype, Symbol.toStringTag, 'Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (Promise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new Promise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => Promise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof Promise) return value;\n if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new Promise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new Promise((resolve, reject) => {\n values.map(value => Promise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n //totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new Promise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof Promise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n \n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\nfunction getStack (promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n \n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with setImmediate() or setTimeout().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new Promise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: Promise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: Promise, configurable: true, writable: true},\n all: Promise.all,\n race: Promise.race,\n resolve: Promise.resolve,\n reject: Promise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits(sourceTaskId) {\n if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) return;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction enqueueNativeMicroTask (job) {\n //\n // Precondition: nativePromiseThen !== undefined\n //\n nativePromiseThen.call(resolvedNativePromise, job);\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone, false),\n nativeAwaitCompatibleWrap(onRejected, zone, false));\n };\n}\n\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\n\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n } catch (e) {}\n if (rv !== false) try {\n var event, eventData = {promise: promise, reason: err};\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n } else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData});\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\n try {_global.onunhandledrejection(event);} catch (_) {}\n }\n if (!event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n } catch (e) {}\n}\n\nexport var rejection = Promise.reject;\n","import {keys, isArray, asap} from './utils';\nimport {nop, mirror, reverseStoppableEventChain} from './chaining-functions';\nimport {exceptions} from './errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","/*\n * Dexie.js - a minimalistic wrapper for IndexedDB\n * ===============================================\n *\n * Copyright (c) 2014-2017 David Fahlander\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n * \n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n * \n */\n\nimport {\n keys,\n setProp,\n isArray,\n extend,\n props,\n derive,\n slice,\n override,\n _global,\n asap,\n trycatcher,\n tryCatch,\n getByKeyPath,\n setByKeyPath,\n delByKeyPath,\n shallowClone,\n deepClone,\n getObjectDiff,\n assert,\n NO_CHAR_ARRAY,\n getArrayOf,\n arrayToObject,\n hasOwn,\n flatten\n} from './utils';\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\nimport Promise, {wrap, PSD, newScope, usePSD, rejection, NativePromise,\n incrementExpectedAwaits, decrementExpectedAwaits, AsyncFunction} from './Promise';\nimport Events from './Events';\nimport {\n nop,\n mirror,\n pureFunctionChain,\n hookCreatingChain,\n hookUpdatingChain,\n hookDeletingChain,\n promisableChain\n} from './chaining-functions';\nimport * as Debug from './debug';\n\nvar DEXIE_VERSION = '{version}',\n maxString = String.fromCharCode(65535),\n // maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\n // Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\n maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(),\n minKey = -Infinity,\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\n STRING_EXPECTED = \"String expected.\",\n connections = [],\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\n hasIEDeleteObjectStoreBug = isIEOrEdge,\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\n dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame),\n dbNamesDB;// Global database for backing Dexie.getDatabaseNames() on browser without indexedDB.webkitGetDatabaseNames() \n\n// Init debug\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default function Dexie(dbName, options) {\n /// Specify only if you wich to control which addons that should run on this instance\n var deps = Dexie.dependencies;\n var opts = extend({\n // Default Options\n addons: Dexie.addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to browser env.\n }, options);\n var addons = opts.addons,\n autoOpen = opts.autoOpen,\n indexedDB = opts.indexedDB,\n IDBKeyRange = opts.IDBKeyRange;\n\n var globalSchema = this._dbSchema = {};\n var versions = [];\n var dbStoreNames = [];\n var allTables = {};\n ///\n var idbdb = null; // Instance of IDBDatabase\n var dbOpenError = null;\n var isBeingOpened = false;\n var onReadyBeingFired = null;\n var openComplete = false;\n var READONLY = \"readonly\", READWRITE = \"readwrite\";\n var db = this;\n var dbReadyResolve,\n dbReadyPromise = new Promise(resolve => {\n dbReadyResolve = resolve;\n }),\n cancelOpen,\n openCanceller = new Promise((_, reject) => {\n cancelOpen = reject;\n });\n var autoSchema = true;\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\n hasGetAll;\n\n function init() {\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n db.on(\"versionchange\", function (ev) {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`);\n db.close();\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n db.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${db.name}') was blocked`);\n else\n console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`);\n });\n }\n\n //\n //\n //\n // ------------------------- Versioning Framework---------------------------\n //\n //\n //\n\n this.version = function (versionNumber) {\n /// \n /// \n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];\n if (versionInstance) return versionInstance;\n versionInstance = new Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n // Disable autoschema mode, as at least one version is specified.\n autoSchema = false;\n return versionInstance;\n };\n\n function Version(versionNumber) {\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n this.stores({}); // Derive earlier schemas by default.\n }\n\n extend(Version.prototype, {\n stores: function (stores) {\n /// \n /// Defines the schema for a particular version\n /// \n /// \n /// Example:
\n /// {users: \"id++,first,last,&username,*email\",
\n /// passwords: \"id++,&username\"}
\n ///
\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

\n /// Special characters:
\n /// \"&\" means unique key,
\n /// \"*\" means value is multiEntry,
\n /// \"++\" means auto-increment and only applicable for primary key
\n /// \n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n var storesSpec = {};\n versions.forEach(function (version) { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n });\n\n var dbschema = (this._cfg.dbschema = {});\n this._parseStoresSpec(storesSpec, dbschema);\n // Update the latest schema to this version\n // Update API\n globalSchema = db._dbSchema = dbschema;\n removeTablesApi([allTables, db, Transaction.prototype]); // Keep Transaction.prototype even though it should be depr.\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n dbStoreNames = keys(dbschema);\n return this;\n },\n upgrade: function (upgradeFunction) {\n /// Function that performs upgrading actions.\n var self = this;\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n },\n _parseStoresSpec: function (stores, outSchema) {\n keys(stores).forEach(function (tableName) {\n if (stores[tableName] !== null) {\n var instanceTemplate = {};\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\n indexes.forEach(function (idx) {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return \"\"; }) : \"\");\n });\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\n }\n });\n }\n });\n \n function runUpgraders (oldVersion, idbtrans, reject) {\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\n trans.create(idbtrans);\n trans._completion.catch(reject);\n var rejectTransaction = trans._reject.bind(trans);\n newScope(function () {\n PSD.trans = trans;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(function (tableName) {\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\n });\n }\n\n function updateTablesAndIndexes (oldVersion, trans, idbtrans) {\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n var queue = [];\n var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0];\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\n var anyContentUpgraderHasRun = false;\n\n var versToRun = versions.filter(v => v._cfg.version > oldVersion);\n versToRun.forEach(function (version) {\n /// \n queue.push(()=>{\n var oldSchema = globalSchema;\n var newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(oldSchema, idbtrans);\n adjustToExistingIndexNames(newSchema, idbtrans);\n globalSchema = db._dbSchema = newSchema;\n var diff = getSchemaDiff(oldSchema, newSchema); \n // Add tables \n diff.add.forEach(function (tuple) {\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(function (change) {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n var store = idbtrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(function (idx) {\n addIndex(store, idx);\n });\n // Update indexes\n change.change.forEach(function (idx) {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(function (idxName) {\n store.deleteIndex(idxName);\n });\n }\n });\n if (version._cfg.contentUpgrade) {\n anyContentUpgraderHasRun = true;\n return Promise.follow(()=>{\n version._cfg.contentUpgrade(trans);\n });\n }\n });\n queue.push(function (idbtrans) {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n var newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n });\n });\n\n // Now, create a queue execution engine\n function runQueue () {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n \n return runQueue().then(()=>{\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n }\n\n function getSchemaDiff(oldSchema, newSchema) {\n var diff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n for (var table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n var oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n var change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (oldDef.primKey.src !== newDef.primKey.src) {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n var oldIndexes = oldDef.idxByName;\n var newIndexes = newDef.idxByName;\n for (var idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n var oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n }\n\n function createTable(idbtrans, tableName, primKey, indexes) {\n /// \n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\n indexes.forEach(function (idx) { addIndex(store, idx); });\n return store;\n }\n\n function createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(function (tableName) {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n }\n\n function deleteRemovedTables(newSchema, idbtrans) {\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\n var storeName = idbtrans.db.objectStoreNames[i];\n if (newSchema[storeName] == null) {\n idbtrans.db.deleteObjectStore(storeName);\n }\n }\n }\n\n function addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n }\n\n //\n //\n // Dexie Protected API\n //\n //\n\n this._allTables = allTables;\n\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\n };\n\n /* Generate a temporary transaction when db operations are done outside a transaction scope.\n */\n function tempTransaction(mode, storeNames, fn) { // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n if (!openComplete && (!PSD.letThrough)) {\n if (!isBeingOpened) {\n if (!autoOpen)\n return rejection (new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, globalSchema);\n try { trans.create(); } catch (ex) { return rejection(ex); }\n return trans._promise(mode, function (resolve, reject) {\n return newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n return trans._completion.then(()=>result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n }\n\n this._whenReady = function (fn) {\n return openComplete || PSD.letThrough ? fn() : new Promise ((resolve, reject) => {\n if (!isBeingOpened) {\n if (!autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n dbReadyPromise.then(resolve, reject);\n }).then(fn);\n };\n \n //\n //\n //\n //\n // Dexie API\n //\n //\n //\n\n this.verno = 0;\n\n this.open = function () {\n if (isBeingOpened || idbdb)\n return dbReadyPromise.then(()=> dbOpenError ? rejection (dbOpenError) : db);\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n isBeingOpened = true;\n dbOpenError = null;\n openComplete = false;\n \n // Function pointers to call when the core opening process completes.\n var resolveDbReady = dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction = null;\n \n return Promise.race([openCanceller, new Promise((resolve, reject) => {\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n \n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI(\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n \n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(\"IndexedDB API not available\"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(fireOnBlocked);\n req.onupgradeneeded = wrap (function (e) {\n upgradeTransaction = req.transaction;\n if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(function () {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\n }\n }, reject);\n \n req.onsuccess = wrap (function () {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n idbdb = req.result;\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n\n if (autoSchema) readGlobalSchema();\n else if (idbdb.objectStoreNames.length > 0) {\n try {\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\n } catch (e) {\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n }\n }\n \n idbdb.onversionchange = wrap(ev => {\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n if (!hasNativeGetDatabaseNames && dbName !== '__dbnames') {\n dbNamesDB.dbnames.put({name: dbName}).catch(nop);\n }\n\n resolve();\n\n }, reject);\n })]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n onReadyBeingFired = [];\n return Promise.resolve(Dexie.vip(db.on.ready.fire)).then(function fireRemainders() {\n if (onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = onReadyBeingFired.reduce(promisableChain, nop);\n onReadyBeingFired = [];\n return Promise.resolve(Dexie.vip(remainders)).then(fireRemainders)\n }\n });\n }).finally(()=>{\n onReadyBeingFired = null;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n isBeingOpened = false;\n return db;\n }).catch(err => {\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch (e) { }\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection (dbOpenError);\n }).finally(()=>{\n openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n };\n \n this.close = function () {\n var idx = connections.indexOf(db);\n if (idx >= 0) connections.splice(idx, 1); \n if (idbdb) {\n try {idbdb.close();} catch(e){}\n idbdb = null;\n }\n autoOpen = false;\n dbOpenError = new exceptions.DatabaseClosed();\n if (isBeingOpened)\n cancelOpen(dbOpenError);\n // Reset dbReadyPromise promise:\n dbReadyPromise = new Promise(resolve => {\n dbReadyResolve = resolve;\n });\n openCanceller = new Promise((_, reject) => {\n cancelOpen = reject;\n });\n };\n \n this.delete = function () {\n var hasArguments = arguments.length > 0;\n return new Promise(function (resolve, reject) {\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (isBeingOpened) {\n dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n function doDelete() {\n db.close();\n var req = indexedDB.deleteDatabase(dbName);\n req.onsuccess = wrap(function () {\n if (!hasNativeGetDatabaseNames) {\n dbNamesDB.dbnames.delete(dbName).catch(nop);\n }\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = fireOnBlocked;\n }\n });\n };\n\n this.backendDB = function () {\n return idbdb;\n };\n\n this.isOpen = function () {\n return idbdb !== null;\n };\n this.hasBeenClosed = function () {\n return dbOpenError && (dbOpenError instanceof exceptions.DatabaseClosed);\n }\n this.hasFailed = function () {\n return dbOpenError !== null;\n };\n this.dynamicallyOpened = function() {\n return autoSchema;\n };\n\n //\n // Properties\n //\n this.name = dbName;\n\n // db.tables - an array of all Table instances.\n props(this, {\n tables: {\n get () {\n /// \n return keys(allTables).map(function (name) { return allTables[name]; });\n }\n }\n });\n\n //\n // Events\n //\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", {ready: [promisableChain, nop]});\n\n this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) {\n return (subscriber, bSticky) => {\n Dexie.vip(()=>{\n if (openComplete) {\n // Database already open. Call subscriber asap.\n if (!dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n this.transaction = function () {\n /// \n ///\n /// \n /// \"r\" for readonly, or \"rw\" for readwrite\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\n /// Function to execute with transaction\n\n var args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n \n function extractTransactionArgs (mode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i-1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n }\n\n this._transaction = function (mode, tables, scopeFunc) {\n var parentTransaction = PSD.trans;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\n var onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n \n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n var storeNames = tables.map(table => {\n var storeName = table instanceof Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode == READONLY)\n mode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n mode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(function (storeName) {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n return (parentTransaction ?\n parentTransaction._promise(mode, enterTransactionScope, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>db._whenReady(enterTransactionScope)) :\n db._whenReady (enterTransactionScope));\n \n function enterTransactionScope() {\n return Promise.resolve().then(()=>{\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n var transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n var zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\n }\n\n // Support for native async await.\n if (scopeFunc.constructor === AsyncFunction) {\n incrementExpectedAwaits();\n }\n\n var returnValue;\n var promiseFollowed = Promise.follow(()=>{\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (returnValue.constructor === NativePromise) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(()=>returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(()=>x);\n }).catch (e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n }\n };\n\n this.table = function (tableName) {\n /// \n if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return allTables[tableName];\n };\n\n //\n //\n //\n // Table Class\n //\n //\n //\n function Table(name, tableSchema, optionalTrans) {\n /// \n this.name = name;\n this.schema = tableSchema;\n this._tx = optionalTrans;\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n }\n\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n }\n\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\n return new Promise((resolve, reject)=>{\n var len = keysOrTuples.length,\n lastItem = len - 1;\n if (len === 0) return resolve();\n if (!hasDeleteHook) {\n for (var i=0; i < len; ++i) {\n var req = idbstore.delete(keysOrTuples[i]);\n req.onerror = eventRejectHandler(reject);\n if (i === lastItem) req.onsuccess = wrap(()=>resolve());\n }\n } else {\n var hookCtx,\n errorHandler = hookedEventRejectHandler(reject),\n successHandler = hookedEventSuccessHandler(null);\n tryCatch(()=> {\n for (var i = 0; i < len; ++i) {\n hookCtx = {onsuccess: null, onerror: null};\n var tuple = keysOrTuples[i];\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\n var req = idbstore.delete(tuple[0]);\n req._hookCtx = hookCtx;\n req.onerror = errorHandler;\n if (i === lastItem)\n req.onsuccess = hookedEventSuccessHandler(resolve);\n else\n req.onsuccess = successHandler;\n }\n }, err=>{\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n }\n });\n } \n\n props(Table.prototype, {\n\n //\n // Table Protected Methods\n //\n\n _trans: function getTransaction(mode, fn, writeLocked) {\n var trans = this._tx || PSD.trans;\n return trans && trans.db === db ?\n trans === PSD.trans ?\n trans._promise (mode, fn, writeLocked) :\n newScope(()=>trans._promise(mode, fn, writeLocked), {trans: trans, transless: PSD.transless || PSD}) :\n tempTransaction (mode, [this.name], fn);\n },\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\n var tableName = this.name;\n function supplyIdbStore (resolve, reject, trans) {\n if (trans.storeNames.indexOf(tableName) === -1)\n throw new exceptions.NotFound(\"Table\" + tableName + \" not part of transaction\");\n return fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\n }\n return this._trans(mode, supplyIdbStore, writeLocked);\n },\n\n //\n // Table Public Methods\n //\n get: function (keyOrCrit, cb) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit).first(cb);\n var self = this;\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\n var req = idbstore.get(keyOrCrit);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(self.hook.reading.fire(req.result));\n }, reject);\n }).then(cb);\n },\n where: function (indexOrCrit) {\n if (typeof indexOrCrit === 'string')\n return new WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n var keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n \n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix =>\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n ix.keyPath.every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n\n if (compoundIndex && maxKey !== maxString)\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n return this\n .where(compoundIndex.name)\n .equals(compoundIndex.keyPath.map(kp => indexOrCrit[kp]));\n\n if (!compoundIndex) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n \n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n var idxByName = this.schema.idxByName;\n var simpleIndex = keyPaths.reduce((r,keyPath)=>[\n r[0] || idxByName[keyPath],\n r[0] || !idxByName[keyPath] ?\n combine(\n r[1],\n x =>''+getByKeyPath(x, keyPath) ==\n ''+indexOrCrit[keyPath])\n : r[1]\n ], [null, null]);\n \n var idx = simpleIndex[0];\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(simpleIndex[1]) :\n compoundIndex ?\n this.filter(simpleIndex[1]) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily.\n },\n count: function (cb) {\n return this.toCollection().count(cb);\n },\n offset: function (offset) {\n return this.toCollection().offset(offset);\n },\n limit: function (numRows) {\n return this.toCollection().limit(numRows);\n },\n reverse: function () {\n return this.toCollection().reverse();\n },\n filter: function (filterFunction) {\n return this.toCollection().and(filterFunction);\n },\n each: function (fn) {\n return this.toCollection().each(fn);\n },\n toArray: function (cb) {\n return this.toCollection().toArray(cb);\n },\n orderBy: function (index) {\n return new Collection(\n new WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n },\n\n toCollection: function () {\n return new Collection(new WhereClause(this));\n },\n\n mapToClass: function (constructor, structure) {\n /// \n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\n /// \n /// Constructor function representing the class.\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\n this.schema.mappedClass = constructor;\n var instanceTemplate = Object.create(constructor.prototype);\n if (structure) {\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\n applyStructure(instanceTemplate, structure);\n }\n this.schema.instanceTemplate = instanceTemplate;\n\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n var readHook = function (obj) {\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\n // Create a new object that derives from constructor:\n var res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){}\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n },\n defineClass: function (structure) {\n /// \n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\n /// as well as making it possible to extend the prototype of the returned constructor function.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n return this.mapToClass(Dexie.defineClass(structure), structure);\n },\n\n bulkDelete: function (keys) {\n if (this.hook.deleting.fire === nop) {\n return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => {\n resolve (bulkDelete(idbstore, trans, keys, false, nop));\n });\n } else {\n return this\n .where(':id')\n .anyOf(keys)\n .delete()\n .then(()=>{}); // Resolve with undefined.\n }\n },\n bulkPut: function(objects, keys) {\n return this._idbstore(READWRITE, (resolve, reject, idbstore) => {\n if (!idbstore.keyPath && !this.schema.primKey.auto && !keys)\n throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n const done = result => {\n if (errorList.length === 0) resolve(result);\n else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList));\n };\n var req,\n errorList = [],\n errorHandler,\n numObjs = objects.length,\n table = this;\n if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) {\n //\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n } else {\n var effectiveKeys = keys || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath));\n // Generate map of {[key]: object}\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); \n var promise = !effectiveKeys ?\n\n // Auto-incremented key-less objects only without any keys argument.\n table.bulkAdd(objects) :\n\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\n // Begin with updating those that exists in DB:\n table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () {\n this.value = objectLookup[this.primKey];\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\n }).catch(ModifyError, e => {\n errorList = e.failures; // No need to concat here. These are the first errors added.\n }).then(()=> {\n // Now, let's examine which items didnt exist so we can add them:\n var objsToAdd = [],\n keysToAdd = keys && [];\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\n for (var i=effectiveKeys.length-1; i>=0; --i) {\n var key = effectiveKeys[i];\n if (key == null || objectLookup[key]) {\n objsToAdd.push(objects[i]);\n keys && keysToAdd.push(key);\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\n }\n }\n // The items are in reverse order so reverse them before adding.\n // Could be important in order to get auto-incremented keys the way the caller\n // would expect. Could have used unshift instead of push()/reverse(),\n // but: http://jsperf.com/unshift-vs-reverse\n objsToAdd.reverse();\n keys && keysToAdd.reverse();\n return table.bulkAdd(objsToAdd, keysToAdd);\n }).then(lastAddedKey => {\n // Resolve with key of the last object in given arguments to bulkPut():\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\n });\n\n promise.then(done).catch(BulkError, e => {\n // Concat failure from ModifyError and reject using our 'done' method.\n errorList = errorList.concat(e.failures);\n done();\n }).catch(reject);\n }\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\n },\n bulkAdd: function(objects, keys) {\n var self = this,\n creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys)\n throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n function done(result) {\n if (errorList.length === 0) resolve(result);\n else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList));\n }\n var req,\n errorList = [],\n errorHandler,\n successHandler,\n numObjs = objects.length;\n if (creatingHook !== nop) {\n //\n // There are subscribers to hook('creating')\n // Must behave as documented.\n //\n var keyPath = idbstore.keyPath,\n hookCtx;\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\n successHandler = hookedEventSuccessHandler(null);\n\n tryCatch(() => {\n for (var i=0, l = objects.length; i < l; ++i) {\n hookCtx = { onerror: null, onsuccess: null };\n var key = keys && keys[i];\n var obj = objects[i],\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\n if (effectiveKey == null && keyToUse != null) {\n if (keyPath) {\n obj = deepClone(obj);\n setByKeyPath(obj, keyPath, keyToUse);\n } else {\n key = keyToUse;\n }\n }\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n if (i < l - 1) {\n req.onerror = errorHandler;\n if (hookCtx.onsuccess)\n req.onsuccess = successHandler;\n }\n }\n }, err => {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\n req.onsuccess = hookedEventSuccessHandler(done);\n } else {\n //\n // Standard Bulk (no 'creating' hook to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n }\n });\n },\n add: function (obj, key) {\n /// \n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\n /// \n /// A javascript object to insert\n /// Primary key\n var creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n var hookCtx = {onsuccess: null, onerror: null};\n if (creatingHook !== nop) {\n var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined);\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\n if (effectiveKey == null && keyToUse != null) { // Using \"==\" and \"!=\" to check for either null or undefined!\n if (idbstore.keyPath)\n setByKeyPath(obj, idbstore.keyPath, keyToUse);\n else\n key = keyToUse;\n }\n }\n try {\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n req.onerror = hookedEventRejectHandler(reject);\n req.onsuccess = hookedEventSuccessHandler(function (result) {\n // TODO: Remove these two lines in next major release (2.0?)\n // It's no good practice to have side effects on provided parameters\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, result);\n resolve(result);\n });\n } catch (e) {\n if (hookCtx.onerror) hookCtx.onerror(e);\n throw e;\n }\n });\n },\n\n put: function (obj, key) {\n /// \n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\n /// \n /// A javascript object to insert or update\n /// Primary key\n var creatingHook = this.hook.creating.fire,\n updatingHook = this.hook.updating.fire;\n if (creatingHook !== nop || updatingHook !== nop) {\n //\n // People listens to when(\"creating\") or when(\"updating\") events!\n // We must know whether the put operation results in an CREATE or UPDATE.\n //\n var keyPath = this.schema.primKey.keyPath;\n var effectiveKey = (key !== undefined) ? key : (keyPath && getByKeyPath(obj, keyPath));\n if (effectiveKey == null) // \"== null\" means checking for either null or undefined.\n return this.add(obj);\n \n // Since key is optional, make sure we get it from obj if not provided\n \n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\n // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.\n obj = deepClone(obj);\n return this._trans(READWRITE, () =>\n this.where(\":id\").equals(effectiveKey).modify(function () {\n // Replace extisting value with our object\n // CRUD event firing handled in Collection.modify()\n this.value = obj;\n }).then(count => count === 0 ? this.add(obj, key) : effectiveKey),\n \"locked\"); // Lock needed because operation is splitted into modify() and add().\n } else {\n // Use the standard IDB put() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function (ev) {\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\n resolve(req.result);\n });\n });\n }\n },\n\n 'delete': function (key) {\n /// Primary key of the object to delete\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\n // call the CRUD event. Only Collection.delete() will know whether an object was actually deleted.\n return this.where(\":id\").equals(key).delete();\n } else {\n // No one listens. Use standard IDB delete() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.delete(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(req.result);\n });\n });\n }\n },\n\n clear: function () {\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\n // call the CRUD event. Only Collection.delete() will knows which objects that are actually deleted.\n return this.toCollection().delete();\n } else {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.clear();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(req.result);\n });\n });\n }\n },\n\n update: function (keyOrObject, modifications) {\n if (typeof modifications !== 'object' || isArray(modifications))\n throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n // object to modify. Also modify given object with the modifications:\n keys(modifications).forEach(function (keyPath) {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection (new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n });\n \n //\n //\n //\n // Transaction Class\n //\n //\n //\n function Transaction(mode, storeNames, dbschema, parent) {\n /// \n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\n /// \n /// Any of \"readwrite\" or \"readonly\"\n /// Array of table names to operate on\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n }\n\n props(Transaction.prototype, {\n //\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n _lock: function () {\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n },\n _unlock: function () {\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n },\n _locked: function () {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n },\n create: function (idbtrans) {\n if (!this.mode) return this;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n });\n return this;\n },\n _promise: function (mode, fn, bWriteLock) {\n\n if (mode === READWRITE && this.mode !== READWRITE)\n return rejection (new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection (new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new Promise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(()=>{\n var p = new Promise((resolve, reject) => {\n this._lock();\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(()=>this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new Promise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n },\n\n _root: function () {\n return this.parent ? this.parent._root() : this;\n },\n\n waitFor (promise) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n promise = Promise.resolve(promise);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(()=>promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin(){\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new Promise ((resolve, reject) => {\n promise.then (\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n },\n\n //\n // Transaction Public Properties and Methods\n //\n abort: function () {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n },\n\n tables: {\n get: Debug.deprecated (\"Transaction.tables\", ()=>allTables)\n },\n\n table: function (name) {\n var table = db.table(name); // Don't check that table is part of transaction. It must fail lazily!\n return new Table(name, table.schema, this);\n }\n });\n\n //\n //\n //\n // WhereClause\n //\n //\n //\n function WhereClause(table, index, orCollection) {\n /// \n /// \n /// \n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n }\n\n props(WhereClause.prototype, function () {\n\n // WhereClause private methods\n\n function fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n }\n\n function emptyCollection(whereClause) {\n return new Collection (whereClause, function() { return IDBKeyRange.only(\"\"); }).limit(0);\n }\n\n function upperFactory(dir) {\n return dir === \"next\" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); };\n }\n function lowerFactory(dir) {\n return dir === \"next\" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); };\n }\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n }\n\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new Collection (whereClause, function() {\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix);\n });\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n }\n\n //\n // WhereClause public methods\n //\n return {\n between: function (lower, upper, includeLower, includeUpper) {\n /// \n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\n /// \n /// \n /// \n /// Whether items that equals lower should be included. Default true.\n /// Whether items that equals upper should be included. Default false.\n /// \n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((cmp(lower, upper) > 0) ||\n (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new Collection (this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); });\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n },\n equals: function (value) {\n return new Collection (this, function() { return IDBKeyRange.only(value); });\n },\n above: function (value) {\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value, true); });\n },\n aboveOrEqual: function (value) {\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value); });\n },\n below: function (value) {\n return new Collection (this, function() { return IDBKeyRange.upperBound(value, true); });\n },\n belowOrEqual: function (value) {\n return new Collection (this, function() { return IDBKeyRange.upperBound(value); });\n },\n startsWith: function (str) {\n /// \n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n },\n startsWithIgnoreCase: function (str) {\n /// \n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString);\n },\n equalsIgnoreCase: function (str) {\n /// \n return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], \"\");\n },\n anyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, \"\");\n },\n startsWithAnyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.some(function(n){\n return x.indexOf(n) === 0;\n });}, set, maxString);\n },\n anyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n var compare = ascending;\n try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n var c = new Collection (this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); });\n\n c._ondirectionchange = function (direction) {\n compare = (direction === \"next\" ? ascending : descending);\n set.sort(compare);\n };\n var i = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n },\n\n notEqual: function(value) {\n return this.inAnyRange([[minKey, value],[value, maxKey]], {includeLowers: false, includeUppers: false});\n },\n\n noneOf: function() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new Collection (this); // Return entire collection.\n try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);}\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; }, null);\n ranges.push([set[set.length - 1], maxKey]);\n return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false});\n },\n\n /** Filter out values withing given set of ranges.\n * Example, give children and elders a rebate of 50%:\n *\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\n *\n * @param {(string|number|Date|Array)[][]} ranges\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\n */\n inAnyRange: function (ranges, options) {\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n var includeLowers = !options || options.includeLowers !== false; // Default to true\n var includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange (ranges, newRange) {\n for (var i=0,l=ranges.length;i 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n var sortDirection = ascending;\n function rangeSorter(a,b) { return sortDirection(a[0], b[0]);}\n\n // Join overlapping ranges\n var set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch(ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n var i = 0;\n var keyIsBeyondCurrentEntry = includeUppers ?\n function(key) { return ascending(key, set[i][1]) > 0; } :\n function(key) { return ascending(key, set[i][1]) >= 0; };\n\n var keyIsBeforeCurrentEntry = includeLowers ?\n function(key) { return descending(key, set[i][0]) > 0; } :\n function(key) { return descending(key, set[i][0]) >= 0; };\n\n function keyWithinCurrentRange (key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n var checkKey = keyIsBeyondCurrentEntry;\n\n var c = new Collection (this, function () {\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\n });\n\n c._ondirectionchange = function (direction) {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function() {\n if (sortDirection === ascending) cursor.continue(set[i][0]);\n else cursor.continue(set[i][1]);\n });\n return false;\n }\n });\n return c;\n },\n startsWithAnyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(function (s) { return typeof s === 'string'; })) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map(function(str) {\n return [str, str + maxString];\n }));\n }\n };\n });\n\n\n\n\n //\n //\n //\n // Collection Class\n //\n //\n //\n function Collection(whereClause, keyRangeGenerator) {\n /// \n ///\n /// \n /// Where clause instance\n /// \n var keyRange = null, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n var whereCtx = whereClause._ctx,\n table = whereCtx.table;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: table.hook.reading.fire\n };\n }\n \n function isPlainKeyRange (ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n } \n\n props(Collection.prototype, function () {\n\n //\n // Collection Private Functions\n //\n\n function addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n }\n\n function addReplayFilter (ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n }\n\n function addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n }\n\n /** @param ctx {\n * isPrimKey: boolean,\n * table: Table,\n * index: string\n * }\n * @param store IDBObjectStore\n **/\n function getIndexOrStore(ctx, store) {\n if (ctx.isPrimKey) return store;\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\n return store.index(indexSpec.name);\n }\n\n /** @param ctx {\n * isPrimKey: boolean,\n * table: Table,\n * index: string,\n * keysOnly: boolean,\n * range?: IDBKeyRange,\n * dir: \"next\" | \"prev\"\n * }\n */\n function openCursor(ctx, store) {\n var idxOrStore = getIndexOrStore(ctx, store);\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ?\n idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) :\n idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\n }\n\n function iter(ctx, fn, resolve, reject, idbstore) {\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\n } else (()=>{\n var set = {};\n var resolved = 0;\n\n function resolveboth() {\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\n }\n\n function union(item, cursor, advance) {\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n ctx.or._iterate(union, resolveboth, reject, idbstore);\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\n })();\n }\n function getInstanceTemplate(ctx) {\n return ctx.table.schema.instanceTemplate;\n }\n \n return {\n\n //\n // Collection Protected Functions\n //\n\n _read: function (fn, cb) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._idbstore(READONLY, fn).then(cb);\n },\n _write: function (fn) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n },\n _addAlgorithm: function (fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n },\n\n _iterate: function (fn, resolve, reject, idbstore) {\n return iter(this._ctx, fn, resolve, reject, idbstore);\n },\n\n clone: function (props) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n },\n\n raw: function () {\n this._ctx.valueMapper = null;\n return this;\n },\n\n //\n // Collection Public methods\n //\n\n each: function (fn) {\n var ctx = this._ctx;\n\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, fn, resolve, reject, idbstore);\n });\n },\n\n count: function (cb) {\n var ctx = this._ctx;\n\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return this._read(function (resolve, reject, idbstore) {\n var idx = getIndexOrStore(ctx, idbstore);\n var req = (ctx.range ? idx.count(ctx.range) : idx.count());\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (e) {\n resolve(Math.min(e.target.result, ctx.limit));\n };\n }, cb);\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore);\n }, cb);\n }\n },\n\n sortBy: function (keyPath, cb) {\n /// \n var parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n },\n\n toArray: function (cb) {\n var ctx = this._ctx;\n return this._read(function (resolve, reject, idbstore) {\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n var readingHook = ctx.table.hook.reading.fire;\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ?\n idxOrStore.getAll(ctx.range, ctx.limit) :\n idxOrStore.getAll(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = readingHook === mirror ?\n eventSuccessHandler(resolve) :\n eventSuccessHandler(res => {\n try {resolve (res.map(readingHook));} catch(e) {reject(e);}\n });\n } else {\n // Getting array through a cursor.\n var a = [];\n iter(ctx, function (item) { a.push(item); }, function arrayComplete() {\n resolve(a);\n }, reject, idbstore);\n }\n }, cb);\n },\n\n offset: function (offset) {\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, ()=> {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(()=> {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, ()=> {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n },\n\n limit: function (numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, ()=> {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n },\n\n until: function (filterFunction, bIncludeStopEntry) {\n var ctx = this._ctx;\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n },\n\n first: function (cb) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n },\n\n last: function (cb) {\n return this.reverse().first(cb);\n },\n\n filter: function (filterFunction) {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction); \n return this;\n },\n \n and: function (filterFunction) {\n return this.filter(filterFunction);\n },\n\n or: function (indexName) {\n return new WhereClause(this._ctx.table, indexName, this);\n },\n\n reverse: function () {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n },\n\n desc: function () {\n return this.reverse();\n },\n\n eachKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n },\n\n eachUniqueKey: function (cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n },\n \n eachPrimaryKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n },\n\n keys: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n },\n \n primaryKeys: function (cb) {\n var ctx = this._ctx;\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read((resolve, reject, idbstore) =>{\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ?\n idxOrStore.getAllKeys(ctx.range, ctx.limit) :\n idxOrStore.getAllKeys(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = eventSuccessHandler(resolve);\n }).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n uniqueKeys: function (cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n },\n\n firstKey: function (cb) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n },\n\n lastKey: function (cb) {\n return this.reverse().firstKey(cb);\n },\n\n distinct: function () {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n },\n\n //\n // Methods that mutate storage\n //\n\n modify: function (changes) {\n var self = this,\n ctx = this._ctx,\n hook = ctx.table.hook,\n updatingHook = hook.updating.fire,\n deletingHook = hook.deleting.fire;\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var modifyer;\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n if (updatingHook === nop && deletingHook === nop) {\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\n modifyer = changes;\n } else {\n // People want to know exactly what is being modified or deleted.\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\n // and call the hooks accordingly!\n modifyer = function (item) {\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\n if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)\n if (!hasOwn(this, \"value\")) {\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\n deletingHook.call(this, this.primKey, item, trans);\n } else {\n // No deletion. Check what was changed\n var objectDiff = getObjectDiff(origItem, this.value);\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\n if (additionalChanges) {\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\n item = this.value;\n keys(additionalChanges).forEach(function (keyPath) {\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n });\n }\n }\n };\n }\n } else if (updatingHook === nop) {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n } else {\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\n // allow it to add additional modifications to make.\n var origChanges = changes;\n changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.\n modifyer = function (item) {\n var anythingModified = false;\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\n if (additionalChanges) extend(changes, additionalChanges);\n keys(changes).forEach(function (keyPath) {\n var val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n });\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\n return anythingModified;\n };\n }\n\n var count = 0;\n var successCount = 0;\n var iterationComplete = false;\n var failures = [];\n var failKeys = [];\n var currentKey = null;\n\n function modifyItem(item, cursor) {\n currentKey = cursor.primaryKey;\n var thisContext = {\n primKey: cursor.primaryKey,\n value: item,\n onsuccess: null,\n onerror: null\n };\n\n function onerror(e) {\n failures.push(e);\n failKeys.push(thisContext.primKey);\n checkFinished();\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\n }\n\n if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update!\n var bDelete = !hasOwn(thisContext, \"value\");\n ++count;\n tryCatch(function () {\n var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value));\n req._hookCtx = thisContext;\n req.onerror = hookedEventRejectHandler(onerror);\n req.onsuccess = hookedEventSuccessHandler(function () {\n ++successCount;\n checkFinished();\n });\n }, onerror);\n } else if (thisContext.onsuccess) {\n // Hook will expect either onerror or onsuccess to always be called!\n thisContext.onsuccess(thisContext.value);\n }\n }\n\n function doReject(e) {\n if (e) {\n failures.push(e);\n failKeys.push(currentKey);\n }\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\n }\n\n function checkFinished() {\n if (iterationComplete && successCount + failures.length === count) {\n if (failures.length > 0)\n doReject();\n else\n resolve(successCount);\n }\n }\n self.clone().raw()._iterate(modifyItem, function () {\n iterationComplete = true;\n checkFinished();\n }, doReject, idbstore);\n });\n },\n\n 'delete': function () {\n var ctx = this._ctx,\n range = ctx.range,\n deletingHook = ctx.table.hook.deleting.fire,\n hasDeleteHook = deletingHook !== nop;\n if (!hasDeleteHook &&\n isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write((resolve, reject, idbstore) => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n var onerror = eventRejectHandler(reject),\n countReq = (range ? idbstore.count(range) : idbstore.count());\n countReq.onerror = onerror;\n countReq.onsuccess = () => {\n var count = countReq.result;\n tryCatch(()=> {\n var delReq = (range ? idbstore.delete(range) : idbstore.clear());\n delReq.onerror = onerror;\n delReq.onsuccess = () => resolve(count);\n }, err => reject(err));\n };\n });\n }\n\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\n // Divide into chunks to not starve RAM.\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\n // more memory and need lower chunk size.\n const CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\n\n return this._write((resolve, reject, idbstore, trans) => {\n var totalCount = 0;\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\n var collection = this\n .clone({\n keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers)\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\n // would become larger than actual delete count.\n .limit(CHUNKSIZE)\n .raw(); // Don't filter through reading-hooks (like mapped classes etc)\n\n var keysOrTuples = [];\n\n // We're gonna do things on as many chunks that are needed.\n // Use recursion of nextChunk function:\n const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => {\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\n // so that the hook can be called with its values in bulkDelete().\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\n } : (val, cursor) => {\n // No one subscribes to hook('deleting'). Collect only primary keys:\n keysOrTuples.push(cursor.primaryKey);\n }).then(() => {\n // Chromium deletes faster when doing it in sort order.\n hasDeleteHook ?\n keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) :\n keysOrTuples.sort(ascending);\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\n\n }).then(()=> {\n var count = keysOrTuples.length;\n totalCount += count;\n keysOrTuples = [];\n return count < CHUNKSIZE ? totalCount : nextChunk();\n });\n\n resolve (nextChunk());\n });\n }\n };\n });\n\n\n //\n //\n //\n // ------------------------- Help functions ---------------------------\n //\n //\n //\n\n function lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n }\n\n function setApiOnPlace(objs, tableNames, dbschema) {\n tableNames.forEach(function (tableName) {\n var schema = dbschema[tableName];\n objs.forEach(obj => {\n if (!(tableName in obj)) {\n if (obj === Transaction.prototype || obj instanceof Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {get() { return this.table(tableName); }});\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new Table(tableName, schema);\n }\n }\n });\n });\n }\n\n function removeTablesApi(objs) {\n objs.forEach(function (obj) {\n for (var key in obj) {\n if (obj[key] instanceof Table) delete obj[key];\n }\n });\n }\n\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn, reject);\n \n if (!req.onerror) req.onerror = eventRejectHandler(reject);\n if (filter) {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () { cursor.continue(); };\n if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject))\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\n c();\n } else {\n resolve();\n }\n }, reject);\n } else {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () { cursor.continue(); };\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\n c();\n } else {\n resolve();\n }\n }, reject);\n }\n }\n\n function parseIndexSyntax(indexes) {\n /// \n /// \n var rv = [];\n indexes.split(',').forEach(function (index) {\n index = index.trim();\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n rv.push(new IndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n /\\./.test(index)\n ));\n });\n return rv;\n }\n\n function cmp(key1, key2) {\n return indexedDB.cmp(key1, key2);\n }\n\n function min(a, b) {\n return cmp(a, b) < 0 ? a : b;\n }\n\n function max(a, b) {\n return cmp(a, b) > 0 ? a : b;\n }\n\n function ascending(a,b) {\n return indexedDB.cmp(a,b);\n }\n\n function descending(a, b) {\n return indexedDB.cmp(b,a);\n }\n\n function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n }\n\n function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n }\n\n function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n }\n\n function readGlobalSchema() {\n db.verno = idbdb.version / 10;\n db._dbSchema = globalSchema = {};\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\n if (dbStoreNames.length === 0) return; // Database contains no stores.\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\n dbStoreNames.forEach(function (storeName) {\n var store = trans.objectStore(storeName),\n keyPath = store.keyPath,\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\n var indexes = [];\n for (var j = 0; j < store.indexNames.length; ++j) {\n var idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\n indexes.push(index);\n }\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\n });\n setApiOnPlace([allTables], keys(globalSchema), globalSchema);\n }\n\n function adjustToExistingIndexNames(schema, idbtrans) {\n /// \n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n /// \n /// Map between name and TableSchema\n /// \n var storeNames = idbtrans.db.objectStoreNames;\n\n for (var i = 0; i < storeNames.length; ++i) {\n var storeName = storeNames[i];\n var store = idbtrans.objectStore(storeName);\n hasGetAll = 'getAll' in store;\n \n for (var j = 0; j < store.indexNames.length; ++j) {\n var indexName = store.indexNames[j];\n var keyPath = store.index(indexName).keyPath;\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n var indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) indexSpec.name = indexName;\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (/Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n hasGetAll = false;\n } \n }\n\n function fireOnBlocked(ev) {\n db.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c=>c.name === db.name && c !== db && !c._vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n extend(this, {\n Collection: Collection,\n Table: Table,\n Transaction: Transaction,\n Version: Version,\n WhereClause: WhereClause\n });\n\n init();\n\n addons.forEach(function (fn) {\n fn(db);\n });\n}\n\nfunction parseType(type) {\n if (typeof type === 'function') {\n return new type();\n } else if (isArray(type)) {\n return [parseType(type[0])];\n } else if (type && typeof type === 'object') {\n var rv = {};\n applyStructure(rv, type);\n return rv;\n } else {\n return type;\n }\n}\n\nfunction applyStructure(obj, structure) {\n keys(structure).forEach(function (member) {\n var value = parseType(structure[member]);\n obj[member] = value;\n });\n return obj;\n}\n\nfunction hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\nfunction eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nfunction eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nfunction hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nfunction preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nfunction awaitIterator (iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext) {\n return val => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n\n//\n// IndexSpec struct\n//\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n this.name = name;\n this.keyPath = keyPath;\n this.unique = unique;\n this.multi = multi;\n this.auto = auto;\n this.compound = compound;\n this.dotted = dotted;\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']');\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\n}\n\n//\n// TableSchema struct\n//\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\n /// \n /// \n /// \n /// \n this.name = name;\n this.primKey = primKey || new IndexSpec();\n this.indexes = indexes || [new IndexSpec()];\n this.instanceTemplate = instanceTemplate;\n this.mappedClass = null;\n this.idxByName = arrayToObject(indexes, index => [index.name, index]);\n}\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\n// Export Error classes\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\n\n//\n// Static methods and properties\n// \nprops(Dexie, {\n \n //\n // Static delete() method.\n //\n delete: function (databaseName) {\n var db = new Dexie(databaseName),\n promise = db.delete();\n promise.onblocked = function (fn) {\n db.on(\"blocked\", fn);\n return this;\n };\n return promise;\n },\n \n //\n // Static exists() method.\n //\n exists: function(name) {\n return new Dexie(name).open().then(db=>{\n db.close();\n return true;\n }).catch(Dexie.NoSuchDatabaseError, () => false);\n },\n \n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames: function (cb) {\n var getDatabaseNames = getNativeGetDatabaseNamesFn(Dexie.dependencies.indexedDB);\n return getDatabaseNames ? new Promise((resolve, reject) => {\n var req = getDatabaseNames();\n req.onsuccess = function (event) {\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\n };\n req.onerror = eventRejectHandler(reject);\n }).then(cb) : dbNamesDB.dbnames.toCollection().primaryKeys(cb);\n },\n \n defineClass: function (structure) {\n /// \n /// Create a javascript constructor based on given template for which properties to expect in the class.\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n\n // Default constructor able to copy given properties into this object.\n function Class(properties) {\n /// Properties to initialize object with.\n /// \n if (properties) extend(this, properties);\n }\n return Class;\n },\n \n applyStructure: applyStructure,\n \n ignoreTransaction: function (scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n \n vip: function (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n },\n\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection (e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n \n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n var promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ? Dexie.ignoreTransaction(promiseOrFunction) : promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ? PSD.trans.waitFor(promise) : promise;\n },\n \n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n \n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter);\n }\n },\n \n // Export our derive/extend/override methodology\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n asap: asap,\n maxKey: maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n \n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\n errnames: errnames,\n \n // Export other static classes\n IndexSpec: IndexSpec,\n TableSchema: TableSchema,\n \n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n },\n \n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p,c,i) => p + (c/Math.pow(10,i*2))),\n \n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n default: Dexie,\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n Dexie: Dexie\n});\n\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\nPromise.rejectionMapper = mapError;\n\n// Initialize dbNamesDB (won't ever be opened on chromium browsers')\ndbNamesDB = new Dexie('__dbnames'); \ndbNamesDB.version(1).stores({dbnames: 'name'});\n\n(()=>{\n // Migrate from Dexie 1.x database names stored in localStorage:\n var DBNAMES = 'Dexie.DatabaseNames';\n if (typeof localStorage !== undefined && _global.document !== undefined) try {\n // Have localStorage and is not executing in a worker. Lets migrate from Dexie 1.x.\n JSON.parse(localStorage.getItem(DBNAMES) || \"[]\")\n .forEach(name => dbNamesDB.dbnames.put({name: name}).catch(nop));\n localStorage.removeItem(DBNAMES);\n } catch (_e) {}\n})();\n"],"names":["asap","props","Debug.setDebug","Debug.debug","Debug.getErrorWithStack","keys","Debug.deprecated"],"mappings":";;;;;;;;;;;;;;;;;;;AAAO,IAAI,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AAC9B,AAAO,IAAI,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AACnC,AAAO,IAAI,OAAO,GACd,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI;IAClC,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM;QACtC,MAAM,CAAC;AAEX,gBAAuB,GAAG,EAAE,SAAS;IACjC,IAAI,OAAO,SAAS,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAC9C,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,UAAU,GAAG;QACjC,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;KAC7B,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;CACd;AAED,AAAO,IAAM,QAAQ,GAAG,MAAM,CAAC,cAAc,CAAC;AAC9C,AAAO,IAAM,OAAO,GAAG,EAAE,CAAC,cAAc,CAAC;AACzC,gBAAuB,GAAG,EAAE,IAAI;IAC5B,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;CAClC;AAED,eAAuB,KAAK,EAAE,SAAS;IACnC,IAAI,OAAO,SAAS,KAAK,UAAU;QAAE,SAAS,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;IAC5E,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,UAAA,GAAG;QACvB,OAAO,CAAC,KAAK,EAAE,GAAG,EA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AC,GAAA,CAAC;SACrB,MAAM,CAAC,UAAC,CAAC,EAAC,CAAC,EAAC,CAAC,IAAK,OAAA,CAAC,IAAI,CAAC,GAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAC,CAAC,GAAC,CAAC,CAAC,CAAC,GAAA,CAAC;;;;IAKhD,OAAO,EAAE,KAAK;;;;;;IAMd,KAAK,EAAE,KAAK;CACf,CAAC,CAAC;;AAGH,OAAO,CAAC,eAAe,GAAG,QAAQ,CAAC;;AAGnC,SAAS,GAAG,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC;AACnC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAC,OAAO,EAAE,MAAM,EAAC,CAAC,CAAC;AAE/C,CAAC;;IAEG,IAAI,OAAO,GAAG,qBAAqB,CAAC;IACpC,IAAI,OAAO,YAAY,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,KAAK,SAAS;QAAE,IAAI;;YAEzE,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC;iBAC5C,OAAO,CAAC,UAAA,IAAI,IAAI,OAAA,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,EAAC,IAAI,EAAE,IAAI,EAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,GAAA,CAAC,CAAC;YACrE,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;SACpC;QAAC,OAAO,EAAE,EAAE,GAAE;CAClB,GAAG,CAAC;;;;"} \ No newline at end of file diff --git a/dist/dexie.min.js b/dist/dexie.min.js new file mode 100644 index 000000000..84a32c1df --- /dev/null +++ b/dist/dexie.min.js @@ -0,0 +1,3 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):n.Dexie=t()}(this,function(){"use strict";function n(n,t){return"object"!=typeof t?n:(In(t).forEach(function(e){n[e]=t[e]}),n)}function t(n,t){return Fn.call(n,t)}function e(n,t){"function"==typeof t&&(t=t(Tn(n))),In(t).forEach(function(e){r(n,e,t[e])})}function r(e,r,i,o){Bn(e,r,n(i&&t(i,"get")&&"function"==typeof i.get?{get:i.get,set:i.set,configurable:!0}:{value:i,configurable:!0,writable:!0},o))}function i(n){return{from:function(t){return n.prototype=Object.create(t.prototype),r(n.prototype,"constructor",n),{extend:e.bind(null,n.prototype)}}}}function o(n,t){var e,r=Nn(n,t);return r||(e=Tn(n))&&o(e,t)}function u(n,t,e){return Mn.call(n,t,e)}function a(n,t){return t(n)}function c(n){if(!n)throw new Error("Assertion Failed")}function s(n){Kn.setImmediate?setImmediate(n):setTimeout(n,0)}function f(n,t){return n.reduce(function(n,e,r){var i=t(e,r);return i&&(n[i[0]]=i[1]),n},{})}function l(n,t){return function(){try{n.apply(this,arguments)}catch(n){t(n)}}}function h(n,t,e){try{n.apply(null,e)}catch(n){t&&t(n)}}function d(n,e){if(t(n,e))return n[e];if(!e)return n;if("string"!=typeof e){for(var r=[],i=0,o=e.length;i=0)e=n;else{e=n.constructor?Object.create(n.constructor.prototype):{};for(var o in n)t(n,o)&&(e[o]=g(n[o]))}return e}function b(n,e,r,i){return r=r||{},i=i||"",In(n).forEach(function(o){if(t(e,o)){var u=n[o],a=e[o];"object"==typeof u&&"object"==typeof a&&u&&a&&""+u.constructor==""+a.constructor?b(u,a,r,i+o+"."):u!==a&&(r[i+o]=e[o])}else r[i+o]=void 0}),In(e).forEach(function(o){t(n,o)||(r[i+o]=e[o])}),r}function w(n){var t,e,r,i;if(1===arguments.length){if(Cn(n))return n.slice();if(this===zn&&"string"==typeof n)return[n];if(i=Vn(n)){for(e=[];r=i.next(),!r.done;)e.push(r.value);return e}if(null==n)return[n];if("number"==typeof(t=n.length)){for(e=new Array(t);t--;)e[t]=n[t];return e}return[n]}for(t=arguments.length,e=new Array(t);t--;)e[t]=arguments[t];return e}function _(n,t){Ln=n,Wn=t}function k(){if(Qn)try{throw k.arguments,new Error}catch(n){return n}return new Error}function x(n,t){var e=n.stack;return e?(t=t||0,0===e.indexOf(n.name)&&(t+=(n.name+n.message).split("\n").length),e.split("\n").slice(t).filter(Wn).map(function(n){return"\n"+n}).join("")):""}function j(n,t){return function(){return console.warn(n+" is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. "+x(k(),1)),t.apply(this,arguments)}}function P(n,t){this._e=k(),this.name=n,this.message=t}function E(n,t){return n+". Errors: "+t.map(function(n){return n.toString()}).filter(function(n,t,e){return e.indexOf(n)===t}).join("\n")}function A(n,t,e,r){this._e=k(),this.failures=t,this.failedKeys=r,this.successCount=e}function O(n,t){this._e=k(),this.name="BulkError",this.failures=t,this.message=E(n,t)}function S(n,t){if(!n||n instanceof P||n instanceof TypeError||n instanceof SyntaxError||!n.name||!nt[n.name])return n;var e=new nt[n.name](t||n.message,n);return"stack"in n&&r(e,"stack",{get:function(){return this.inner.stack}}),e}function D(){}function I(n){return n}function C(n,t){return null==n||n===I?t:function(e){return t(n(e))}}function K(n,t){return function(){n.apply(this,arguments),t.apply(this,arguments)}}function T(n,t){return n===D?t:function(){var e=n.apply(this,arguments);void 0!==e&&(arguments[0]=e);var r=this.onsuccess,i=this.onerror;this.onsuccess=null,this.onerror=null;var o=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?K(r,this.onsuccess):r),i&&(this.onerror=this.onerror?K(i,this.onerror):i),void 0!==o?o:e}}function F(n,t){return n===D?t:function(){n.apply(this,arguments);var e=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),e&&(this.onsuccess=this.onsuccess?K(e,this.onsuccess):e),r&&(this.onerror=this.onerror?K(r,this.onerror):r)}}function B(t,e){return t===D?e:function(r){var i=t.apply(this,arguments);n(r,i);var o=this.onsuccess,u=this.onerror;this.onsuccess=null,this.onerror=null;var a=e.apply(this,arguments);return o&&(this.onsuccess=this.onsuccess?K(o,this.onsuccess):o),u&&(this.onerror=this.onerror?K(u,this.onerror):u),void 0===i?void 0===a?void 0:a:n(i,a)}}function N(n,t){return n===D?t:function(){return!1!==t.apply(this,arguments)&&n.apply(this,arguments)}}function M(n,t){return n===D?t:function(){var e=n.apply(this,arguments);if(e&&"function"==typeof e.then){for(var r=this,i=arguments.length,o=new Array(i);i--;)o[i]=arguments[i];return e.then(function(){return t.apply(r,o)})}return t.apply(this,arguments)}}function q(n){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");this._listeners=[],this.onuncatched=D,this._lib=!1;var t=this._PSD=xt;if(Ln&&(this._stackHolder=k(),this._prev=null,this._numPrev=0),"function"!=typeof n){if(n!==et)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(!1===this._state&&V(this,this._value))}this._state=null,this._value=null,++t.ref,U(this,n)}function R(n,t,e,r,i){this.onFulfilled="function"==typeof n?n:null,this.onRejected="function"==typeof t?t:null,this.resolve=e,this.reject=r,this.psd=i}function U(n,t){try{t(function(t){if(null===n._state){if(t===n)throw new TypeError("A promise cannot be resolved with itself.");var e=n._lib&&J();t&&"function"==typeof t.then?U(n,function(n,e){t instanceof q?t._then(n,e):t.then(n,e)}):(n._state=!0,n._value=t,z(n)),e&&Y()}},V.bind(null,n))}catch(t){V(n,t)}}function V(n,t){if(bt.push(t),null===n._state){var e=n._lib&&J();t=_t(t),n._state=!1,n._value=t,Ln&&null!==t&&"object"==typeof t&&!t._promise&&h(function(){var e=o(t,"stack");t._promise=n,r(t,"stack",{get:function(){return dt?e&&(e.get?e.get.apply(t):e.value):n.stack}})}),Z(n),z(n),e&&Y()}}function z(n){var t=n._listeners;n._listeners=[];for(var e=0,r=t.length;e0;)for(n=jt,jt=[],e=n.length,t=0;t0);yt=!0,mt=!0}function $(){var n=gt;gt=[],n.forEach(function(n){n._PSD.onunhandled.call(null,n._value,n)});for(var t=Et.slice(0),e=t.length;e;)t[--e]()}function X(n){function t(){n(),Et.splice(Et.indexOf(t),1)}Et.push(t),++Pt,pt(function(){0==--Pt&&$()},[])}function Z(n){gt.some(function(t){return t._value===n._value})||gt.push(n)}function nn(n){for(var t=gt.length;t;)if(gt[--t]._value===n._value)return void gt.splice(t,1)}function tn(n){return new q(et,!1,n)}function en(n,t){var e=xt;return function(){var r=J(),i=xt;try{return fn(e,!0),n.apply(this,arguments)}catch(n){t&&t(n)}finally{fn(i,!1),r&&Y()}}}function rn(t,e,r,i){var o=xt,u=Object.create(o);u.parent=o,u.ref=0,u.global=!1,u.id=++Tt;var a=kt.env;u.env=ht?{Promise:q,PromiseProp:{value:q,configurable:!0,writable:!0},all:q.all,race:q.race,resolve:q.resolve,reject:q.reject,nthen:pn(a.nthen,u),gthen:pn(a.gthen,u)}:{},e&&n(u,e),++o.ref,u.finalize=function(){--this.parent.ref||this.parent.finalize()};var c=hn(u,t,r,i);return 0===u.ref&&u.finalize(),c}function on(){return St.id||(St.id=++Dt),++St.awaits,St.echoes+=it,St.id}function un(n){!St.awaits||n&&n!==St.id||(0==--St.awaits&&(St.id=0),St.echoes=St.awaits*it)}function an(n){return St.echoes&&n&&n.constructor===ft?(on(),n.then(function(n){return un(),n},function(n){return un(),Bt(n)})):n}function cn(n){++Kt,St.echoes&&0!=--St.echoes||(St.echoes=St.id=0),It.push(xt),fn(n,!0)}function sn(){var n=It[It.length-1];It.pop(),fn(n,!1)}function fn(n,t){var e=xt;if((t?!St.echoes||Ct++&&n===xt:!Ct||--Ct&&n===xt)||dn(t?cn.bind(null,n):sn),n!==xt&&(xt=n,e===kt&&(kt.env=ln()),ht)){var r=kt.env.Promise,i=n.env;at.then=i.nthen,r.prototype.then=i.gthen,(e.global||n.global)&&(Object.defineProperty(Kn,"Promise",i.PromiseProp),r.all=i.all,r.race=i.race,r.resolve=i.resolve,r.reject=i.reject)}}function ln(){var n=Kn.Promise;return ht?{Promise:n,PromiseProp:Object.getOwnPropertyDescriptor(Kn,"Promise"),all:n.all,race:n.race,resolve:n.resolve,reject:n.reject,nthen:at.then,gthen:n.prototype.then}:{}}function hn(n,t,e,r,i){var o=xt;try{return fn(n,!0),t(e,r,i)}finally{fn(o,!1)}}function dn(n){st.call(ut,n)}function vn(n,t,e){return"function"!=typeof n?n:function(){var r=xt;e&&on(),fn(t,!0);try{return n.apply(this,arguments)}finally{fn(r,!1)}}}function pn(n,t){return function(e,r){return n.call(this,vn(e,t,!1),vn(r,t,!1))}}function yn(t,e){var r;try{r=e.onuncatched(t)}catch(n){}if(!1!==r)try{var i,o={promise:e,reason:t};if(Kn.document&&document.createEvent?(i=document.createEvent("Event"),i.initEvent(Ft,!0,!0),n(i,o)):Kn.CustomEvent&&(i=new CustomEvent(Ft,{detail:o}),n(i,o)),i&&Kn.dispatchEvent&&(dispatchEvent(i),!Kn.PromiseRejectionEvent&&Kn.onunhandledrejection))try{Kn.onunhandledrejection(i)}catch(n){}i.defaultPrevented||console.warn("Unhandled rejection: "+(t.stack||t))}catch(n){}}function mn(n){function t(n,t,o){if("object"==typeof n)return e(n);t||(t=N),o||(o=D);var u={subscribers:[],fire:o,subscribe:function(n){-1===u.subscribers.indexOf(n)&&(u.subscribers.push(n),u.fire=t(u.fire,n))},unsubscribe:function(n){u.subscribers=u.subscribers.filter(function(t){return t!==n}),u.fire=u.subscribers.reduce(t,o)}};return r[n]=i[n]=u,u}function e(n){In(n).forEach(function(e){var r=n[e];if(Cn(r))t(e,n[e][0],n[e][1]);else{if("asap"!==r)throw new Zn.InvalidArgument("Invalid event config");var i=t(e,I,function(){for(var n=arguments.length,t=new Array(n);n--;)t[n]=arguments[n];i.subscribers.forEach(function(n){s(function(){n.apply(null,t)})})})}})}var r={},i=function(t,e){if(e){for(var i=arguments.length,o=new Array(i-1);--i;)o[i-1]=arguments[i];return r[t].subscribe.apply(null,o),n}if("string"==typeof t)return r[t]};i.addEventType=t;for(var o=1,u=arguments.length;on}).forEach(function(n){i.push(function(){var r=Un,i=n._cfg.dbschema;vn(r,e),vn(i,e),Un=nt._dbSchema=i;var o=x(r,i);if(o.add.forEach(function(n){P(e,n[0],n[1].primKey,n[1].indexes)}),o.change.forEach(function(n){if(n.recreate)throw new Zn.Upgrade("Not yet support for changing primary key");var t=e.objectStore(n.name);n.add.forEach(function(n){K(t,n)}),n.change.forEach(function(n){t.deleteIndex(n.name),K(t,n)}),n.del.forEach(function(n){t.deleteIndex(n)})}),n._cfg.contentUpgrade)return u=!0,q.follow(function(){n._cfg.contentUpgrade(t)})}),i.push(function(t){u&&Wt||S(n._cfg.dbschema,t)})}),r().then(function(){E(Un,e)})}function x(n,t){var e={del:[],add:[],change:[]};for(var r in n)t[r]||e.del.push(r);for(r in t){var i=n[r],o=t[r];if(i){var u={name:r,def:o,recreate:!1,del:[],add:[],change:[]};if(i.primKey.src!==o.primKey.src)u.recreate=!0,e.change.push(u);else{var a=i.idxByName,c=o.idxByName;for(var s in a)c[s]||u.del.push(s);for(s in c){var f=a[s],l=c[s];f?f.src!==l.src&&u.change.push(l):u.add.push(l)}(u.del.length>0||u.add.length>0||u.change.length>0)&&e.change.push(u)}}else e.add.push([r,o])}return e}function P(n,t,e,r){var i=n.db.createObjectStore(t,e.keyPath?{keyPath:e.keyPath,autoIncrement:e.auto}:{autoIncrement:e.auto});return r.forEach(function(n){K(i,n)}),i}function E(n,t){In(n).forEach(function(e){t.db.objectStoreNames.contains(e)||P(t,e,n[e].primKey,n[e].indexes)})}function S(n,t){for(var e=0;e0?n:t}function an(n,t){return qn.cmp(n,t)}function cn(n,t){return qn.cmp(t,n)}function sn(n,t){return nt?-1:n===t?0:1}function ln(n,t){return n?t?function(){return n.apply(this,arguments)&&t.apply(this,arguments)}:n:t}function dn(){if(nt.verno=Hn.version/10,nt._dbSchema=Un={},Wn=u(Hn.objectStoreNames,0),0!==Wn.length){var n=Hn.transaction(Sn(Wn),"readonly");Wn.forEach(function(t){for(var e=n.objectStore(t),r=e.keyPath,i=r&&"string"==typeof r&&-1!==r.indexOf("."),o=new An(r,r||"",!1,!1,!!e.autoIncrement,r&&"string"!=typeof r,i),u=[],a=0;aMath.pow(2,62)?0:n.oldVersion)/10,t,e)}},e),r.onsuccess=en(function(){if(t=null,Hn=r.result,zt.push(nt),rt)dn();else if(Hn.objectStoreNames.length>0)try{vn(Un,Hn.transaction(Sn(Hn.objectStoreNames),"readonly"))}catch(n){}Hn.onversionchange=en(function(n){nt._vcFired=!0,nt.on("versionchange").fire(n)}),it||"__dbnames"===i||Ot.dbnames.put({name:i}).catch(D),n()},e)})]).then(function(){return Yn=[],q.resolve(gn.vip(nt.on.ready.fire)).then(function n(){if(Yn.length>0){var t=Yn.reduce(M,D);return Yn=[],q.resolve(gn.vip(t)).then(n)}})}).finally(function(){Yn=null}).then(function(){return Jn=!1,nt}).catch(function(n){try{t&&t.abort()}catch(n){}return Jn=!1,nt.close(),Gn=n,Bt(Gn)}).finally(function(){$n=!0,n()})},this.close=function(){var n=zt.indexOf(nt);if(n>=0&&zt.splice(n,1),Hn){try{Hn.close()}catch(n){}Hn=null}Mn=!1,Gn=new Zn.DatabaseClosed,Jn&&bn(Gn),tt=new q(function(n){yn=n}),et=new q(function(n,t){bn=t})},this.delete=function(){var n=arguments.length>0;return new q(function(t,e){function r(){nt.close();var n=qn.deleteDatabase(i);n.onsuccess=en(function(){it||Ot.dbnames.delete(i).catch(D),t()}),n.onerror=kn(e),n.onblocked=pn}if(n)throw new Zn.InvalidArgument("Arguments not allowed in db.delete()");Jn?tt.then(r):r()})},this.backendDB=function(){return Hn},this.isOpen=function(){return null!==Hn},this.hasBeenClosed=function(){return Gn&&Gn instanceof Zn.DatabaseClosed},this.hasFailed=function(){return null!==Gn},this.dynamicallyOpened=function(){return rt},this.name=i,e(this,{tables:{get:function(){return In(Qn).map(function(n){return Qn[n]})}}}),this.on=mn(this,"populate","blocked","versionchange",{ready:[M,D]}),this.on.ready.subscribe=a(this.on.ready.subscribe,function(n){return function(t,e){gn.vip(function(){$n?(Gn||q.resolve().then(t),e&&n(t)):Yn?(Yn.push(t),e&&n(t)):(n(t),e||n(function n(){nt.on.ready.unsubscribe(t),nt.on.ready.unsubscribe(n)}))})}}),this.transaction=function(){var n=R.apply(this,arguments);return this._transaction.apply(this,n)},this._transaction=function(n,t,e){function r(){return q.resolve().then(function(){var t=xt.transless||xt,r=nt._createTransaction(n,u,Un,i),o={trans:r,transless:t};i?r.idbtrans=i.idbtrans:r.create(),e.constructor===lt&&on();var a,c=q.follow(function(){if(a=e.call(r,r))if(a.constructor===ft){var n=un.bind(null,null);a.then(n,n)}else"function"==typeof a.next&&"function"==typeof a.throw&&(a=En(a))},o);return(a&&"function"==typeof a.then?q.resolve(a).then(function(n){return r.active?n:Bt(new Zn.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):c.then(function(){return a})).then(function(n){return i&&r._resolve(),r._completion.then(function(){return n})}).catch(function(n){return r._reject(n),Bt(n)})})}var i=xt.trans;i&&i.db===nt&&-1===n.indexOf("!")||(i=null);var o=-1!==n.indexOf("?");n=n.replace("!","").replace("?","");try{var u=t.map(function(n){var t=n instanceof U?n.name:n;if("string"!=typeof t)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return t});if("r"==n||"readonly"==n)n="readonly";else{if("rw"!=n&&n!=Xn)throw new Zn.InvalidArgument("Invalid transaction mode: "+n);n=Xn}if(i){if("readonly"===i.mode&&n===Xn){if(!o)throw new Zn.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");i=null}i&&u.forEach(function(n){if(i&&-1===i.storeNames.indexOf(n)){if(!o)throw new Zn.SubTransaction("Table "+n+" not included in parent transaction.");i=null}}),o&&i&&!i.active&&(i=null)}}catch(n){return i?i._promise(null,function(t,e){e(n)}):Bt(n)}return i?i._promise(n,r,"lock"):xt.trans?hn(xt.transless,function(){return nt._whenReady(r)}):nt._whenReady(r)},this.table=function(n){if(!t(Qn,n))throw new Zn.InvalidTable("Table "+n+" does not exist");return Qn[n]},e(U.prototype,{_trans:function(n,t,e){var r=this._tx||xt.trans;return r&&r.db===nt?r===xt.trans?r._promise(n,t,e):rn(function(){return r._promise(n,t,e)},{trans:r,transless:xt.transless||xt}):N(n,[this.name],t)},_idbstore:function(n,t,e){function r(n,e,r){if(-1===r.storeNames.indexOf(i))throw new Zn.NotFound("Table"+i+" not part of transaction");return t(n,e,r.idbtrans.objectStore(i),r)}var i=this.name;return this._trans(n,r,e)},get:function(n,t){if(n&&n.constructor===Object)return this.where(n).first(t);var e=this;return this._idbstore("readonly",function(t,r,i){var o=i.get(n);o.onerror=kn(r),o.onsuccess=en(function(){t(e.hook.reading.fire(o.result))},r)}).then(t)},where:function(n){if("string"==typeof n)return new W(this,n);if(Cn(n))return new W(this,"["+n.join("+")+"]");var t=In(n);if(1===t.length)return this.where(t[0]).equals(n[t[0]]);var e=this.schema.indexes.concat(this.schema.primKey).filter(function(n){return n.compound&&t.every(function(t){return n.keyPath.indexOf(t)>=0})&&n.keyPath.every(function(n){return t.indexOf(n)>=0})})[0];if(e&&qt!==Mt)return this.where(e.name).equals(e.keyPath.map(function(t){return n[t]}));e||console.warn("The query "+JSON.stringify(n)+" on "+this.name+" would benefit of a compound index ["+t.join("+")+"]");var r=this.schema.idxByName,i=t.reduce(function(t,e){return[t[0]||r[e],t[0]||!r[e]?ln(t[1],function(t){return""+d(t,e)==""+n[e]}):t[1]]},[null,null]),o=i[0];return o?this.where(o.name).equals(n[o.keyPath]).filter(i[1]):e?this.filter(i[1]):this.where(t).equals("")},count:function(n){return this.toCollection().count(n)},offset:function(n){return this.toCollection().offset(n)},limit:function(n){return this.toCollection().limit(n)},reverse:function(){return this.toCollection().reverse()},filter:function(n){return this.toCollection().and(n)},each:function(n){return this.toCollection().each(n)},toArray:function(n){return this.toCollection().toArray(n)},orderBy:function(n){return new Q(new W(this,Cn(n)?"["+n.join("+")+"]":n))},toCollection:function(){return new Q(new W(this))},mapToClass:function(n,e){this.schema.mappedClass=n;var r=Object.create(n.prototype);e&&wn(r,e),this.schema.instanceTemplate=r;var i=function(e){if(!e)return e;var r=Object.create(n.prototype);for(var i in e)if(t(e,i))try{r[i]=e[i]}catch(n){}return r};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=i,this.hook("reading",i),n},defineClass:function(n){return this.mapToClass(gn.defineClass(n),n)},bulkDelete:function(n){return this.hook.deleting.fire===D?this._idbstore(Xn,function(t,e,r,i){t(z(r,i,n,!1,D))}):this.where(":id").anyOf(n).delete().then(function(){})},bulkPut:function(n,t){var e=this;return this._idbstore(Xn,function(r,i,o){if(!o.keyPath&&!e.schema.primKey.auto&&!t)throw new Zn.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");if(o.keyPath&&t)throw new Zn.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(t&&t.length!==n.length)throw new Zn.InvalidArgument("Arguments objects and keys must have the same length");if(0===n.length)return r();var u,a,c=function(n){0===s.length?r(n):i(new O(e.name+".bulkPut(): "+s.length+" of "+l+" operations failed",s))},s=[],l=n.length,h=e;if(e.hook.creating.fire===D&&e.hook.updating.fire===D){a=V(s);for(var v=0,p=n.length;v=0;--i){var o=y[i];(null==o||m[o])&&(e.push(n[i]),t&&r.push(o),null!=o&&(m[o]=null))}return e.reverse(),t&&r.reverse(),h.bulkAdd(e,r)}).then(function(n){var t=y[y.length-1];return null!=t?t:n}):h.bulkAdd(n)).then(c).catch(O,function(n){s=s.concat(n.failures),c()}).catch(i)}},"locked")},bulkAdd:function(n,t){var e=this,r=this.hook.creating.fire;return this._idbstore(Xn,function(i,o,u,a){function c(n){0===p.length?i(n):o(new O(e.name+".bulkAdd(): "+p.length+" of "+y+" operations failed",p))}if(!u.keyPath&&!e.schema.primKey.auto&&!t)throw new Zn.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");if(u.keyPath&&t)throw new Zn.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(t&&t.length!==n.length)throw new Zn.InvalidArgument("Arguments objects and keys must have the same length");if(0===n.length)return i();var s,f,l,p=[],y=n.length;if(r!==D){var m,b=u.keyPath;f=V(p,null,!0),l=_n(null),h(function(){for(var e=0,i=n.length;e0&&!this._locked();){var n=this._blockedFuncs.shift();try{hn(n[1],n[0])}catch(n){}}return this},_locked:function(){return this._reculock&&xt.lockOwnerFor!==this},create:function(n){var t=this;if(!this.mode)return this;if(c(!this.idbtrans),!n&&!Hn)switch(Gn&&Gn.name){case"DatabaseClosedError":throw new Zn.DatabaseClosed(Gn);case"MissingAPIError":throw new Zn.MissingAPI(Gn.message,Gn);default:throw new Zn.OpenFailed(Gn)}if(!this.active)throw new Zn.TransactionInactive;return c(null===this._completion._state),n=this.idbtrans=n||Hn.transaction(Sn(this.storeNames),this.mode),n.onerror=en(function(e){Pn(e),t._reject(n.error)}),n.onabort=en(function(e){Pn(e),t.active&&t._reject(new Zn.Abort(n.error)),t.active=!1,t.on("abort").fire(e)}),n.oncomplete=en(function(){t.active=!1,t._resolve()}),this},_promise:function(n,t,e){var r=this;if(n===Xn&&this.mode!==Xn)return Bt(new Zn.ReadOnly("Transaction is readonly"));if(!this.active)return Bt(new Zn.TransactionInactive);if(this._locked())return new q(function(i,o){r._blockedFuncs.push([function(){r._promise(n,t,e).then(i,o)},xt])});if(e)return rn(function(){var n=new q(function(n,e){r._lock();var i=t(n,e,r);i&&i.then&&i.then(n,e)});return n.finally(function(){return r._unlock()}),n._lib=!0,n});var i=new q(function(n,e){var i=t(n,e,r);i&&i.then&&i.then(n,e)});return i._lib=!0,i},_root:function(){return this.parent?this.parent._root():this},waitFor:function(n){var t=this._root();if(n=q.resolve(n),t._waitingFor)t._waitingFor=t._waitingFor.then(function(){return n});else{t._waitingFor=n,t._waitingQueue=[];var e=t.idbtrans.objectStore(t.storeNames[0]);!function n(){for(++t._spinCount;t._waitingQueue.length;)t._waitingQueue.shift()();t._waitingFor&&(e.get(-1/0).onsuccess=n)}()}var r=t._waitingFor;return new q(function(e,i){n.then(function(n){return t._waitingQueue.push(en(e.bind(null,n)))},function(n){return t._waitingQueue.push(en(i.bind(null,n)))}).finally(function(){t._waitingFor===r&&(t._waitingFor=null)})})},abort:function(){this.active&&this._reject(new Zn.Abort),this.active=!1},tables:{get:j("Transaction.tables",function(){return Qn})},table:function(n){return new U(n,nt.table(n).schema,this)}}),e(W.prototype,function(){function n(n,t,e){var r=n instanceof W?new Q(n):n;return r._ctx.error=e?new e(t):new TypeError(t),r}function t(n){return new Q(n,function(){return Rn.only("")}).limit(0)}function e(n){return"next"===n?function(n){return n.toUpperCase()}:function(n){return n.toLowerCase()}}function r(n){return"next"===n?function(n){return n.toLowerCase()}:function(n){return n.toUpperCase()}}function i(n,t,e,r,i,o){for(var u=Math.min(n.length,r.length),a=-1,c=0;c=0?n.substr(0,a)+t[a]+e.substr(a+1):null;i(n[c],s)<0&&(a=c)}return u0)&&(a=s)}return t(null!==a?function(){n.continue(a+p)}:e),!1}),m}return{between:function(e,r,i,o){i=!1!==i,o=!0===o;try{return Z(e,r)>0||0===Z(e,r)&&(i||o)&&(!i||!o)?t(this):new Q(this,function(){return Rn.bound(e,r,!i,!o)})}catch(t){return n(this,Ut)}},equals:function(n){return new Q(this,function(){return Rn.only(n)})},above:function(n){return new Q(this,function(){return Rn.lowerBound(n,!0)})},aboveOrEqual:function(n){return new Q(this,function(){return Rn.lowerBound(n)})},below:function(n){return new Q(this,function(){return Rn.upperBound(n,!0)})},belowOrEqual:function(n){return new Q(this,function(){return Rn.upperBound(n)})},startsWith:function(t){return"string"!=typeof t?n(this,Vt):this.between(t,t+Mt,!0,!0)},startsWithIgnoreCase:function(n){return""===n?this.startsWith(n):o(this,function(n,t){return 0===n.indexOf(t[0])},[n],Mt)},equalsIgnoreCase:function(n){return o(this,function(n,t){return n===t[0]},[n],"")},anyOfIgnoreCase:function(){var n=w.apply(zn,arguments);return 0===n.length?t(this):o(this,function(n,t){return-1!==t.indexOf(n)},n,"")},startsWithAnyOfIgnoreCase:function(){var n=w.apply(zn,arguments);return 0===n.length?t(this):o(this,function(n,t){return t.some(function(t){return 0===n.indexOf(t)})},n,Mt)},anyOf:function(){var e=w.apply(zn,arguments),r=an;try{e.sort(r)}catch(t){return n(this,Ut)}if(0===e.length)return t(this);var i=new Q(this,function(){return Rn.bound(e[0],e[e.length-1])});i._ondirectionchange=function(n){r="next"===n?an:cn,e.sort(r)};var o=0;return i._addAlgorithm(function(n,t,i){for(var u=n.key;r(u,e[o])>0;)if(++o===e.length)return t(i),!1;return 0===r(u,e[o])||(t(function(){n.continue(e[o])}),!1)}),i},notEqual:function(n){return this.inAnyRange([[Rt,n],[n,qt]],{includeLowers:!1,includeUppers:!1})},noneOf:function(){var t=w.apply(zn,arguments);if(0===t.length)return new Q(this);try{t.sort(an)}catch(t){return n(this,Ut)}var e=t.reduce(function(n,t){return n?n.concat([[n[n.length-1][1],t]]):[[Rt,t]]},null);return e.push([t[t.length-1],qt]),this.inAnyRange(e,{includeLowers:!1,includeUppers:!1})},inAnyRange:function(e,r){function i(n,t){for(var e=0,r=n.length;e0){i[0]=nn(i[0],t[0]),i[1]=tn(i[1],t[1]);break}}return e===r&&n.push(t),n}function o(n,t){return f(n[0],t[0])}function u(n){return!h(n)&&!d(n)}if(0===e.length)return t(this);if(!e.every(function(n){return void 0!==n[0]&&void 0!==n[1]&&an(n[0],n[1])<=0}))return n(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Zn.InvalidArgument);var a,c=!r||!1!==r.includeLowers,s=r&&!0===r.includeUppers,f=an;try{a=e.reduce(i,[]),a.sort(o)}catch(t){return n(this,Ut)}var l=0,h=s?function(n){return an(n,a[l][1])>0}:function(n){return an(n,a[l][1])>=0},d=c?function(n){return cn(n,a[l][0])>0}:function(n){return cn(n,a[l][0])>=0},v=h,p=new Q(this,function(){return Rn.bound(a[0][0],a[a.length-1][1],!c,!s)});return p._ondirectionchange=function(n){"next"===n?(v=h,f=an):(v=d,f=cn),a.sort(o)},p._addAlgorithm(function(n,t,e){for(var r=n.key;v(r);)if(++l===a.length)return t(e),!1;return!!u(r)||0!==Z(r,a[l][1])&&0!==Z(r,a[l][0])&&(t(function(){f===an?n.continue(a[l][0]):n.continue(a[l][1])}),!1)}),p},startsWithAnyOf:function(){var e=w.apply(zn,arguments);return e.every(function(n){return"string"==typeof n})?0===e.length?t(this):this.inAnyRange(e.map(function(n){return[n,n+Mt]})):n(this,"startsWithAnyOf() only works with strings")}}}),e(Q.prototype,function(){function e(n,t){n.filter=ln(n.filter,t)}function r(n,t,e){var r=n.replayFilter;n.replayFilter=r?function(){return ln(r(),t())}:t,n.justLimit=e&&!r}function i(n,t){n.isMatch=ln(n.isMatch,t)}function o(n,t){if(n.isPrimKey)return t;var e=n.table.schema.idxByName[n.index];if(!e)throw new Zn.Schema("KeyPath "+n.index+" on object store "+t.name+" is not indexed");return t.index(e.name)}function u(n,t){var e=o(n,t);return n.keysOnly&&"openKeyCursor"in e?e.openKeyCursor(n.range||null,n.dir+n.unique):e.openCursor(n.range||null,n.dir+n.unique)}function a(n,e,r,i,o){var a=n.replayFilter?ln(n.filter,n.replayFilter()):n.filter;n.or?function(){function c(){2==++l&&r()}function s(n,r,o){if(!a||a(r,o,c,i)){var u=r.primaryKey,s=""+u;"[object ArrayBuffer]"===s&&(s=""+new Uint8Array(u)),t(f,s)||(f[s]=!0,e(n,r,o))}}var f={},l=0;n.or._iterate(s,c,i,o),$(u(n,o),n.algorithm,s,c,i,!n.keysOnly&&n.valueMapper)}():$(u(n,o),ln(n.algorithm,a),e,r,i,!n.keysOnly&&n.valueMapper)}return{_read:function(n,t){var e=this._ctx;return e.error?e.table._trans(null,Bt.bind(null,e.error)):e.table._idbstore("readonly",n).then(t)},_write:function(n){var t=this._ctx;return t.error?t.table._trans(null,Bt.bind(null,t.error)):t.table._idbstore(Xn,n,"locked")},_addAlgorithm:function(n){var t=this._ctx;t.algorithm=ln(t.algorithm,n)},_iterate:function(n,t,e,r){return a(this._ctx,n,t,e,r)},clone:function(t){var e=Object.create(this.constructor.prototype),r=Object.create(this._ctx);return t&&n(r,t),e._ctx=r,e},raw:function(){return this._ctx.valueMapper=null,this},each:function(n){var t=this._ctx;return this._read(function(e,r,i){a(t,n,e,r,i)})},count:function(n){var t=this._ctx;if(H(t,!0))return this._read(function(n,e,r){var i=o(t,r),u=t.range?i.count(t.range):i.count();u.onerror=kn(e),u.onsuccess=function(e){n(Math.min(e.target.result,t.limit))}},n);var e=0;return this._read(function(n,r,i){a(t,function(){return++e,!1},function(){n(e)},r,i)},n)},sortBy:function(n,t){function e(n,t){return t?e(n[i[t]],t-1):n[o]}function r(n,t){var r=e(n,u),i=e(t,u);return ri?a:0}var i=n.split(".").reverse(),o=i[0],u=i.length-1,a="next"===this._ctx.dir?1:-1;return this.toArray(function(n){return n.sort(r)}).then(t)},toArray:function(n){var t=this._ctx;return this._read(function(n,e,r){if(Tn&&"next"===t.dir&&H(t,!0)&&t.limit>0){var i=t.table.hook.reading.fire,u=o(t,r),c=t.limit<1/0?u.getAll(t.range,t.limit):u.getAll(t.range);c.onerror=kn(e),c.onsuccess=xn(i===I?n:function(t){try{n(t.map(i))}catch(n){e(n)}})}else{var s=[];a(t,function(n){s.push(n)},function(){n(s)},e,r)}},n)},offset:function(n){var t=this._ctx;return n<=0?this:(t.offset+=n,H(t)?r(t,function(){var t=n;return function(n,e){return 0===t||(1===t?(--t,!1):(e(function(){n.advance(t),t=0}),!1))}}):r(t,function(){var t=n;return function(){return--t<0}}),this)},limit:function(n){return this._ctx.limit=Math.min(this._ctx.limit,n),r(this._ctx,function(){var t=n;return function(n,e,r){return--t<=0&&e(r),t>=0}},!0),this},until:function(n,t){this._ctx;return e(this._ctx,function(e,r,i){return!n(e.value)||(r(i),t)}),this},first:function(n){return this.limit(1).toArray(function(n){return n[0]}).then(n)},last:function(n){return this.reverse().first(n)},filter:function(n){return e(this._ctx,function(t){return n(t.value)}),i(this._ctx,n),this},and:function(n){return this.filter(n)},or:function(n){return new W(this._ctx.table,n,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(n){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each(function(t,e){n(e.key,e)})},eachUniqueKey:function(n){return this._ctx.unique="unique",this.eachKey(n)},eachPrimaryKey:function(n){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each(function(t,e){n(e.primaryKey,e)})},keys:function(n){var t=this._ctx;t.keysOnly=!t.isMatch;var e=[];return this.each(function(n,t){e.push(t.key)}).then(function(){return e}).then(n)},primaryKeys:function(n){var t=this._ctx;if(Tn&&"next"===t.dir&&H(t,!0)&&t.limit>0)return this._read(function(n,e,r){var i=o(t,r),u=t.limit<1/0?i.getAllKeys(t.range,t.limit):i.getAllKeys(t.range);u.onerror=kn(e),u.onsuccess=xn(n)}).then(n);t.keysOnly=!t.isMatch;var e=[];return this.each(function(n,t){e.push(t.primaryKey)}).then(function(){return e}).then(n)},uniqueKeys:function(n){return this._ctx.unique="unique",this.keys(n)},firstKey:function(n){return this.limit(1).keys(function(n){return n[0]}).then(n)},lastKey:function(n){return this.reverse().firstKey(n)},distinct:function(){var n=this._ctx,r=n.index&&n.table.schema.idxByName[n.index];if(!r||!r.multi)return this;var i={};return e(this._ctx,function(n){var e=n.primaryKey.toString(),r=t(i,e);return i[e]=!0,!r}),this},modify:function(e){var r=this,i=this._ctx,o=i.table.hook,u=o.updating.fire,a=o.deleting.fire;return this._write(function(i,o,c,s){function f(n,e){function r(n){return E.push(n),O.push(i.primKey),p(),!0}S=e.primaryKey;var i={primKey:e.primaryKey,value:n,onsuccess:null,onerror:null};if(!1!==m.call(i,n,i)){var o=!t(i,"value");++x,h(function(){var n=o?e.delete():e.update(i.value);n._hookCtx=i,n.onerror=jn(r),n.onsuccess=_n(function(){++j,p()})},r)}else i.onsuccess&&i.onsuccess(i.value)}function l(n){return n&&(E.push(n),O.push(S)),o(new A("Error modifying one or more objects",E,j,O))}function p(){P&&j+E.length===x&&(E.length>0?l():i(j))}var m;if("function"==typeof e)m=u===D&&a===D?e:function(n){var r=g(n);if(!1===e.call(this,n,this))return!1;if(t(this,"value")){var i=b(r,this.value),o=u.call(this,i,this.primKey,r,s);o&&(n=this.value,In(o).forEach(function(t){v(n,t,o[t])}))}else a.call(this,this.primKey,n,s)};else if(u===D){var w=In(e),_=w.length;m=function(n){for(var t=!1,r=0;r<_;++r){var i=w[r],o=e[i];d(n,i)!==o&&(v(n,i,o),t=!0)}return t}}else{var k=e;e=y(k),m=function(t){var r=!1,i=u.call(this,e,this.primKey,g(t),s);return i&&n(e,i),In(e).forEach(function(n){var i=e[n];d(t,n)!==i&&(v(t,n,i),r=!0)}),i&&(e=y(k)),r}}var x=0,j=0,P=!1,E=[],O=[],S=null;r.clone().raw()._iterate(f,function(){P=!0,p()},l,c)})},delete:function(){var n=this,t=this._ctx,e=t.range,r=t.table.hook.deleting.fire,i=r!==D;if(!i&&H(t)&&(t.isPrimKey&&!Qt||!e))return this._write(function(n,t,r){var i=kn(t),o=e?r.count(e):r.count();o.onerror=i,o.onsuccess=function(){var u=o.result;h(function(){var t=e?r.delete(e):r.clear();t.onerror=i,t.onsuccess=function(){return n(u)}},function(n){return t(n)})}});var o=i?2e3:1e4;return this._write(function(e,u,a,c){var s=0,f=n.clone({keysOnly:!t.isMatch&&!i}).distinct().limit(o).raw(),l=[],h=function(){return f.each(i?function(n,t){l.push([t.primaryKey,t.value])}:function(n,t){l.push(t.primaryKey)}).then(function(){return i?l.sort(function(n,t){return an(n[0],t[0])}):l.sort(an),z(a,c,l,i,r)}).then(function(){var n=l.length;return s+=n,l=[],n0?console.warn("Another connection wants to upgrade database '"+nt.name+"'. Closing db now to resume the upgrade."):console.warn("Another connection wants to delete database '"+nt.name+"'. Closing db now to resume the delete request."),nt.close()}),nt.on("blocked",function(n){!n.newVersion||n.newVersion{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];")()}catch(t){var n=Kn.Promise;return n?[n.resolve(),n.prototype,n.resolve()]:[]}}(),ut=ot[0],at=ot[1],ct=ot[2],st=at&&at.then,ft=ut&&ut.constructor,lt=ot[3],ht=!!ct,dt=!1,vt=ct?function(){ct.then(G)}:Kn.setImmediate?setImmediate.bind(null,G):Kn.MutationObserver?function(){var n=document.createElement("div");new MutationObserver(function(){G(),n=null}).observe(n,{attributes:!0}),n.setAttribute("i","1")}:function(){setTimeout(G,0)},pt=function(n,t){jt.push([n,t]),mt&&(vt(),mt=!1)},yt=!0,mt=!0,gt=[],bt=[],wt=null,_t=I,kt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:yn,pgp:!1,env:{},finalize:function(){this.unhandleds.forEach(function(n){try{yn(n[0],n[1])}catch(n){}})}},xt=kt,jt=[],Pt=0,Et=[],At={get:function(){function n(n,r){var i=this,o=!t.global&&(t!==xt||e!==Kt);o&&un();var u=new q(function(e,u){L(i,new R(vn(n,t,o),vn(r,t,o),e,u,t))});return Ln&&H(u,this),u}var t=xt,e=Kt;return n.prototype=et,n},set:function(n){r(this,"then",n&&n.prototype===et?At:{get:function(){return n},set:At.set})}};e(q.prototype,{then:At,_then:function(n,t){L(this,new R(null,null,n,t,xt))},catch:function(n){if(1===arguments.length)return this.then(null,n);var t=arguments[0],e=arguments[1];return"function"==typeof t?this.then(null,function(n){return n instanceof t?e(n):tn(n)}):this.then(null,function(n){return n&&n.name===t?e(n):tn(n)})},finally:function(n){return this.then(function(t){return n(),t},function(t){return n(),tn(t)})},stack:{get:function(){if(this._stack)return this._stack;try{dt=!0;var n=Q(this,[],20),t=n.join("\nFrom previous: ");return null!==this._state&&(this._stack=t),t}finally{dt=!1}}},timeout:function(n,t){var e=this;return n<1/0?new q(function(r,i){var o=setTimeout(function(){return i(new Zn.Timeout(t))},n);e.then(r,i).finally(clearTimeout.bind(null,o))}):this}}),"undefined"!=typeof Symbol&&Symbol.toStringTag&&r(q.prototype,Symbol.toStringTag,"Promise"),kt.env=ln(),e(q,{all:function(){var n=w.apply(null,arguments).map(an);return new q(function(t,e){0===n.length&&t([]);var r=n.length;n.forEach(function(i,o){return q.resolve(i).then(function(e){n[o]=e,--r||t(n)},e)})})},resolve:function(n){if(n instanceof q)return n;if(n&&"function"==typeof n.then)return new q(function(t,e){n.then(t,e)});var t=new q(et,!0,n);return H(t,wt),t},reject:tn,race:function(){var n=w.apply(null,arguments).map(an);return new q(function(t,e){n.map(function(n){return q.resolve(n).then(t,e)})})},PSD:{get:function(){return xt},set:function(n){return xt=n}},newPSD:rn,usePSD:hn,scheduler:{get:function(){return pt},set:function(n){pt=n}},rejectionMapper:{get:function(){return _t},set:function(n){_t=n}},follow:function(n,t){return new q(function(e,r){return rn(function(t,e){var r=xt;r.unhandleds=[],r.onunhandled=e,r.finalize=K(function(){var n=this;X(function(){0===n.unhandleds.length?t():e(n.unhandleds[0])})},r.finalize),n()},t,e,r)})}});var Ot,St={awaits:0,echoes:0,id:0},Dt=0,It=[],Ct=0,Kt=0,Tt=0,Ft="unhandledrejection",Bt=q.reject,Nt="2.0.2",Mt=String.fromCharCode(65535),qt=function(){try{return IDBKeyRange.only([[]]),[[]]}catch(n){return Mt}}(),Rt=-1/0,Ut="Invalid key provided. Keys must be of type string, number, Date or Array.",Vt="String expected.",zt=[],Lt="undefined"!=typeof navigator&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),Wt=Lt,Qt=Lt,Ht=function(n){return!/(dexie\.js|dexie\.min\.js)/.test(n)};return _(Ln,Ht),e(gn,tt),e(gn,{delete:function(n){var t=new gn(n),e=t.delete();return e.onblocked=function(n){return t.on("blocked",n),this},e},exists:function(n){return new gn(n).open().then(function(n){return n.close(),!0}).catch(gn.NoSuchDatabaseError,function(){return!1})},getDatabaseNames:function(n){var t=Dn(gn.dependencies.indexedDB);return t?new q(function(n,e){var r=t();r.onsuccess=function(t){n(u(t.target.result,0))},r.onerror=kn(e)}).then(n):Ot.dbnames.toCollection().primaryKeys(n)},defineClass:function(t){function e(t){t&&n(this,t)}return e},applyStructure:wn,ignoreTransaction:function(n){return xt.trans?hn(xt.transless,n):n()},vip:function(n){return rn(function(){return xt.letThrough=!0,n()})},async:function(n){return function(){try{var t=En(n.apply(this,arguments));return t&&"function"==typeof t.then?t:q.resolve(t)}catch(n){return Bt(n)}}},spawn:function(n,t,e){try{var r=En(n.apply(e,t||[]));return r&&"function"==typeof r.then?r:q.resolve(r)}catch(n){return Bt(n)}},currentTransaction:{get:function(){return xt.trans||null}},waitFor:function(n,t){var e=q.resolve("function"==typeof n?gn.ignoreTransaction(n):n).timeout(t||6e4);return xt.trans?xt.trans.waitFor(e):e},Promise:q,debug:{get:function(){return Ln},set:function(n){_(n,"dexie"===n?function(){return!0}:Ht)}},derive:i,extend:n,props:e,override:a,Events:mn,getByKeyPath:d,setByKeyPath:v,delByKeyPath:p,shallowClone:y,deepClone:g,getObjectDiff:b,asap:s,maxKey:qt,minKey:Rt,addons:[],connections:zt,MultiModifyError:Zn.Modify,errnames:$n,IndexSpec:An,TableSchema:On,dependencies:{indexedDB:Kn.indexedDB||Kn.mozIndexedDB||Kn.webkitIndexedDB||Kn.msIndexedDB,IDBKeyRange:Kn.IDBKeyRange||Kn.webkitIDBKeyRange},semVer:Nt,version:Nt.split(".").map(function(n){return parseInt(n)}).reduce(function(n,t,e){return n+t/Math.pow(10,2*e)}),default:gn,Dexie:gn}),q.rejectionMapper=S,Ot=new gn("__dbnames"),Ot.version(1).stores({dbnames:"name"}),function(){if(void 0!==typeof localStorage&&void 0!==Kn.document)try{JSON.parse(localStorage.getItem("Dexie.DatabaseNames")||"[]").forEach(function(n){return Ot.dbnames.put({name:n}).catch(D)}),localStorage.removeItem("Dexie.DatabaseNames")}catch(n){}}(),gn}); +//# sourceMappingURL=dexie.min.js.map \ No newline at end of file diff --git a/dist/dexie.min.js.map b/dist/dexie.min.js.map new file mode 100644 index 000000000..49a1b4218 --- /dev/null +++ b/dist/dexie.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/utils.js","../src/debug.js","../src/errors.js","../src/chaining-functions.js","../src/Promise.js","../src/Events.js","../src/Dexie.js"],"names":["extend","obj","extension","keys","forEach","key","hasOwn","prop","_hasOwn","call","props","proto","getProto","setProp","functionOrGetSet","options","defineProperty","get","set","configurable","value","writable","derive","Child","from","Parent","prototype","Object","create","bind","getPropertyDescriptor","pd","getOwnPropertyDescriptor","slice","args","start","end","_slice","override","origFunc","overridedFactory","assert","b","Error","asap","fn","_global","setImmediate","setTimeout","arrayToObject","array","extractor","reduce","result","item","i","nameAndValue","trycatcher","reject","apply","this","arguments","e","tryCatch","onerror","ex","getByKeyPath","keyPath","rv","l","length","val","push","period","indexOf","innerObj","substr","undefined","setByKeyPath","isFrozen","currentKeyPath","remainingKeyPath","delByKeyPath","map","kp","shallowClone","m","flatten","a","concat","deepClone","any","isArray","intrinsicTypes","constructor","getObjectDiff","prfx","ap","bp","getArrayOf","arrayLike","x","it","NO_CHAR_ARRAY","getIteratorOf","next","done","Array","setDebug","filter","debug","libraryFilter","getErrorWithStack","NEEDS_THROW_FOR_STACK","prettyStack","exception","numIgnoredFrames","stack","name","message","split","frame","join","deprecated","what","console","warn","DexieError","msg","_e","getMultiErrorMessage","failures","f","toString","v","s","ModifyError","successCount","failedKeys","BulkError","mapError","domError","TypeError","SyntaxError","exceptionMap","inner","mirror","pureFunctionChain","f1","f2","callBoth","on1","on2","hookCreatingChain","nop","res","onsuccess","res2","hookDeletingChain","hookUpdatingChain","modifications","reverseStoppableEventChain","promisableChain","then","thiz","Promise","_listeners","onuncatched","_lib","psd","_PSD","PSD","_stackHolder","_prev","_numPrev","INTERNAL","_state","_value","handleRejection","ref","executePromiseTask","Listener","onFulfilled","onRejected","resolve","zone","promise","shouldExecuteTick","beginMicroTickScope","_then","propagateAllListeners","endMicroTickScope","reason","rejectingErrors","rejectionMapper","_promise","origProp","stack_being_generated","addPossiblyUnhandledError","listeners","len","propagateToListener","finalize","numScheduledCalls","finalizePhysicalTick","listener","cb","callListener","currentFulfiller","ret","markErrorAsHandled","getStack","stacks","limit","errorName","failure","linkToPreviousPromise","prev","numPrev","LONG_STACKS_CLIP_LIMIT","physicalTick","wasRootExec","isOutsideMicroTick","needsNewPhysicalTick","callbacks","microtickQueue","unhandledErrs","unhandledErrors","p","onunhandled","finalizers","tickFinalizers","run_at_end_of_this_or_next_physical_tick","finalizer","splice","some","PromiseReject","wrap","errorCatcher","outerScope","switchToZone","newScope","a1","a2","parent","global","id","zone_id_counter","globalEnv","globalPSD","env","patchGlobalPromise","PromiseProp","all","race","nthen","getPatchedPromiseThen","gthen","usePSD","incrementExpectedAwaits","task","taskCounter","awaits","echoes","ZONE_ECHO_LIMIT","decrementExpectedAwaits","sourceTaskId","onPossibleParallellAsync","possiblePromise","NativePromise","rejection","zoneEnterEcho","targetZone","totalEchoes","zoneStack","zoneLeaveEcho","pop","bEnteringZone","currentZone","zoneEchoes","enqueueNativeMicroTask","snapShot","GlobalPromise","targetEnv","nativePromiseProto","a3","job","nativePromiseThen","resolvedNativePromise","nativeAwaitCompatibleWrap","possibleAwait","outerZone","origThen","onResolved","globalError","err","event","eventData","document","createEvent","initEvent","UNHANDLEDREJECTION","CustomEvent","detail","dispatchEvent","PromiseRejectionEvent","onunhandledrejection","_","defaultPrevented","ctx","add","eventName","chainFunction","defaultFunction","addConfiguredEvents","context","subscribers","fire","subscribe","unsubscribe","evs","cfg","exceptions","InvalidArgument","subscriber","addEventType","Dexie","dbName","Version","versionNumber","_cfg","version","storesSource","dbschema","tables","contentUpgrade","stores","runUpgraders","oldVersion","idbtrans","trans","db","_createTransaction","READWRITE","dbStoreNames","globalSchema","_completion","catch","rejectTransaction","_reject","tableName","createTable","primKey","indexes","follow","on","populate","updateTablesAndIndexes","runQueue","queue","shift","oldVersionStruct","versions","Upgrade","_dbSchema","anyContentUpgraderHasRun","oldSchema","newSchema","adjustToExistingIndexNames","diff","getSchemaDiff","tuple","change","recreate","store","objectStore","idx","addIndex","deleteIndex","del","idxName","hasIEDeleteObjectStoreBug","deleteRemovedTables","createMissingTables","table","oldDef","newDef","def","src","oldIndexes","idxByName","newIndexes","oldIdx","newIdx","createObjectStore","autoIncrement","auto","objectStoreNames","contains","storeName","deleteObjectStore","createIndex","unique","multiEntry","multi","tempTransaction","mode","storeNames","openComplete","letThrough","isBeingOpened","autoOpen","DatabaseClosed","open","dbReadyPromise","extractTransactionArgs","_tableArgs_","scopeFunc","Table","tableSchema","optionalTrans","schema","_tx","hook","allTables","Events","creating","reading","updating","deleting","BulkErrorHandlerCatchAll","errorList","supportHooks","hookedEventRejectHandler","eventRejectHandler","bulkDelete","idbstore","keysOrTuples","hasDeleteHook","deletingHook","lastItem","hookCtx","errorHandler","successHandler","hookedEventSuccessHandler","req","delete","_hookCtx","Transaction","_this","active","_reculock","_blockedFuncs","_resolve","_waitingFor","_waitingQueue","_spinCount","complete","wasActive","error","abort","WhereClause","index","orCollection","_ctx","or","Collection","whereClause","keyRangeGenerator","keyRange","whereCtx","isPrimKey","range","keysOnly","dir","algorithm","replayFilter","justLimit","isMatch","offset","Infinity","valueMapper","isPlainKeyRange","ignoreLimitFilter","lowerVersionFirst","setApiOnPlace","objs","tableNames","removeTablesApi","iterate","mappedFn","c","wrappedFn","cursor","continue","advancer","parseIndexSyntax","trim","replace","test","match","IndexSpec","cmp","key1","key2","indexedDB","min","max","ascending","descending","simpleCompare","simpleCompareReverse","combine","filter1","filter2","readGlobalSchema","verno","idbdb","transaction","safariMultiStoreFix","dotted","j","indexNames","idbindex","TableSchema","hasGetAll","indexName","dexieName","indexSpec","navigator","userAgent","WorkerGlobalScope","fireOnBlocked","ev","connections","_vcFired","dbReadyResolve","cancelOpen","deps","dependencies","opts","addons","IDBKeyRange","dbOpenError","onReadyBeingFired","openCanceller","autoSchema","hasNativeGetDatabaseNames","getNativeGetDatabaseNamesFn","Schema","Math","versionInstance","sort","storesSpec","_parseStoresSpec","upgrade","upgradeFunction","outSchema","instanceTemplate","compound","_allTables","parentTransaction","_whenReady","Debug.debug","Debug.getErrorWithStack","resolveDbReady","upgradeTransaction","MissingAPI","round","onblocked","onupgradeneeded","_allowEmptyDB","preventDefault","close","delreq","deleteDatabase","NoSuchDatabase","pow","onversionchange","dbNamesDB","dbnames","put","vip","ready","fireRemainders","remainders","finally","hasArguments","doDelete","backendDB","isOpen","hasBeenClosed","hasFailed","dynamicallyOpened","bSticky","_transaction","enterTransactionScope","transless","zoneProps","AsyncFunction","returnValue","promiseFollowed","decrementor","throw","awaitIterator","PrematureCommit","onlyIfCompatible","SubTransaction","InvalidTable","_trans","writeLocked","_idbstore","supplyIdbStore","NotFound","keyOrCrit","where","first","self","indexOrCrit","keyPaths","equals","compoundIndex","ix","every","maxKey","maxString","JSON","stringify","simpleIndex","r","count","toCollection","numRows","reverse","filterFunction","and","each","toArray","orderBy","mapToClass","structure","mappedClass","applyStructure","readHook","defineClass","anyOf","bulkPut","objects","numObjs","eventSuccessHandler","effectiveKeys","o","objectLookup","modify","objsToAdd","keysToAdd","bulkAdd","lastAddedKey","lastEffectiveKey","creatingHook","effectiveKey","keyToUse","updatingHook","target","clear","update","keyOrObject","_lock","lockOwnerFor","_unlock","_locked","fnAndPSD","OpenFailed","TransactionInactive","onabort","Abort","oncomplete","bWriteLock","ReadOnly","_root","waitFor","root","spin","currentWaitPromise","Debug.deprecated","fail","collectionOrWhereClause","T","collection","emptyCollection","only","upperFactory","toUpperCase","toLowerCase","lowerFactory","nextCasing","lowerKey","upperNeedle","lowerNeedle","llp","lwrKeyChar","addIgnoreCaseAlgorithm","needles","suffix","initDirection","upper","lower","compare","needleBounds","needle","upperNeedles","nb","lowerNeedles","direction","nextKeySuffix","needlesLen","STRING_EXPECTED","bound","_ondirectionchange","firstPossibleNeedle","_addAlgorithm","advance","lowestPossibleCasing","casing","between","includeLower","includeUpper","INVALID_KEY_ARGUMENT","above","lowerBound","aboveOrEqual","below","upperBound","belowOrEqual","startsWith","str","startsWithIgnoreCase","equalsIgnoreCase","anyOfIgnoreCase","startsWithAnyOfIgnoreCase","n","notEqual","inAnyRange","minKey","includeLowers","includeUppers","noneOf","ranges","addRange","newRange","rangeSorter","sortDirection","keyWithinCurrentRange","keyIsBeyondCurrentEntry","keyIsBeforeCurrentEntry","checkKey","startsWithAnyOf","addFilter","addReplayFilter","factory","isLimitFilter","curr","addMatchFilter","getIndexOrStore","openCursor","idxOrStore","openKeyCursor","iter","resolveboth","resolved","union","primaryKey","Uint8Array","_iterate","_read","_write","clone","raw","sortBy","getval","parts","lastPart","sorter","aVal","lastIndex","bVal","order","readingHook","getAll","offsetLeft","rowsLeft","until","bIncludeStopEntry","last","desc","eachKey","eachUniqueKey","eachPrimaryKey","primaryKeys","getAllKeys","uniqueKeys","firstKey","lastKey","distinct","strKey","found","changes","modifyItem","failKeys","thisContext","checkFinished","currentKey","modifyer","bDelete","doReject","iterationComplete","origItem","objectDiff","additionalChanges","numKeys","anythingModified","origChanges","hangsOnDeleteLargeKeyRange","countReq","delReq","CHUNKSIZE","totalCount","nextChunk","newVersion","parseType","type","member","hookSuccessHandler","hookErrorHandler","stopPropagation","iterator","step","getNext","onSuccess","onError","callNext","doThrow","keyPathSrc","getDatabaseNames","webkitGetDatabaseNames","window","getPrototypeOf","hasOwnProperty","num","t","iteratorSymbol","Symbol","location","href","dexieErrorNames","idbDomErrorNames","defaultTexts","VersionChanged","_stack","errnames","BaseException","msgOrInner","fullName","Syntax","Type","Range","RangeError","fullNameExceptions","nativePromiseInstanceAndProto","Function","P","resolvedGlobalPromise","schedulePhysicalTick","MutationObserver","hiddenDiv","createElement","observe","attributes","setAttribute","callback","unhandleds","pgp","uh","thenProp","microTaskId","handler","onFinally","timeout","ms","handle","Timeout","clearTimeout","toStringTag","values","remaining","newPSD","scheduler","DEXIE_VERSION","String","fromCharCode","isIEOrEdge","dexieStackFrameFilter","Debug.setDebug","databaseName","exists","NoSuchDatabaseError","Class","properties","ignoreTransaction","async","generatorFn","spawn","currentTransaction","promiseOrFunction","optionalTimeout","MultiModifyError","Modify","mozIndexedDB","webkitIndexedDB","msIndexedDB","webkitIDBKeyRange","semVer","parseInt","default","localStorage","parse","getItem","removeItem"],"mappings":"gLAOA,SAAAA,GAAuBC,EAAKC,GACxB,MAAyB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AmBx2B,GAAQy2B,YAC3FzX,YAAahf,GAAQgf,aAAehf,GAAQ02B,mBAIhDC,OAAQxB,GACRtjB,QAASsjB,GAAczwB,MAAM,KACxBrC,IAAI,SAAAipB,GAAK,MAAAsL,UAAStL,KAClBhrB,OAAO,SAACgL,EAAEuQ,EAAEpb,GAAM,MAAA6K,GAAKuQ,EAAE2D,KAAK2B,IAAI,GAAK,EAAF1gB,KAK1Co2B,QAASrlB,GAMTA,MAAOA,KAIXjK,EAAQ6B,gBAAkBtD,EAG1Bub,GAAY,GAAI7P,IAAM,aACtB6P,GAAUxP,QAAQ,GAAGK,QAAQoP,QAAS,SAEtC,WAGI,OAA4Bvf,WAAjB+0B,mBAAmD/0B,KAArB/B,GAAQ4P,SAAwB,IAErEwU,KAAK2S,MAAMD,aAAaE,QAHd,wBAGkC,MACvC15B,QAAQ,SAAAkH,GAAQ,MAAA6c,IAAUC,QAAQC,KAAK/c,KAAMA,IAAOqO,MAAMjM,KAC/DkwB,aAAaG,WALH,uBAMZ,MAAO9xB","file":"dexie.min.js","sourcesContent":["export var keys = Object.keys;\nexport var isArray = Array.isArray;\nexport var _global =\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n\nexport function extend(obj, extension) {\n if (typeof extension !== 'object') return obj;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n keys(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n var pd = getOwnPropertyDescriptor(obj, prop),\n proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nvar _slice = [].slice;\nexport function slice(args, start, end) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array, extractor) {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn, onerror, args) {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a) {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nvar intrinsicTypes =\n \"Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]).map(t=>_global[t])\n\nexport function deepClone(any) {\n if (!any || typeof any !== 'object') return any;\n var rv;\n if (isArray(any)) {\n rv = [];\n for (var i = 0, l = any.length; i < l; ++i) {\n rv.push(deepClone(any[i]));\n }\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\n rv = any;\n } else {\n rv = any.constructor ? Object.create(any.constructor.prototype) : {};\n for (var prop in any) {\n if (hasOwn(any, prop)) {\n rv[prop] = deepClone(any[prop]);\n }\n }\n }\n return rv;\n}\n\nexport function getObjectDiff(a, b, rv, prfx) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach(prop => {\n if (!hasOwn(b, prop))\n rv[prfx+prop] = undefined; // Property removed\n else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' &&\n ap && bp &&\n // Now compare constructors are same (not equal because wont work in Safari)\n (''+ap.constructor) === (''+bp.constructor))\n // Same type of object but its properties may have changed\n getObjectDiff (ap, bp, rv, prfx + prop + \".\");\n else if (ap !== bp)\n rv[prfx + prop] = b[prop];// Primitive value changed\n }\n });\n keys(b).forEach(prop => {\n if (!hasOwn(a, prop)) {\n rv[prfx+prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\nexport const getIteratorOf = iteratorSymbol ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch(e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\nexport function deprecated (what, fn) {\n return function () {\n console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n }\n}\n","import { derive, setProp } from './utils';\nimport { getErrorWithStack, prettyStack } from './debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function() {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + failures\n .map(f=>f.toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = failures;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = msgOrInner;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport {tryCatch, props, setProp, _global,\n getPropertyDescriptor, getArrayOf, extend} from './utils';\nimport {nop, callBoth, mirror} from './chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from './errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 7,\n nativePromiseInstanceAndProto = (()=>{\n try {\n // Be able to patch native async functions\n return new Function(`let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];`)();\n } catch(e) {\n var P = _global.Promise;\n return P ?\n [P.resolve(), P.prototype, P.resolve()] :\n []; \n }\n })(),\n resolvedNativePromise = nativePromiseInstanceAndProto[0],\n nativePromiseProto = nativePromiseInstanceAndProto[1],\n resolvedGlobalPromise = nativePromiseInstanceAndProto[2],\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nexport const AsyncFunction = nativePromiseInstanceAndProto[3];\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nvar schedulePhysicalTick = resolvedGlobalPromise ?\n () => {resolvedGlobalPromise.then(physicalTick);}\n :\n _global.setImmediate ? \n // setImmediate supported. Those modern platforms also supports Function.bind().\n setImmediate.bind(null, physicalTick) :\n _global.MutationObserver ?\n // MutationObserver supported\n () => {\n var hiddenDiv = document.createElement(\"div\");\n (new MutationObserver(() => {\n physicalTick();\n hiddenDiv = null;\n })).observe(hiddenDiv, { attributes: true });\n hiddenDiv.setAttribute('i', '1');\n } :\n // No support for setImmediate or MutationObserver. No worry, setTimeout is only called\n // once time. Every tick that follows will be our emulated micro tick.\n // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \n ()=>{setTimeout(physicalTick,0);};\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: globalError,\n pgp: false,\n env: {},\n finalize: function () {\n this.unhandleds.forEach(uh => {\n try {\n globalError(uh[0], uh[1]);\n } catch (e) {}\n });\n }\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n }\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n if (possibleAwait) decrementExpectedAwaits();\n var rv = new Promise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(Promise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n \n stack: {\n get: function() {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack (this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new Promise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(Promise.prototype, Symbol.toStringTag, 'Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (Promise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new Promise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => Promise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof Promise) return value;\n if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new Promise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new Promise((resolve, reject) => {\n values.map(value => Promise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n //totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new Promise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof Promise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n \n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\nfunction getStack (promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n \n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with setImmediate() or setTimeout().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n beginMicroTickScope() && endMicroTickScope();\n}\n\nfunction beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nfunction endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new Promise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: Promise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: Promise, configurable: true, writable: true},\n all: Promise.all,\n race: Promise.race,\n resolve: Promise.resolve,\n reject: Promise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits(sourceTaskId) {\n if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) return;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction enqueueNativeMicroTask (job) {\n //\n // Precondition: nativePromiseThen !== undefined\n //\n nativePromiseThen.call(resolvedNativePromise, job);\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone, false),\n nativeAwaitCompatibleWrap(onRejected, zone, false));\n };\n}\n\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\n\nfunction globalError(err, promise) {\n var rv;\n try {\n rv = promise.onuncatched(err);\n } catch (e) {}\n if (rv !== false) try {\n var event, eventData = {promise: promise, reason: err};\n if (_global.document && document.createEvent) {\n event = document.createEvent('Event');\n event.initEvent(UNHANDLEDREJECTION, true, true);\n extend(event, eventData);\n } else if (_global.CustomEvent) {\n event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData});\n extend(event, eventData);\n }\n if (event && _global.dispatchEvent) {\n dispatchEvent(event);\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\n try {_global.onunhandledrejection(event);} catch (_) {}\n }\n if (!event.defaultPrevented) {\n console.warn(`Unhandled rejection: ${err.stack || err}`);\n }\n } catch (e) {}\n}\n\nexport var rejection = Promise.reject;\n","import {keys, isArray, asap} from './utils';\nimport {nop, mirror, reverseStoppableEventChain} from './chaining-functions';\nimport {exceptions} from './errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","/*\n * Dexie.js - a minimalistic wrapper for IndexedDB\n * ===============================================\n *\n * Copyright (c) 2014-2017 David Fahlander\n *\n * Version {version}, {date}\n *\n * http://dexie.org\n * \n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n * \n */\n\nimport {\n keys,\n setProp,\n isArray,\n extend,\n props,\n derive,\n slice,\n override,\n _global,\n asap,\n trycatcher,\n tryCatch,\n getByKeyPath,\n setByKeyPath,\n delByKeyPath,\n shallowClone,\n deepClone,\n getObjectDiff,\n assert,\n NO_CHAR_ARRAY,\n getArrayOf,\n arrayToObject,\n hasOwn,\n flatten\n} from './utils';\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\nimport Promise, {wrap, PSD, newScope, usePSD, rejection, NativePromise,\n incrementExpectedAwaits, decrementExpectedAwaits, AsyncFunction} from './Promise';\nimport Events from './Events';\nimport {\n nop,\n mirror,\n pureFunctionChain,\n hookCreatingChain,\n hookUpdatingChain,\n hookDeletingChain,\n promisableChain\n} from './chaining-functions';\nimport * as Debug from './debug';\n\nvar DEXIE_VERSION = '{version}',\n maxString = String.fromCharCode(65535),\n // maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\n // Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\n maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(),\n minKey = -Infinity,\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\n STRING_EXPECTED = \"String expected.\",\n connections = [],\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\n hasIEDeleteObjectStoreBug = isIEOrEdge,\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\n dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame),\n dbNamesDB;// Global database for backing Dexie.getDatabaseNames() on browser without indexedDB.webkitGetDatabaseNames() \n\n// Init debug\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport default function Dexie(dbName, options) {\n /// Specify only if you wich to control which addons that should run on this instance\n var deps = Dexie.dependencies;\n var opts = extend({\n // Default Options\n addons: Dexie.addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to browser env.\n }, options);\n var addons = opts.addons,\n autoOpen = opts.autoOpen,\n indexedDB = opts.indexedDB,\n IDBKeyRange = opts.IDBKeyRange;\n\n var globalSchema = this._dbSchema = {};\n var versions = [];\n var dbStoreNames = [];\n var allTables = {};\n ///\n var idbdb = null; // Instance of IDBDatabase\n var dbOpenError = null;\n var isBeingOpened = false;\n var onReadyBeingFired = null;\n var openComplete = false;\n var READONLY = \"readonly\", READWRITE = \"readwrite\";\n var db = this;\n var dbReadyResolve,\n dbReadyPromise = new Promise(resolve => {\n dbReadyResolve = resolve;\n }),\n cancelOpen,\n openCanceller = new Promise((_, reject) => {\n cancelOpen = reject;\n });\n var autoSchema = true;\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\n hasGetAll;\n\n function init() {\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n db.on(\"versionchange\", function (ev) {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`);\n db.close();\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n db.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${db.name}') was blocked`);\n else\n console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`);\n });\n }\n\n //\n //\n //\n // ------------------------- Versioning Framework---------------------------\n //\n //\n //\n\n this.version = function (versionNumber) {\n /// \n /// \n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];\n if (versionInstance) return versionInstance;\n versionInstance = new Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n // Disable autoschema mode, as at least one version is specified.\n autoSchema = false;\n return versionInstance;\n };\n\n function Version(versionNumber) {\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n this.stores({}); // Derive earlier schemas by default.\n }\n\n extend(Version.prototype, {\n stores: function (stores) {\n /// \n /// Defines the schema for a particular version\n /// \n /// \n /// Example:
\n /// {users: \"id++,first,last,&username,*email\",
\n /// passwords: \"id++,&username\"}
\n ///
\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

\n /// Special characters:
\n /// \"&\" means unique key,
\n /// \"*\" means value is multiEntry,
\n /// \"++\" means auto-increment and only applicable for primary key
\n /// \n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n var storesSpec = {};\n versions.forEach(function (version) { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n });\n\n var dbschema = (this._cfg.dbschema = {});\n this._parseStoresSpec(storesSpec, dbschema);\n // Update the latest schema to this version\n // Update API\n globalSchema = db._dbSchema = dbschema;\n removeTablesApi([allTables, db, Transaction.prototype]); // Keep Transaction.prototype even though it should be depr.\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n dbStoreNames = keys(dbschema);\n return this;\n },\n upgrade: function (upgradeFunction) {\n /// Function that performs upgrading actions.\n var self = this;\n this._cfg.contentUpgrade = upgradeFunction;\n return this;\n },\n _parseStoresSpec: function (stores, outSchema) {\n keys(stores).forEach(function (tableName) {\n if (stores[tableName] !== null) {\n var instanceTemplate = {};\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\n indexes.forEach(function (idx) {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return \"\"; }) : \"\");\n });\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\n }\n });\n }\n });\n \n function runUpgraders (oldVersion, idbtrans, reject) {\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\n trans.create(idbtrans);\n trans._completion.catch(reject);\n var rejectTransaction = trans._reject.bind(trans);\n newScope(function () {\n PSD.trans = trans;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(function (tableName) {\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\n });\n }\n\n function updateTablesAndIndexes (oldVersion, trans, idbtrans) {\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n var queue = [];\n var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0];\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\n var anyContentUpgraderHasRun = false;\n\n var versToRun = versions.filter(v => v._cfg.version > oldVersion);\n versToRun.forEach(function (version) {\n /// \n queue.push(()=>{\n var oldSchema = globalSchema;\n var newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(oldSchema, idbtrans);\n adjustToExistingIndexNames(newSchema, idbtrans);\n globalSchema = db._dbSchema = newSchema;\n var diff = getSchemaDiff(oldSchema, newSchema); \n // Add tables \n diff.add.forEach(function (tuple) {\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(function (change) {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n var store = idbtrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(function (idx) {\n addIndex(store, idx);\n });\n // Update indexes\n change.change.forEach(function (idx) {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(function (idxName) {\n store.deleteIndex(idxName);\n });\n }\n });\n if (version._cfg.contentUpgrade) {\n anyContentUpgraderHasRun = true;\n return Promise.follow(()=>{\n version._cfg.contentUpgrade(trans);\n });\n }\n });\n queue.push(function (idbtrans) {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n var newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n });\n });\n\n // Now, create a queue execution engine\n function runQueue () {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n \n return runQueue().then(()=>{\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n }\n\n function getSchemaDiff(oldSchema, newSchema) {\n var diff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n for (var table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n var oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n var change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (oldDef.primKey.src !== newDef.primKey.src) {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n var oldIndexes = oldDef.idxByName;\n var newIndexes = newDef.idxByName;\n for (var idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n var oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n }\n\n function createTable(idbtrans, tableName, primKey, indexes) {\n /// \n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\n indexes.forEach(function (idx) { addIndex(store, idx); });\n return store;\n }\n\n function createMissingTables(newSchema, idbtrans) {\n keys(newSchema).forEach(function (tableName) {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n }\n\n function deleteRemovedTables(newSchema, idbtrans) {\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\n var storeName = idbtrans.db.objectStoreNames[i];\n if (newSchema[storeName] == null) {\n idbtrans.db.deleteObjectStore(storeName);\n }\n }\n }\n\n function addIndex(store, idx) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n }\n\n //\n //\n // Dexie Protected API\n //\n //\n\n this._allTables = allTables;\n\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\n };\n\n /* Generate a temporary transaction when db operations are done outside a transaction scope.\n */\n function tempTransaction(mode, storeNames, fn) { // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n if (!openComplete && (!PSD.letThrough)) {\n if (!isBeingOpened) {\n if (!autoOpen)\n return rejection (new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, globalSchema);\n try { trans.create(); } catch (ex) { return rejection(ex); }\n return trans._promise(mode, function (resolve, reject) {\n return newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n return trans._completion.then(()=>result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n }\n\n this._whenReady = function (fn) {\n return openComplete || PSD.letThrough ? fn() : new Promise ((resolve, reject) => {\n if (!isBeingOpened) {\n if (!autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n dbReadyPromise.then(resolve, reject);\n }).then(fn);\n };\n \n //\n //\n //\n //\n // Dexie API\n //\n //\n //\n\n this.verno = 0;\n\n this.open = function () {\n if (isBeingOpened || idbdb)\n return dbReadyPromise.then(()=> dbOpenError ? rejection (dbOpenError) : db);\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n isBeingOpened = true;\n dbOpenError = null;\n openComplete = false;\n \n // Function pointers to call when the core opening process completes.\n var resolveDbReady = dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction = null;\n \n return Promise.race([openCanceller, new Promise((resolve, reject) => {\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n \n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI(\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\n \n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(\"IndexedDB API not available\"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(fireOnBlocked);\n req.onupgradeneeded = wrap (function (e) {\n upgradeTransaction = req.transaction;\n if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(function () {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\n }\n }, reject);\n \n req.onsuccess = wrap (function () {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n idbdb = req.result;\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n\n if (autoSchema) readGlobalSchema();\n else if (idbdb.objectStoreNames.length > 0) {\n try {\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\n } catch (e) {\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n }\n }\n \n idbdb.onversionchange = wrap(ev => {\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n if (!hasNativeGetDatabaseNames && dbName !== '__dbnames') {\n dbNamesDB.dbnames.put({name: dbName}).catch(nop);\n }\n\n resolve();\n\n }, reject);\n })]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n onReadyBeingFired = [];\n return Promise.resolve(Dexie.vip(db.on.ready.fire)).then(function fireRemainders() {\n if (onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = onReadyBeingFired.reduce(promisableChain, nop);\n onReadyBeingFired = [];\n return Promise.resolve(Dexie.vip(remainders)).then(fireRemainders)\n }\n });\n }).finally(()=>{\n onReadyBeingFired = null;\n }).then(()=>{\n // Resolve the db.open() with the db instance.\n isBeingOpened = false;\n return db;\n }).catch(err => {\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch (e) { }\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n // A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n return rejection (dbOpenError);\n }).finally(()=>{\n openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n });\n };\n \n this.close = function () {\n var idx = connections.indexOf(db);\n if (idx >= 0) connections.splice(idx, 1); \n if (idbdb) {\n try {idbdb.close();} catch(e){}\n idbdb = null;\n }\n autoOpen = false;\n dbOpenError = new exceptions.DatabaseClosed();\n if (isBeingOpened)\n cancelOpen(dbOpenError);\n // Reset dbReadyPromise promise:\n dbReadyPromise = new Promise(resolve => {\n dbReadyResolve = resolve;\n });\n openCanceller = new Promise((_, reject) => {\n cancelOpen = reject;\n });\n };\n \n this.delete = function () {\n var hasArguments = arguments.length > 0;\n return new Promise(function (resolve, reject) {\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (isBeingOpened) {\n dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n function doDelete() {\n db.close();\n var req = indexedDB.deleteDatabase(dbName);\n req.onsuccess = wrap(function () {\n if (!hasNativeGetDatabaseNames) {\n dbNamesDB.dbnames.delete(dbName).catch(nop);\n }\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = fireOnBlocked;\n }\n });\n };\n\n this.backendDB = function () {\n return idbdb;\n };\n\n this.isOpen = function () {\n return idbdb !== null;\n };\n this.hasBeenClosed = function () {\n return dbOpenError && (dbOpenError instanceof exceptions.DatabaseClosed);\n }\n this.hasFailed = function () {\n return dbOpenError !== null;\n };\n this.dynamicallyOpened = function() {\n return autoSchema;\n };\n\n //\n // Properties\n //\n this.name = dbName;\n\n // db.tables - an array of all Table instances.\n props(this, {\n tables: {\n get () {\n /// \n return keys(allTables).map(function (name) { return allTables[name]; });\n }\n }\n });\n\n //\n // Events\n //\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", {ready: [promisableChain, nop]});\n\n this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) {\n return (subscriber, bSticky) => {\n Dexie.vip(()=>{\n if (openComplete) {\n // Database already open. Call subscriber asap.\n if (!dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n this.transaction = function () {\n /// \n ///\n /// \n /// \"r\" for readonly, or \"rw\" for readwrite\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\n /// Function to execute with transaction\n\n var args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n \n function extractTransactionArgs (mode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i-1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n }\n\n this._transaction = function (mode, tables, scopeFunc) {\n var parentTransaction = PSD.trans;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\n var onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n \n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n var storeNames = tables.map(table => {\n var storeName = table instanceof Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode == READONLY)\n mode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n mode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(function (storeName) {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n return (parentTransaction ?\n parentTransaction._promise(mode, enterTransactionScope, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>db._whenReady(enterTransactionScope)) :\n db._whenReady (enterTransactionScope));\n \n function enterTransactionScope() {\n return Promise.resolve().then(()=>{\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n var transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n var zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\n }\n\n // Support for native async await.\n if (scopeFunc.constructor === AsyncFunction) {\n incrementExpectedAwaits();\n }\n\n var returnValue;\n var promiseFollowed = Promise.follow(()=>{\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (returnValue.constructor === NativePromise) {\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(()=>returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(()=>x);\n }).catch (e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n }\n };\n\n this.table = function (tableName) {\n /// \n if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return allTables[tableName];\n };\n\n //\n //\n //\n // Table Class\n //\n //\n //\n function Table(name, tableSchema, optionalTrans) {\n /// \n this.name = name;\n this.schema = tableSchema;\n this._tx = optionalTrans;\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n });\n }\n\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n }\n\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\n return new Promise((resolve, reject)=>{\n var len = keysOrTuples.length,\n lastItem = len - 1;\n if (len === 0) return resolve();\n if (!hasDeleteHook) {\n for (var i=0; i < len; ++i) {\n var req = idbstore.delete(keysOrTuples[i]);\n req.onerror = eventRejectHandler(reject);\n if (i === lastItem) req.onsuccess = wrap(()=>resolve());\n }\n } else {\n var hookCtx,\n errorHandler = hookedEventRejectHandler(reject),\n successHandler = hookedEventSuccessHandler(null);\n tryCatch(()=> {\n for (var i = 0; i < len; ++i) {\n hookCtx = {onsuccess: null, onerror: null};\n var tuple = keysOrTuples[i];\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\n var req = idbstore.delete(tuple[0]);\n req._hookCtx = hookCtx;\n req.onerror = errorHandler;\n if (i === lastItem)\n req.onsuccess = hookedEventSuccessHandler(resolve);\n else\n req.onsuccess = successHandler;\n }\n }, err=>{\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n }\n });\n } \n\n props(Table.prototype, {\n\n //\n // Table Protected Methods\n //\n\n _trans: function getTransaction(mode, fn, writeLocked) {\n var trans = this._tx || PSD.trans;\n return trans && trans.db === db ?\n trans === PSD.trans ?\n trans._promise (mode, fn, writeLocked) :\n newScope(()=>trans._promise(mode, fn, writeLocked), {trans: trans, transless: PSD.transless || PSD}) :\n tempTransaction (mode, [this.name], fn);\n },\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\n var tableName = this.name;\n function supplyIdbStore (resolve, reject, trans) {\n if (trans.storeNames.indexOf(tableName) === -1)\n throw new exceptions.NotFound(\"Table\" + tableName + \" not part of transaction\");\n return fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\n }\n return this._trans(mode, supplyIdbStore, writeLocked);\n },\n\n //\n // Table Public Methods\n //\n get: function (keyOrCrit, cb) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit).first(cb);\n var self = this;\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\n var req = idbstore.get(keyOrCrit);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(self.hook.reading.fire(req.result));\n }, reject);\n }).then(cb);\n },\n where: function (indexOrCrit) {\n if (typeof indexOrCrit === 'string')\n return new WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n var keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n \n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix =>\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\n ix.keyPath.every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\n\n if (compoundIndex && maxKey !== maxString)\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n return this\n .where(compoundIndex.name)\n .equals(compoundIndex.keyPath.map(kp => indexOrCrit[kp]));\n\n if (!compoundIndex) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n \n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n var idxByName = this.schema.idxByName;\n var simpleIndex = keyPaths.reduce((r,keyPath)=>[\n r[0] || idxByName[keyPath],\n r[0] || !idxByName[keyPath] ?\n combine(\n r[1],\n x =>''+getByKeyPath(x, keyPath) ==\n ''+indexOrCrit[keyPath])\n : r[1]\n ], [null, null]);\n \n var idx = simpleIndex[0];\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(simpleIndex[1]) :\n compoundIndex ?\n this.filter(simpleIndex[1]) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily.\n },\n count: function (cb) {\n return this.toCollection().count(cb);\n },\n offset: function (offset) {\n return this.toCollection().offset(offset);\n },\n limit: function (numRows) {\n return this.toCollection().limit(numRows);\n },\n reverse: function () {\n return this.toCollection().reverse();\n },\n filter: function (filterFunction) {\n return this.toCollection().and(filterFunction);\n },\n each: function (fn) {\n return this.toCollection().each(fn);\n },\n toArray: function (cb) {\n return this.toCollection().toArray(cb);\n },\n orderBy: function (index) {\n return new Collection(\n new WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n },\n\n toCollection: function () {\n return new Collection(new WhereClause(this));\n },\n\n mapToClass: function (constructor, structure) {\n /// \n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\n /// \n /// Constructor function representing the class.\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\n this.schema.mappedClass = constructor;\n var instanceTemplate = Object.create(constructor.prototype);\n if (structure) {\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\n applyStructure(instanceTemplate, structure);\n }\n this.schema.instanceTemplate = instanceTemplate;\n\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n var readHook = function (obj) {\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\n // Create a new object that derives from constructor:\n var res = Object.create(constructor.prototype);\n // Clone members:\n for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){}\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n },\n defineClass: function (structure) {\n /// \n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\n /// as well as making it possible to extend the prototype of the returned constructor function.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n return this.mapToClass(Dexie.defineClass(structure), structure);\n },\n\n bulkDelete: function (keys) {\n if (this.hook.deleting.fire === nop) {\n return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => {\n resolve (bulkDelete(idbstore, trans, keys, false, nop));\n });\n } else {\n return this\n .where(':id')\n .anyOf(keys)\n .delete()\n .then(()=>{}); // Resolve with undefined.\n }\n },\n bulkPut: function(objects, keys) {\n return this._idbstore(READWRITE, (resolve, reject, idbstore) => {\n if (!idbstore.keyPath && !this.schema.primKey.auto && !keys)\n throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n const done = result => {\n if (errorList.length === 0) resolve(result);\n else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList));\n };\n var req,\n errorList = [],\n errorHandler,\n numObjs = objects.length,\n table = this;\n if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) {\n //\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n } else {\n var effectiveKeys = keys || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath));\n // Generate map of {[key]: object}\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); \n var promise = !effectiveKeys ?\n\n // Auto-incremented key-less objects only without any keys argument.\n table.bulkAdd(objects) :\n\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\n // Begin with updating those that exists in DB:\n table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () {\n this.value = objectLookup[this.primKey];\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\n }).catch(ModifyError, e => {\n errorList = e.failures; // No need to concat here. These are the first errors added.\n }).then(()=> {\n // Now, let's examine which items didnt exist so we can add them:\n var objsToAdd = [],\n keysToAdd = keys && [];\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\n for (var i=effectiveKeys.length-1; i>=0; --i) {\n var key = effectiveKeys[i];\n if (key == null || objectLookup[key]) {\n objsToAdd.push(objects[i]);\n keys && keysToAdd.push(key);\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\n }\n }\n // The items are in reverse order so reverse them before adding.\n // Could be important in order to get auto-incremented keys the way the caller\n // would expect. Could have used unshift instead of push()/reverse(),\n // but: http://jsperf.com/unshift-vs-reverse\n objsToAdd.reverse();\n keys && keysToAdd.reverse();\n return table.bulkAdd(objsToAdd, keysToAdd);\n }).then(lastAddedKey => {\n // Resolve with key of the last object in given arguments to bulkPut():\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\n });\n\n promise.then(done).catch(BulkError, e => {\n // Concat failure from ModifyError and reject using our 'done' method.\n errorList = errorList.concat(e.failures);\n done();\n }).catch(reject);\n }\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\n },\n bulkAdd: function(objects, keys) {\n var self = this,\n creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys)\n throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\n if (idbstore.keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n if (objects.length === 0) return resolve(); // Caller provided empty list.\n function done(result) {\n if (errorList.length === 0) resolve(result);\n else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList));\n }\n var req,\n errorList = [],\n errorHandler,\n successHandler,\n numObjs = objects.length;\n if (creatingHook !== nop) {\n //\n // There are subscribers to hook('creating')\n // Must behave as documented.\n //\n var keyPath = idbstore.keyPath,\n hookCtx;\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\n successHandler = hookedEventSuccessHandler(null);\n\n tryCatch(() => {\n for (var i=0, l = objects.length; i < l; ++i) {\n hookCtx = { onerror: null, onsuccess: null };\n var key = keys && keys[i];\n var obj = objects[i],\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\n if (effectiveKey == null && keyToUse != null) {\n if (keyPath) {\n obj = deepClone(obj);\n setByKeyPath(obj, keyPath, keyToUse);\n } else {\n key = keyToUse;\n }\n }\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n if (i < l - 1) {\n req.onerror = errorHandler;\n if (hookCtx.onsuccess)\n req.onsuccess = successHandler;\n }\n }\n }, err => {\n hookCtx.onerror && hookCtx.onerror(err);\n throw err;\n });\n\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\n req.onsuccess = hookedEventSuccessHandler(done);\n } else {\n //\n // Standard Bulk (no 'creating' hook to care about)\n //\n errorHandler = BulkErrorHandlerCatchAll(errorList);\n for (var i = 0, l = objects.length; i < l; ++i) {\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\n req.onerror = errorHandler;\n }\n // Only need to catch success or error on the last operation\n // according to the IDB spec.\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\n req.onsuccess = eventSuccessHandler(done);\n }\n });\n },\n add: function (obj, key) {\n /// \n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\n /// \n /// A javascript object to insert\n /// Primary key\n var creatingHook = this.hook.creating.fire;\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\n var hookCtx = {onsuccess: null, onerror: null};\n if (creatingHook !== nop) {\n var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined);\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\n if (effectiveKey == null && keyToUse != null) { // Using \"==\" and \"!=\" to check for either null or undefined!\n if (idbstore.keyPath)\n setByKeyPath(obj, idbstore.keyPath, keyToUse);\n else\n key = keyToUse;\n }\n }\n try {\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\n req._hookCtx = hookCtx;\n req.onerror = hookedEventRejectHandler(reject);\n req.onsuccess = hookedEventSuccessHandler(function (result) {\n // TODO: Remove these two lines in next major release (2.0?)\n // It's no good practice to have side effects on provided parameters\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, result);\n resolve(result);\n });\n } catch (e) {\n if (hookCtx.onerror) hookCtx.onerror(e);\n throw e;\n }\n });\n },\n\n put: function (obj, key) {\n /// \n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\n /// \n /// A javascript object to insert or update\n /// Primary key\n var creatingHook = this.hook.creating.fire,\n updatingHook = this.hook.updating.fire;\n if (creatingHook !== nop || updatingHook !== nop) {\n //\n // People listens to when(\"creating\") or when(\"updating\") events!\n // We must know whether the put operation results in an CREATE or UPDATE.\n //\n var keyPath = this.schema.primKey.keyPath;\n var effectiveKey = (key !== undefined) ? key : (keyPath && getByKeyPath(obj, keyPath));\n if (effectiveKey == null) // \"== null\" means checking for either null or undefined.\n return this.add(obj);\n \n // Since key is optional, make sure we get it from obj if not provided\n \n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\n // clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.\n obj = deepClone(obj);\n return this._trans(READWRITE, () =>\n this.where(\":id\").equals(effectiveKey).modify(function () {\n // Replace extisting value with our object\n // CRUD event firing handled in Collection.modify()\n this.value = obj;\n }).then(count => count === 0 ? this.add(obj, key) : effectiveKey),\n \"locked\"); // Lock needed because operation is splitted into modify() and add().\n } else {\n // Use the standard IDB put() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function (ev) {\n var keyPath = idbstore.keyPath;\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\n resolve(req.result);\n });\n });\n }\n },\n\n 'delete': function (key) {\n /// Primary key of the object to delete\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\n // call the CRUD event. Only Collection.delete() will know whether an object was actually deleted.\n return this.where(\":id\").equals(key).delete();\n } else {\n // No one listens. Use standard IDB delete() method.\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.delete(key);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(req.result);\n });\n });\n }\n },\n\n clear: function () {\n if (this.hook.deleting.subscribers.length) {\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\n // call the CRUD event. Only Collection.delete() will knows which objects that are actually deleted.\n return this.toCollection().delete();\n } else {\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\n var req = idbstore.clear();\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(function () {\n resolve(req.result);\n });\n });\n }\n },\n\n update: function (keyOrObject, modifications) {\n if (typeof modifications !== 'object' || isArray(modifications))\n throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n // object to modify. Also modify given object with the modifications:\n keys(modifications).forEach(function (keyPath) {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection (new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n });\n \n //\n //\n //\n // Transaction Class\n //\n //\n //\n function Transaction(mode, storeNames, dbschema, parent) {\n /// \n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\n /// \n /// Any of \"readwrite\" or \"readonly\"\n /// Array of table names to operate on\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n }\n\n props(Transaction.prototype, {\n //\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n _lock: function () {\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n },\n _unlock: function () {\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n },\n _locked: function () {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n },\n create: function (idbtrans) {\n if (!this.mode) return this;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null);\n\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n });\n return this;\n },\n _promise: function (mode, fn, bWriteLock) {\n\n if (mode === READWRITE && this.mode !== READWRITE)\n return rejection (new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection (new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new Promise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(()=>{\n var p = new Promise((resolve, reject) => {\n this._lock();\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(()=>this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new Promise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n },\n\n _root: function () {\n return this.parent ? this.parent._root() : this;\n },\n\n waitFor (promise) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n promise = Promise.resolve(promise);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(()=>promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin(){\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new Promise ((resolve, reject) => {\n promise.then (\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n },\n\n //\n // Transaction Public Properties and Methods\n //\n abort: function () {\n this.active && this._reject(new exceptions.Abort());\n this.active = false;\n },\n\n tables: {\n get: Debug.deprecated (\"Transaction.tables\", ()=>allTables)\n },\n\n table: function (name) {\n var table = db.table(name); // Don't check that table is part of transaction. It must fail lazily!\n return new Table(name, table.schema, this);\n }\n });\n\n //\n //\n //\n // WhereClause\n //\n //\n //\n function WhereClause(table, index, orCollection) {\n /// \n /// \n /// \n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n }\n\n props(WhereClause.prototype, function () {\n\n // WhereClause private methods\n\n function fail(collectionOrWhereClause, err, T) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n }\n\n function emptyCollection(whereClause) {\n return new Collection (whereClause, function() { return IDBKeyRange.only(\"\"); }).limit(0);\n }\n\n function upperFactory(dir) {\n return dir === \"next\" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); };\n }\n function lowerFactory(dir) {\n return dir === \"next\" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); };\n }\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n }\n\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new Collection (whereClause, function() {\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix);\n });\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n }\n\n //\n // WhereClause public methods\n //\n return {\n between: function (lower, upper, includeLower, includeUpper) {\n /// \n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\n /// \n /// \n /// \n /// Whether items that equals lower should be included. Default true.\n /// Whether items that equals upper should be included. Default false.\n /// \n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((cmp(lower, upper) > 0) ||\n (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new Collection (this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); });\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n },\n equals: function (value) {\n return new Collection (this, function() { return IDBKeyRange.only(value); });\n },\n above: function (value) {\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value, true); });\n },\n aboveOrEqual: function (value) {\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value); });\n },\n below: function (value) {\n return new Collection (this, function() { return IDBKeyRange.upperBound(value, true); });\n },\n belowOrEqual: function (value) {\n return new Collection (this, function() { return IDBKeyRange.upperBound(value); });\n },\n startsWith: function (str) {\n /// \n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n },\n startsWithIgnoreCase: function (str) {\n /// \n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString);\n },\n equalsIgnoreCase: function (str) {\n /// \n return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], \"\");\n },\n anyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, \"\");\n },\n startsWithAnyOfIgnoreCase: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, function (x, a) {\n return a.some(function(n){\n return x.indexOf(n) === 0;\n });}, set, maxString);\n },\n anyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n var compare = ascending;\n try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n var c = new Collection (this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); });\n\n c._ondirectionchange = function (direction) {\n compare = (direction === \"next\" ? ascending : descending);\n set.sort(compare);\n };\n var i = 0;\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function () { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n },\n\n notEqual: function(value) {\n return this.inAnyRange([[minKey, value],[value, maxKey]], {includeLowers: false, includeUppers: false});\n },\n\n noneOf: function() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new Collection (this); // Return entire collection.\n try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);}\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; }, null);\n ranges.push([set[set.length - 1], maxKey]);\n return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false});\n },\n\n /** Filter out values withing given set of ranges.\n * Example, give children and elders a rebate of 50%:\n *\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\n *\n * @param {(string|number|Date|Array)[][]} ranges\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\n */\n inAnyRange: function (ranges, options) {\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) {\n return fail(this, \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\", exceptions.InvalidArgument);\n }\n var includeLowers = !options || options.includeLowers !== false; // Default to true\n var includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange (ranges, newRange) {\n for (var i=0,l=ranges.length;i 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n var sortDirection = ascending;\n function rangeSorter(a,b) { return sortDirection(a[0], b[0]);}\n\n // Join overlapping ranges\n var set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch(ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n var i = 0;\n var keyIsBeyondCurrentEntry = includeUppers ?\n function(key) { return ascending(key, set[i][1]) > 0; } :\n function(key) { return ascending(key, set[i][1]) >= 0; };\n\n var keyIsBeforeCurrentEntry = includeLowers ?\n function(key) { return descending(key, set[i][0]) > 0; } :\n function(key) { return descending(key, set[i][0]) >= 0; };\n\n function keyWithinCurrentRange (key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n var checkKey = keyIsBeyondCurrentEntry;\n\n var c = new Collection (this, function () {\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\n });\n\n c._ondirectionchange = function (direction) {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(function() {\n if (sortDirection === ascending) cursor.continue(set[i][0]);\n else cursor.continue(set[i][1]);\n });\n return false;\n }\n });\n return c;\n },\n startsWithAnyOf: function () {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(function (s) { return typeof s === 'string'; })) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map(function(str) {\n return [str, str + maxString];\n }));\n }\n };\n });\n\n\n\n\n //\n //\n //\n // Collection Class\n //\n //\n //\n function Collection(whereClause, keyRangeGenerator) {\n /// \n ///\n /// \n /// Where clause instance\n /// \n var keyRange = null, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n var whereCtx = whereClause._ctx,\n table = whereCtx.table;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: table.hook.reading.fire\n };\n }\n \n function isPlainKeyRange (ctx, ignoreLimitFilter) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n } \n\n props(Collection.prototype, function () {\n\n //\n // Collection Private Functions\n //\n\n function addFilter(ctx, fn) {\n ctx.filter = combine(ctx.filter, fn);\n }\n\n function addReplayFilter (ctx, factory, isLimitFilter) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n }\n\n function addMatchFilter(ctx, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n }\n\n /** @param ctx {\n * isPrimKey: boolean,\n * table: Table,\n * index: string\n * }\n * @param store IDBObjectStore\n **/\n function getIndexOrStore(ctx, store) {\n if (ctx.isPrimKey) return store;\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\n return store.index(indexSpec.name);\n }\n\n /** @param ctx {\n * isPrimKey: boolean,\n * table: Table,\n * index: string,\n * keysOnly: boolean,\n * range?: IDBKeyRange,\n * dir: \"next\" | \"prev\"\n * }\n */\n function openCursor(ctx, store) {\n var idxOrStore = getIndexOrStore(ctx, store);\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ?\n idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) :\n idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\n }\n\n function iter(ctx, fn, resolve, reject, idbstore) {\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\n } else (()=>{\n var set = {};\n var resolved = 0;\n\n function resolveboth() {\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\n }\n\n function union(item, cursor, advance) {\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n ctx.or._iterate(union, resolveboth, reject, idbstore);\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\n })();\n }\n function getInstanceTemplate(ctx) {\n return ctx.table.schema.instanceTemplate;\n }\n \n return {\n\n //\n // Collection Protected Functions\n //\n\n _read: function (fn, cb) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._idbstore(READONLY, fn).then(cb);\n },\n _write: function (fn) {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n },\n _addAlgorithm: function (fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n },\n\n _iterate: function (fn, resolve, reject, idbstore) {\n return iter(this._ctx, fn, resolve, reject, idbstore);\n },\n\n clone: function (props) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n },\n\n raw: function () {\n this._ctx.valueMapper = null;\n return this;\n },\n\n //\n // Collection Public methods\n //\n\n each: function (fn) {\n var ctx = this._ctx;\n\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, fn, resolve, reject, idbstore);\n });\n },\n\n count: function (cb) {\n var ctx = this._ctx;\n\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return this._read(function (resolve, reject, idbstore) {\n var idx = getIndexOrStore(ctx, idbstore);\n var req = (ctx.range ? idx.count(ctx.range) : idx.count());\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = function (e) {\n resolve(Math.min(e.target.result, ctx.limit));\n };\n }, cb);\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return this._read(function (resolve, reject, idbstore) {\n iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore);\n }, cb);\n }\n },\n\n sortBy: function (keyPath, cb) {\n /// \n var parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n },\n\n toArray: function (cb) {\n var ctx = this._ctx;\n return this._read(function (resolve, reject, idbstore) {\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n var readingHook = ctx.table.hook.reading.fire;\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ?\n idxOrStore.getAll(ctx.range, ctx.limit) :\n idxOrStore.getAll(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = readingHook === mirror ?\n eventSuccessHandler(resolve) :\n eventSuccessHandler(res => {\n try {resolve (res.map(readingHook));} catch(e) {reject(e);}\n });\n } else {\n // Getting array through a cursor.\n var a = [];\n iter(ctx, function (item) { a.push(item); }, function arrayComplete() {\n resolve(a);\n }, reject, idbstore);\n }\n }, cb);\n },\n\n offset: function (offset) {\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, ()=> {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(()=> {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, ()=> {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n },\n\n limit: function (numRows) {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, ()=> {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n },\n\n until: function (filterFunction, bIncludeStopEntry) {\n var ctx = this._ctx;\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n },\n\n first: function (cb) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n },\n\n last: function (cb) {\n return this.reverse().first(cb);\n },\n\n filter: function (filterFunction) {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction); \n return this;\n },\n \n and: function (filterFunction) {\n return this.filter(filterFunction);\n },\n\n or: function (indexName) {\n return new WhereClause(this._ctx.table, indexName, this);\n },\n\n reverse: function () {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n },\n\n desc: function () {\n return this.reverse();\n },\n\n eachKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n },\n\n eachUniqueKey: function (cb) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n },\n \n eachPrimaryKey: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n },\n\n keys: function (cb) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n },\n \n primaryKeys: function (cb) {\n var ctx = this._ctx;\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read((resolve, reject, idbstore) =>{\n var idxOrStore = getIndexOrStore(ctx, idbstore);\n var req = ctx.limit < Infinity ?\n idxOrStore.getAllKeys(ctx.range, ctx.limit) :\n idxOrStore.getAllKeys(ctx.range);\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = eventSuccessHandler(resolve);\n }).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n },\n\n uniqueKeys: function (cb) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n },\n\n firstKey: function (cb) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n },\n\n lastKey: function (cb) {\n return this.reverse().firstKey(cb);\n },\n\n distinct: function () {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n },\n\n //\n // Methods that mutate storage\n //\n\n modify: function (changes) {\n var self = this,\n ctx = this._ctx,\n hook = ctx.table.hook,\n updatingHook = hook.updating.fire,\n deletingHook = hook.deleting.fire;\n\n return this._write(function (resolve, reject, idbstore, trans) {\n var modifyer;\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n if (updatingHook === nop && deletingHook === nop) {\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\n modifyer = changes;\n } else {\n // People want to know exactly what is being modified or deleted.\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\n // and call the hooks accordingly!\n modifyer = function (item) {\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\n if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)\n if (!hasOwn(this, \"value\")) {\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\n deletingHook.call(this, this.primKey, item, trans);\n } else {\n // No deletion. Check what was changed\n var objectDiff = getObjectDiff(origItem, this.value);\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\n if (additionalChanges) {\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\n item = this.value;\n keys(additionalChanges).forEach(function (keyPath) {\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n });\n }\n }\n };\n }\n } else if (updatingHook === nop) {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n } else {\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\n // allow it to add additional modifications to make.\n var origChanges = changes;\n changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.\n modifyer = function (item) {\n var anythingModified = false;\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\n if (additionalChanges) extend(changes, additionalChanges);\n keys(changes).forEach(function (keyPath) {\n var val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val);\n anythingModified = true;\n }\n });\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\n return anythingModified;\n };\n }\n\n var count = 0;\n var successCount = 0;\n var iterationComplete = false;\n var failures = [];\n var failKeys = [];\n var currentKey = null;\n\n function modifyItem(item, cursor) {\n currentKey = cursor.primaryKey;\n var thisContext = {\n primKey: cursor.primaryKey,\n value: item,\n onsuccess: null,\n onerror: null\n };\n\n function onerror(e) {\n failures.push(e);\n failKeys.push(thisContext.primKey);\n checkFinished();\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\n }\n\n if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update!\n var bDelete = !hasOwn(thisContext, \"value\");\n ++count;\n tryCatch(function () {\n var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value));\n req._hookCtx = thisContext;\n req.onerror = hookedEventRejectHandler(onerror);\n req.onsuccess = hookedEventSuccessHandler(function () {\n ++successCount;\n checkFinished();\n });\n }, onerror);\n } else if (thisContext.onsuccess) {\n // Hook will expect either onerror or onsuccess to always be called!\n thisContext.onsuccess(thisContext.value);\n }\n }\n\n function doReject(e) {\n if (e) {\n failures.push(e);\n failKeys.push(currentKey);\n }\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\n }\n\n function checkFinished() {\n if (iterationComplete && successCount + failures.length === count) {\n if (failures.length > 0)\n doReject();\n else\n resolve(successCount);\n }\n }\n self.clone().raw()._iterate(modifyItem, function () {\n iterationComplete = true;\n checkFinished();\n }, doReject, idbstore);\n });\n },\n\n 'delete': function () {\n var ctx = this._ctx,\n range = ctx.range,\n deletingHook = ctx.table.hook.deleting.fire,\n hasDeleteHook = deletingHook !== nop;\n if (!hasDeleteHook &&\n isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write((resolve, reject, idbstore) => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n var onerror = eventRejectHandler(reject),\n countReq = (range ? idbstore.count(range) : idbstore.count());\n countReq.onerror = onerror;\n countReq.onsuccess = () => {\n var count = countReq.result;\n tryCatch(()=> {\n var delReq = (range ? idbstore.delete(range) : idbstore.clear());\n delReq.onerror = onerror;\n delReq.onsuccess = () => resolve(count);\n }, err => reject(err));\n };\n });\n }\n\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\n // Divide into chunks to not starve RAM.\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\n // more memory and need lower chunk size.\n const CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\n\n return this._write((resolve, reject, idbstore, trans) => {\n var totalCount = 0;\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\n var collection = this\n .clone({\n keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers)\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\n // would become larger than actual delete count.\n .limit(CHUNKSIZE)\n .raw(); // Don't filter through reading-hooks (like mapped classes etc)\n\n var keysOrTuples = [];\n\n // We're gonna do things on as many chunks that are needed.\n // Use recursion of nextChunk function:\n const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => {\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\n // so that the hook can be called with its values in bulkDelete().\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\n } : (val, cursor) => {\n // No one subscribes to hook('deleting'). Collect only primary keys:\n keysOrTuples.push(cursor.primaryKey);\n }).then(() => {\n // Chromium deletes faster when doing it in sort order.\n hasDeleteHook ?\n keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) :\n keysOrTuples.sort(ascending);\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\n\n }).then(()=> {\n var count = keysOrTuples.length;\n totalCount += count;\n keysOrTuples = [];\n return count < CHUNKSIZE ? totalCount : nextChunk();\n });\n\n resolve (nextChunk());\n });\n }\n };\n });\n\n\n //\n //\n //\n // ------------------------- Help functions ---------------------------\n //\n //\n //\n\n function lowerVersionFirst(a, b) {\n return a._cfg.version - b._cfg.version;\n }\n\n function setApiOnPlace(objs, tableNames, dbschema) {\n tableNames.forEach(function (tableName) {\n var schema = dbschema[tableName];\n objs.forEach(obj => {\n if (!(tableName in obj)) {\n if (obj === Transaction.prototype || obj instanceof Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {get() { return this.table(tableName); }});\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new Table(tableName, schema);\n }\n }\n });\n });\n }\n\n function removeTablesApi(objs) {\n objs.forEach(function (obj) {\n for (var key in obj) {\n if (obj[key] instanceof Table) delete obj[key];\n }\n });\n }\n\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn, reject);\n \n if (!req.onerror) req.onerror = eventRejectHandler(reject);\n if (filter) {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () { cursor.continue(); };\n if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject))\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\n c();\n } else {\n resolve();\n }\n }, reject);\n } else {\n req.onsuccess = trycatcher(function filter_record() {\n var cursor = req.result;\n if (cursor) {\n var c = function () { cursor.continue(); };\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\n c();\n } else {\n resolve();\n }\n }, reject);\n }\n }\n\n function parseIndexSyntax(indexes) {\n /// \n /// \n var rv = [];\n indexes.split(',').forEach(function (index) {\n index = index.trim();\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n rv.push(new IndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n /\\./.test(index)\n ));\n });\n return rv;\n }\n\n function cmp(key1, key2) {\n return indexedDB.cmp(key1, key2);\n }\n\n function min(a, b) {\n return cmp(a, b) < 0 ? a : b;\n }\n\n function max(a, b) {\n return cmp(a, b) > 0 ? a : b;\n }\n\n function ascending(a,b) {\n return indexedDB.cmp(a,b);\n }\n\n function descending(a, b) {\n return indexedDB.cmp(b,a);\n }\n\n function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n }\n\n function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n }\n\n function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n }\n\n function readGlobalSchema() {\n db.verno = idbdb.version / 10;\n db._dbSchema = globalSchema = {};\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\n if (dbStoreNames.length === 0) return; // Database contains no stores.\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\n dbStoreNames.forEach(function (storeName) {\n var store = trans.objectStore(storeName),\n keyPath = store.keyPath,\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\n var indexes = [];\n for (var j = 0; j < store.indexNames.length; ++j) {\n var idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\n indexes.push(index);\n }\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\n });\n setApiOnPlace([allTables], keys(globalSchema), globalSchema);\n }\n\n function adjustToExistingIndexNames(schema, idbtrans) {\n /// \n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n /// \n /// Map between name and TableSchema\n /// \n var storeNames = idbtrans.db.objectStoreNames;\n\n for (var i = 0; i < storeNames.length; ++i) {\n var storeName = storeNames[i];\n var store = idbtrans.objectStore(storeName);\n hasGetAll = 'getAll' in store;\n \n for (var j = 0; j < store.indexNames.length; ++j) {\n var indexName = store.indexNames[j];\n var keyPath = store.index(indexName).keyPath;\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n var indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) indexSpec.name = indexName;\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (/Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n hasGetAll = false;\n } \n }\n\n function fireOnBlocked(ev) {\n db.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c=>c.name === db.name && c !== db && !c._vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n extend(this, {\n Collection: Collection,\n Table: Table,\n Transaction: Transaction,\n Version: Version,\n WhereClause: WhereClause\n });\n\n init();\n\n addons.forEach(function (fn) {\n fn(db);\n });\n}\n\nfunction parseType(type) {\n if (typeof type === 'function') {\n return new type();\n } else if (isArray(type)) {\n return [parseType(type[0])];\n } else if (type && typeof type === 'object') {\n var rv = {};\n applyStructure(rv, type);\n return rv;\n } else {\n return type;\n }\n}\n\nfunction applyStructure(obj, structure) {\n keys(structure).forEach(function (member) {\n var value = parseType(structure[member]);\n obj[member] = value;\n });\n return obj;\n}\n\nfunction hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\nfunction eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nfunction eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nfunction hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nfunction preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nfunction awaitIterator (iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext) {\n return val => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n\n//\n// IndexSpec struct\n//\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\n /// \n /// \n /// \n /// \n /// \n /// \n /// \n this.name = name;\n this.keyPath = keyPath;\n this.unique = unique;\n this.multi = multi;\n this.auto = auto;\n this.compound = compound;\n this.dotted = dotted;\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']');\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\n}\n\n//\n// TableSchema struct\n//\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\n /// \n /// \n /// \n /// \n this.name = name;\n this.primKey = primKey || new IndexSpec();\n this.indexes = indexes || [new IndexSpec()];\n this.instanceTemplate = instanceTemplate;\n this.mappedClass = null;\n this.idxByName = arrayToObject(indexes, index => [index.name, index]);\n}\n\nfunction safariMultiStoreFix(storeNames) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\n// Export Error classes\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\n\n//\n// Static methods and properties\n// \nprops(Dexie, {\n \n //\n // Static delete() method.\n //\n delete: function (databaseName) {\n var db = new Dexie(databaseName),\n promise = db.delete();\n promise.onblocked = function (fn) {\n db.on(\"blocked\", fn);\n return this;\n };\n return promise;\n },\n \n //\n // Static exists() method.\n //\n exists: function(name) {\n return new Dexie(name).open().then(db=>{\n db.close();\n return true;\n }).catch(Dexie.NoSuchDatabaseError, () => false);\n },\n \n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames: function (cb) {\n var getDatabaseNames = getNativeGetDatabaseNamesFn(Dexie.dependencies.indexedDB);\n return getDatabaseNames ? new Promise((resolve, reject) => {\n var req = getDatabaseNames();\n req.onsuccess = function (event) {\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\n };\n req.onerror = eventRejectHandler(reject);\n }).then(cb) : dbNamesDB.dbnames.toCollection().primaryKeys(cb);\n },\n \n defineClass: function (structure) {\n /// \n /// Create a javascript constructor based on given template for which properties to expect in the class.\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\n /// \n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\n\n // Default constructor able to copy given properties into this object.\n function Class(properties) {\n /// Properties to initialize object with.\n /// \n if (properties) extend(this, properties);\n }\n return Class;\n },\n \n applyStructure: applyStructure,\n \n ignoreTransaction: function (scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n \n vip: function (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n },\n\n async: function (generatorFn) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection (e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n \n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n var promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ? Dexie.ignoreTransaction(promiseOrFunction) : promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ? PSD.trans.waitFor(promise) : promise;\n },\n \n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n \n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter);\n }\n },\n \n // Export our derive/extend/override methodology\n derive: derive,\n extend: extend,\n props: props,\n override: override,\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n asap: asap,\n maxKey: maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n \n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\n errnames: errnames,\n \n // Export other static classes\n IndexSpec: IndexSpec,\n TableSchema: TableSchema,\n \n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n },\n \n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p,c,i) => p + (c/Math.pow(10,i*2))),\n \n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n default: Dexie,\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n Dexie: Dexie\n});\n\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\nPromise.rejectionMapper = mapError;\n\n// Initialize dbNamesDB (won't ever be opened on chromium browsers')\ndbNamesDB = new Dexie('__dbnames'); \ndbNamesDB.version(1).stores({dbnames: 'name'});\n\n(()=>{\n // Migrate from Dexie 1.x database names stored in localStorage:\n var DBNAMES = 'Dexie.DatabaseNames';\n if (typeof localStorage !== undefined && _global.document !== undefined) try {\n // Have localStorage and is not executing in a worker. Lets migrate from Dexie 1.x.\n JSON.parse(localStorage.getItem(DBNAMES) || \"[]\")\n .forEach(name => dbNamesDB.dbnames.put({name: name}).catch(nop));\n localStorage.removeItem(DBNAMES);\n } catch (_e) {}\n})();\n"]} \ No newline at end of file diff --git a/test/bundle.js b/test/bundle.js new file mode 100644 index 000000000..ce30ce8cd --- /dev/null +++ b/test/bundle.js @@ -0,0 +1,10002 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('dexie'), require('QUnit')) : typeof define === 'function' && define.amd ? define(['dexie', 'QUnit'], factory) : factory(global.Dexie, global.QUnit); +})(this, function (Dexie, QUnit) { + 'use strict'; + + Dexie = 'default' in Dexie ? Dexie['default'] : Dexie; + + // Custom QUnit config options. + QUnit.config.urlConfig.push( /*{ + id: "polyfillIE", // Remarked because has no effect anymore. Find out why. + label: "Include IE Polyfill", + tooltip: "Enabling this will include the idb-iegap polyfill that makes" + + " IE10&IE11 support multiEntry and compound indexes as well as compound" + + " primary keys" + }, { + id: "indexedDBShim", // Remarked because has no effect anymore. Need to find out why. Should invoke the shim if set! + label: "IndexedDBShim (UseWebSQL as backend)", + tooltip: "Enable this in Safari browsers without indexedDB support or" + + " with poor indexedDB support" + },*/{ + id: "dontoptimize", + label: "Dont optimize tests", + tooltip: "Always delete and recreate the DB between each test" + }, { + id: "longstacks", + label: "Long async stacks", + tooltip: "Set Dexie.debug=true, turning on long async stacks on all" + " errors (Actually we use Dexie.debug='dexie' so that frames from" + " dexie.js are also included)" + }); + Dexie.debug = window.location.search.indexOf('longstacks') !== -1 ? 'dexie' : false; + if (window.location.search.indexOf('longstacks=tests') !== -1) Dexie.debug = true; // Don't include stuff from dexie.js. + var no_optimize = window.no_optimize || window.location.search.indexOf('dontoptimize') !== -1; + var ArrayBuffer = window.ArrayBuffer; + function stringify(idbKey) { + var res = '' + (idbKey && idbKey.constructor && idbKey.constructor === ArrayBuffer ? new Uint8Array(idbKey) : idbKey); + return res; + } + function resetDatabase(db) { + /// + var Promise = Dexie.Promise; + return no_optimize || !db._hasBeenCreated ? + // Full Database recreation. Takes much time! + db.delete().then(function () { + return db.open().then(function () { + if (!no_optimize) { + db._hasBeenCreated = true; + var initialState = db._initialState = {}; + // Now, snapshot the database how it looks like initially (what on.populate did) + return db.transaction('r', db.tables, function () { + var trans = Dexie.currentTransaction; + return Promise.all(trans.storeNames.filter(function (tableName) { + // Don't clear 'meta tables' + return tableName[0] != '_' && tableName[0] != '$'; + }).map(function (tableName) { + var items = {}; + initialState[tableName] = items; + return db.table(tableName).each(function (item, cursor) { + items[stringify(cursor.primaryKey)] = { key: cursor.primaryKey, value: item }; + }); + })); + }); + } + }); + }) : + // Optimize: Don't delete and recreate database. Instead, just clear all object stores, + // and manually run db.on.populate + db.transaction('rw!', db.tables, function () { + // Got to do an operation in order for backend transaction to be created. + var trans = Dexie.currentTransaction; + var initialState = db._initialState; + return Promise.all(trans.storeNames.filter(function (tableName) { + // Don't clear 'meta tables' + return tableName[0] != '_' && tableName[0] != '$'; + }).map(function (tableName) { + // Read current state + var items = {}; + return db.table(tableName).each(function (item, cursor) { + items[stringify(cursor.primaryKey)] = { key: cursor.primaryKey, value: item }; + }).then(function () { + // Diff from initialState + // Go through initialState and diff with current state + var initialItems = initialState[tableName]; + return Promise.all(Object.keys(initialItems).map(function (key) { + var item = items[key]; + var initialItem = initialItems[key]; + if (!item || JSON.stringify(item.value) != JSON.stringify(initialItem.value)) return db.table(tableName).schema.primKey.keyPath ? db.table(tableName).put(initialItem.value) : db.table(tableName).put(initialItem.value, initialItem.key); + return Promise.resolve(); + })); + }).then(function () { + // Go through current state and diff with initialState + var initialItems = initialState[tableName]; + var keysToDelete = Object.keys(items).filter(function (key) { + return !initialItems[key]; + }).map(function (key) { + return items[key].key; + }); + if (keysToDelete.length > 0) { + return db.table(tableName).bulkDelete(keysToDelete); + } + }); + })); + }); + } + + var isIE = !window.ActiveXObject && "ActiveXObject" in window; + var isEdge = /Edge\/\d+/.test(navigator.userAgent); + var hasPolyfillIE = [].slice.call(document.getElementsByTagName("script")).some(function (s) { + return s.src.indexOf("idb-iegap") !== -1; + }); + function supports(features) { + return features.split('+').reduce(function (result, feature) { + switch (feature.toLowerCase()) { + case "compound": + return result && Array.isArray(Dexie.maxKey); + case "multientry": + return result && (hasPolyfillIE || !isIE && !isEdge); // Should add Safari to + case "deleteobjectstoreafterread": + return result && !isIE && !isEdge; + case "versionchange": + return result; + //return result && (!isIE && !isEdge); // Should add Safari to + case "binarykeys": + try { + return result && Array.isArray(Dexie.maxKey) && indexedDB.cmp(new Uint8Array([1]), new Uint8Array([1])) === 0; + } catch (e) { + return false; + } + default: + throw new Error("Unknown feature: " + feature); + } + }, true); + } + function spawnedTest(name, num, promiseGenerator) { + if (!promiseGenerator) { + promiseGenerator = num; + QUnit.test(name, function (assert) { + var done = assert.async(); + Dexie.spawn(promiseGenerator).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).then(done); + }); + } else { + QUnit.test(name, num, function (assert) { + var done = assert.async(); + Dexie.spawn(promiseGenerator).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).then(done); + }); + } + } + function promisedTest(name, num, asyncFunction) { + if (!asyncFunction) { + asyncFunction = num; + QUnit.test(name, function (assert) { + var done = assert.async(); + Promise.resolve().then(asyncFunction).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).then(done); + }); + } else { + QUnit.test(name, num, function (assert) { + var done = assert.async(); + Promise.resolve().then(asyncFunction).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).then(done); + }); + } + } + + var __generator = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var db = new Dexie("TestDBTable"); + db.version(1).stores({ + users: "++id,first,last,&username,*&email,*pets", + folks: "++,first,last" + }); + var User = db.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String] + }); + var idOfFirstUser = 0; + var idOfLastUser = 0; + db.on("populate", function (trans) { + db.users.add({ first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }).then(function (id) { + idOfFirstUser = id; + }); + db.users.add({ first: "Karl", last: "Faadersköld", username: "kceder", email: ["karl@ceder.what", "dadda@ceder.what"], pets: [] }).then(function (id) { + idOfLastUser = id; + }); + }); + QUnit.module("table", { + setup: function () { + QUnit.stop(); + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + QUnit.asyncTest("get", 4, function () { + db.table("users").get(idOfFirstUser).then(function (obj) { + QUnit.equal(obj.first, "David", "Got the first object"); + return db.users.get(idOfLastUser); + }).then(function (obj) { + QUnit.equal(obj.first, "Karl", "Got the second object"); + return db.users.get("nonexisting key"); + }).then(function (obj) { + QUnit.ok(true, "Got then() even when getting non-existing object"); + QUnit.equal(obj, undefined, "Result is 'undefined' when not existing"); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("where", function () { + db.transaction("r", db.users, function () { + db.users.where("username").equals("kceder").first(function (user) { + QUnit.equal(user.first, "Karl", "where().equals()"); + }), db.users.where("id").above(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 1, "where().above()"); + }), db.users.where("id").aboveOrEqual(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 2, "where().aboveOrEqual()"); + }), db.users.where("id").below(idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().below().count()"); + }), db.users.where("id").below(idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().below().count() should be zero"); + }), db.users.where("id").belowOrEqual(idOfFirstUser).count(function (count) { + QUnit.ok(count == 1, "where().belowOrEqual()"); + }), db.users.where("id").between(idOfFirstUser, idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 1)"); + }), db.users.where("id").between(0, Infinity).count(function (count) { + QUnit.ok(count == 2, "where().between(0, Infinity)"); + }), db.users.where("id").between(idOfFirstUser, idOfFirstUser, true, true).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 1, true, true)"); + }), db.users.where("id").between(1, -1, true, true).count(function (count) { + QUnit.ok(count == 0, "where().between(1, -1, true, true)"); + }), db.users.where("id").between(idOfFirstUser, idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 2)"); + }), db.users.where("id").between(idOfFirstUser, idOfLastUser, true, true).count(function (count) { + QUnit.ok(count == 2, "where().between(1, 2, true, true)"); + }), db.users.where("id").between(idOfFirstUser, idOfLastUser, false, false).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 2, false, false)"); + }); + db.users.where("last").startsWith("Fah").toArray(function (a) { + QUnit.equal(a.length, 1, "where().startsWith(existing) only matches Fahlander, not Faadersköld"); + QUnit.equal(a[0].first, "David"); + }); + db.users.where("last").startsWith("Faa").toArray(function (a) { + QUnit.equal(a.length, 1, "where().startsWith(existing) only matches Faadersköld, not Fahlander"); + QUnit.equal(a[0].first, "Karl"); + }); + db.users.where("last").startsWith("Fa").toArray(function (a) { + QUnit.equal(a.length, 2, "length = 2 on: where().startsWith(2 existing)"); + QUnit.equal(a[0].first, "Karl", "Karl found first on last 'Faadersköld'"); + QUnit.equal(a[1].first, "David", "David found second on last 'Fahlander'"); + }); + db.users.where("last").anyOf("Fahlander", "Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 2, "in() returned expected number of items"); + QUnit.equal(a[0].last, "Faadersköld", "Faadersköld is first"); + }); + db.users.where("last").anyOf("Fahlander", "Faadersköld").reverse().toArray(function (a) { + QUnit.equal(a.length, 2, "in().reverse() returned expected number of items"); + QUnit.equal(a[0].last, "Fahlander", "Fahlander is first"); + }); + db.users.where("last").anyOf("Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 1, "in() returned expected number of items"); + }); + if (supports("multiEntry")) { + db.users.where("email").equals("david@awarica.com").toArray(function (a) { + QUnit.equal(a.length, 1, "Finding items from array members. Expect to fail on IE10/IE11."); + }); + db.users.where("email").startsWith("da").distinct().toArray(function (a) { + QUnit.equal(a.length, 2, "Found both because both have emails starting with 'da'. Expect to fail on IE10/IE11."); + }); + } else { + QUnit.ok(true, "SKIPPED - MULTIENTRY UNSUPPORTED"); + QUnit.ok(true, "SKIPPED - MULTIENTRY UNSUPPORTED"); + } + }).catch(function (e) { + QUnit.ok(false, "Transaction failed: " + e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("count", function () { + db.users.count(function (count) { + QUnit.equal(count, 2, "Table.count()"); + }).catch(function (e) { + QUnit.ok(false, e.message); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("count with limit", function () { + db.users.limit(1).count(function (count) { + QUnit.equal(count, 1, "Table.limit().count()"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("limit(),orderBy(),modify(), abort(), reverse()", function () { + db.transaction("rw", db.users, function () { + // Modify first found user with a helloMessage + db.users.orderBy("first").reverse().limit(1).modify(function (user) { + user.helloMessage = "Hello " + user.first; + }); + // Check that the modification went fine: + db.users.orderBy("first").reverse().toArray(function (a) { + QUnit.equal(a[0].first, "Karl", "First item is Karl"); + QUnit.equal(a[0].helloMessage, "Hello Karl", "Karl got helloMessage 'Hello Karl'"); + QUnit.equal(a[1].first, "David", "Second item is David"); + QUnit.ok(!a[1].helloMessage, "David was not modified due to limit()"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("filter", function () { + db.users.filter(function (user) { + return user.email.indexOf("david@awarica.com") != -1; + }).toArray(function (davids) { + QUnit.equal(1, davids.length, "Got one David"); + QUnit.equal("David", davids[0].first, "The name of the David is David"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("each", function () { + var users = []; + db.users.each(function (user) { + users.push(user); + }).then(function () { + QUnit.equal(users.length, 2, "Got 2 users"); + QUnit.equal(users[0].first, "David", "Got David"); + QUnit.equal(users[1].first, "Karl", "Got Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("put", function () { + db.transaction("rw", db.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db.users.put(newUser).then(function (id) { + QUnit.ok(id > idOfLastUser, "Got id " + id + " because we didnt supply an id"); + QUnit.equal(newUser.id, id, "The id property of the new user was set"); + }); + db.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + user.last = "ChangedLastName"; + var currentId = user.id; + db.users.put(user).then(function (id) { + QUnit.equal(id, currentId, "Still got same id because we update same object"); + }); + db.users.where("last").equals("ChangedLastName").first(function (user) { + QUnit.equal(user.last, "ChangedLastName", "LastName was successfully changed"); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("put-no-transaction", function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db.users.put(newUser).then(function (id) { + QUnit.ok(id > idOfLastUser, "Got id " + id + " because we didnt supply an id"); + QUnit.equal(newUser.id, id, "The id property of the new user was set"); + return db.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + user.last = "ChangedLastName"; + var userId = user.id; + return db.users.put(user).then(function (id) { + QUnit.equal(id, userId, "Still got same id because we update same object"); + return db.users.where("last").equals("ChangedLastName").first(function (user) { + QUnit.equal(user.last, "ChangedLastName", "LastName was successfully changed"); + }); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("add", function () { + db.transaction("rw", db.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db.users.add(newUser).then(function (id) { + QUnit.ok(id > idOfLastUser, "Got id " + id + " because we didnt supply an id"); + QUnit.equal(newUser.id, id, "The id property of the new user was set"); + }); + db.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + spawnedTest("bulkAdd", function () { + var highestKey, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.users.add({ username: "fsdkljfd", email: ["fjkljslk"] })]; + case 1: + highestKey = _a.sent(); + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + return [4 /*yield*/, db.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db.users.bulkAdd([{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }])]; + case 3: + result = _a.sent(); + QUnit.equal(result, highestKey + 2, "Result of bulkAdd() operation was equal to highestKey + 2"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-catching errors", function () { + var _a, newUsersX, e_1, _b, _c, newUsersY, e_2, _d, newUsersZ, _e; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: + return [4 /*yield*/, db.transaction("rw", db.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db.users.bulkAdd(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got BulkError: " + e.message); + QUnit.equal(e.failures.length, 1, "One error due to a duplicate username: " + e.failures[0]); + }); + // Now, since we catched the error, the transaction should continue living. + db.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-added"); + }); + })]; + case 1: + _f.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where("username").startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_f.sent(), 3, "Previous transaction committed"]); + newUsersX = [{ first: "Xke1", last: "Persbrant1", username: "xper1", email: ["xper1@persbrant.net"] }, { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] }]; + _f.label = 3; + case 3: + _f.trys.push([3, 5,, 6]); + return [4 /*yield*/, db.transaction("rw", db.users, function () { + db.users.bulkAdd(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + })]; + case 4: + _f.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 6]; + case 5: + e_1 = _f.sent(); + QUnit.ok(true, "Got: " + e_1); + return [3 /*break*/, 6]; + case 6: + _b = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 7: + _b.apply(void 0, [_f.sent(), 0, "0 users! Good, means that previous transaction did not commit"]); + return [4 /*yield*/, db.users.bulkAdd(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + })]; + case 8: + _f.sent(); + _c = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 9: + _c.apply(void 0, [_f.sent(), 3, "3 users! Good - means that previous operation catched and therefore committed"]); + newUsersY = [{ first: "Yke1", last: "Persbrant1", username: "yper1", email: ["yper1@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] }]; + _f.label = 10; + case 10: + _f.trys.push([10, 12,, 13]); + return [4 /*yield*/, db.users.bulkAdd(newUsersY)]; + case 11: + _f.sent(); + return [3 /*break*/, 13]; + case 12: + e_2 = _f.sent(); + QUnit.ok(true, "Got: " + e_2); + return [3 /*break*/, 13]; + case 13: + _d = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('yper').count()]; + case 14: + _d.apply(void 0, [_f.sent(), 3, "3 users! Good - means that previous operation catched (via try..yield..catch this time, and therefore committed"]); + newUsersZ = [{ first: "Zke1", last: "Persbrant1", username: "zper1", email: ["zper1@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] }]; + return [4 /*yield*/, db.transaction('rw', db.users, function () { + var e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2,, 3]); + return [4 /*yield*/, db.users.bulkAdd(newUsersZ)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_3 = _a.sent(); + throw e_3; + case 3: + return [2 /*return*/]; + } + }); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('zper').count()]; + case 16: + _e.apply(void 0, [_f.sent(), 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-non-inbound-autoincrement", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + return [4 /*yield*/, db.folks.bulkAdd([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }])]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.folks.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_c.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db.folks.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_c.sent(), 1, "Shoudl be 1 Bar"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-catch sub transaction", function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + return [4 /*yield*/, db.transaction('rw', db.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db.transaction('rw', db.users, function () { + db.users.bulkAdd(newUsers); + }).then(function () { + QUnit.ok(false, "Should not succeed with all these operations"); + }).catch(function (e) { + QUnit.equal(e.failures.length, 1, "Should get one failure"); + }); + }).catch(function (e) { + QUnit.ok(true, "Outer transaction aborted due to inner transaction abort. This is ok: " + e); + })]; + case 1: + _b.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_b.sent(), 0, "0 users! Good, means that inner transaction did not commit"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut", function () { + var highestKey, existingFirstUserToReplace, result, ourAddedUsers, replacedDfahlander; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.users.add({ username: "fsdkljfd", email: ["fjkljslk"] })]; + case 1: + highestKey = _a.sent(); + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + return [4 /*yield*/, db.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db.users.get(idOfFirstUser)]; + case 3: + existingFirstUserToReplace = _a.sent(); + QUnit.equal(existingFirstUserToReplace.username, "dfahlander", "Existing user should be dfahlander"); + return [4 /*yield*/, db.users.bulkPut([{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { id: idOfFirstUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }])]; + case 4: + result = _a.sent(); + QUnit.equal(result, highestKey + 2, "Result of bulkPut() operation was equal to highestKey + 2"); + return [4 /*yield*/, db.users.where('username').startsWith("aper").toArray()]; + case 5: + ourAddedUsers = _a.sent(); + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, db.users.get(idOfFirstUser)]; + case 6: + replacedDfahlander = _a.sent(); + QUnit.equal(replacedDfahlander.username, "aper2", "dfahlander Should now be aper2 instead"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut with overlapping objects", function () { + var theOne; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.users.bulkPut([{ + id: "sdjls83", + first: "Daveious" + }, { + id: "sdjls83", + last: "Olvono" + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db.users.get("sdjls83")]; + case 2: + theOne = _a.sent(); + QUnit.equal(theOne.last, "Olvono", "Last item is the one inserted"); + QUnit.ok(theOne.first === undefined, "Object doesnt have a first property"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-catching errors", function () { + var _a, newUsersX, e_4, _b, _c, newUsersY, e_5, _d, newUsersZ, _e; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: + return [4 /*yield*/, db.transaction("rw", db.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { id: idOfLastUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { id: idOfFirstUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db.users.bulkPut(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got BulkError: " + e.message); + QUnit.equal(e.failures.length, 2, "Two errors due to a duplicate username: " + e.failures[0]); + }); + // Now, since we catched the error, the transaction should continue living. + db.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-putted"); + }); + })]; + case 1: + _f.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where("username").startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_f.sent(), 3, "Previous transaction committed"]); + newUsersX = [{ first: "Xke1", last: "Persbrant1", username: "xper1", email: ["xper1@persbrant.net"] }, { id: idOfLastUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { id: idOfFirstUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] }]; + _f.label = 3; + case 3: + _f.trys.push([3, 5,, 6]); + return [4 /*yield*/, db.transaction("rw", db.users, function () { + db.users.bulkPut(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + })]; + case 4: + _f.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 6]; + case 5: + e_4 = _f.sent(); + QUnit.ok(true, "Got: " + e_4); + return [3 /*break*/, 6]; + case 6: + _b = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 7: + _b.apply(void 0, [_f.sent(), 0, "0 users! Good, means that previous transaction did not commit"]); + return [4 /*yield*/, db.users.bulkPut(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + })]; + case 8: + _f.sent(); + _c = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('xper').count()]; + case 9: + _c.apply(void 0, [_f.sent(), 3, "Should count to 3 users because previous operation was catched and therefore should have been committed"]); + newUsersY = [{ first: "Yke1", last: "Persbrant1", username: "yper1", email: ["yper1@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { id: idOfFirstUser, first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] }]; + _f.label = 10; + case 10: + _f.trys.push([10, 12,, 13]); + return [4 /*yield*/, db.users.bulkPut(newUsersY)]; + case 11: + _f.sent(); + return [3 /*break*/, 13]; + case 12: + e_5 = _f.sent(); + QUnit.ok(true, "Got: " + e_5); + return [3 /*break*/, 13]; + case 13: + _d = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('yper').count()]; + case 14: + _d.apply(void 0, [_f.sent(), 3, "Should count to 3 users because previous previous operation catched (via try..yield..catch this time, and therefore should have been committed"]); + newUsersZ = [{ first: "Zke1", last: "Persbrant1", username: "zper1", email: ["zper1@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { id: idOfLastUser, first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] }]; + return [4 /*yield*/, db.transaction('rw', db.users, function () { + var e_6; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2,, 3]); + return [4 /*yield*/, db.users.bulkPut(newUsersZ)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_6 = _a.sent(); + throw e_6; + case 3: + return [2 /*return*/]; + } + }); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('zper').count()]; + case 16: + _e.apply(void 0, [_f.sent(), 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-non-inbound-autoincrement", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + return [4 /*yield*/, db.folks.bulkPut([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }])]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.folks.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_c.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db.folks.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_c.sent(), 1, "Should be 1 Bar"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut - mixed inbound autoIncrement", function () { + var lastId, _a, _b, newLastId, _c, _d, foo2s; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: + return [4 /*yield*/, db.users.bulkPut([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }])]; + case 1: + lastId = _e.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_e.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db.users.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_e.sent(), 1, "Should be 1 Bar"]); + return [4 /*yield*/, db.users.bulkPut([{ id: lastId - 3, first: "Foo2", last: "BarA" }, { first: "Foo2", last: "BarB" }, { id: lastId - 1, first: "Foo2", last: "BarC" }, { first: "Foo2", last: "BarD" // Will create + }])]; + case 4: + newLastId = _e.sent(); + QUnit.equal(newLastId, lastId + 2, "Should have incremented last ID twice now"); + _c = QUnit.equal; + return [4 /*yield*/, db.users.where('first').equals('Foo').count()]; + case 5: + _c.apply(void 0, [_e.sent(), 2, "Should be 2 Foos now"]); + _d = QUnit.equal; + return [4 /*yield*/, db.users.where('first').equals('Foo2').count()]; + case 6: + _d.apply(void 0, [_e.sent(), 4, "Should be 4 Foo2s now"]); + return [4 /*yield*/, db.users.where('first').equals('Foo2').toArray()]; + case 7: + foo2s = _e.sent(); + QUnit.equal(foo2s[0].last, "BarA", "BarA should be first (updated previous ID)"); + QUnit.equal(foo2s[1].last, "BarC", "BarC should be second (updated previous ID"); + QUnit.equal(foo2s[2].last, "BarB", "BarB should be third (got new key)"); + QUnit.equal(foo2s[3].last, "BarD", "BarD should be forth (got new key)"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-catch sub transaction", function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + return [4 /*yield*/, db.transaction('rw', db.users, function () { + var newUsers = [{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] }]; + db.transaction('rw', db.users, function () { + db.users.bulkPut(newUsers); + }).then(function () { + QUnit.ok(false, "Should not succeed with all these operations"); + }).catch(function (e) { + QUnit.equal(e.failures.length, 1, "Should get one failure"); + }); + }).catch(function (e) { + QUnit.ok(true, "Outer transaction aborted due to inner transaction abort. This is ok: " + e); + })]; + case 1: + _b.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db.users.where('username').startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_b.sent(), 0, "0 users! Good, means that inner transaction did not commit"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkDelete", function () { + var userKeys, userCount; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.users.orderBy('id').keys()]; + case 1: + userKeys = _a.sent(); + QUnit.ok(userKeys.length > 0, "User keys found: " + userKeys.join(',')); + return [4 /*yield*/, db.users.bulkDelete(userKeys)]; + case 2: + _a.sent(); + return [4 /*yield*/, db.users.count()]; + case 3: + userCount = _a.sent(); + QUnit.equal(userCount, 0, "Should be no users there now"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkDelete - nonexisting keys", function () { + var userKeys, _a, userCount; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["nonexisting1", "nonexisting2"]; + return [4 /*yield*/, db.users.orderBy(':id').lastKey()]; + case 1: + userKeys = _a.concat([_b.sent()]); + return [4 /*yield*/, db.users.bulkDelete(userKeys)]; + case 2: + _b.sent(); + return [4 /*yield*/, db.users.count()]; + case 3: + userCount = _b.sent(); + QUnit.equal(userCount, 1, "Should be one user there now. (the other should have been deleted)"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkDelete-faulty-key", function () { + var userKeys; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + userKeys = [{ faulty: "ohyes" }]; + return [4 /*yield*/, db.users.bulkDelete(userKeys).then(function () { + QUnit.ok(false, "Should not succeed"); + }).catch('DataError', function (e) { + QUnit.ok(true, "Should get error: " + e); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("delete", function () { + // Without transaction + db.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }).then(function () { + db.users.delete(1).then(function () { + db.users.get(1, function (user) { + QUnit.equal(user, null, "User not found anymore"); + QUnit.start(); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e); + QUnit.start(); + }); + }); + QUnit.asyncTest("delete(using transaction)", function () { + // With transaction + db.transaction("rw", db.users, function () { + db.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }); + db.users.delete(idOfFirstUser); + db.users.get(idOfFirstUser, function (user) { + QUnit.equal(user, null, "User not found anymore"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("delete nonexisting item", 3, function () { + var numUsers; + db.users.count().then(function (count) { + numUsers = count; + QUnit.ok(true, "Number of users before delete: " + count); + }).then(function () { + return db.users.delete("nonexisting key"); + }).then(function () { + QUnit.ok(true, "Success even though nothing was deleted"); + }).then(function () { + return db.users.count(); + }).then(function (count) { + QUnit.equal(numUsers, count, "Just verifying number of items in user table is still same"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("clear", function () { + db.transaction("rw", "users", function () { + db.users.count(function (count) { + QUnit.equal(count, 2, "There are 2 items in database before clearing it"); + }); + db.users.clear(); + db.users.count(function (count) { + QUnit.equal(count, 0, "There are 0 items in database after it has been cleared"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + spawnedTest("failReadonly", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.transaction('r', 'users', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.users.bulkAdd([{ first: "Foo", last: "Bar" }])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('ReadOnlyError', function (e) { + QUnit.ok(true, "Got ReadOnlyError: " + e.stack); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("failNotIncludedStore", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.transaction('rw', 'folks', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.users.bulkAdd([{ first: "Foo", last: "Bar" }])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("failNotIncludedStoreTrans", function () { + db.transaction('rw', 'foodassaddas', function () {}).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + }).catch(function (e) { + QUnit.ok(false, "Oops: " + e.stack); + }).then(QUnit.start); + }); + + var __generator$1 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var db$1 = new Dexie("TestDBCollection"); + db$1.version(1).stores({ users: "id,first,last,&username,*&email,*pets" }); + var User$1 = db$1.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String] + }); + db$1.on("populate", function () { + db$1.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$1.users.add({ id: 2, first: "Karl", last: "Cedersköld", username: "kceder", email: ["karl@ceder.what"], pets: [] }); + }); + QUnit.module("collection", { + setup: function () { + QUnit.stop(); + resetDatabase(db$1).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + spawnedTest("and with values", function () { + var array; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$1.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]).and(function (user) { + return user.username === "dfahlander"; + }).toArray()]; + case 1: + array = _a.sent(); + QUnit.equal(array.length, 1, "Should find one user with given criteria"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("and with keys", function () { + var keys; + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$1.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]).and(function (user) { + return user.username === "dfahlander"; + }).keys()]; + case 1: + keys = _a.sent(); + QUnit.equal(keys.length, 1, "Should find one user with given criteria"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("and with delete", function () { + return __generator$1(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$1.users.orderBy('username').and(function (u) { + return QUnit.ok(!!u, "User should exist here"); + }).delete()]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("each", 3, function () { + var array = []; + db$1.users.orderBy("id").each(function (user) { + array.push(user); + }).then(function () { + QUnit.equal(array.length, 2, "Got two users"); + QUnit.equal(array[0].first, "David", "First is David"); + QUnit.equal(array[1].first, "Karl", "Second is Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("count", 1, function () { + db$1.users.count(function (count) { + QUnit.equal(count, 2, "Two objects in table"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("toArray", 3, function () { + db$1.users.orderBy("last").toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + QUnit.equal(a[0].first, "Karl", "First is Karl"); + QUnit.equal(a[1].first, "David", "Second is David"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("limit", 6, function () { + db$1.transaction("r", db$1.users, function () { + db$1.users.orderBy("last").limit(1).toArray(function (a) { + QUnit.equal(a.length, 1, "Array length is 1"); + QUnit.equal(a[0].first, "Karl", "First is Karl"); + }); + db$1.users.orderBy("last").limit(10).toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + }); + db$1.users.orderBy("last").limit(0).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$1.users.orderBy("last").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$1.users.orderBy("id").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("offset().limit() with advanced combinations", 22, function () { + db$1.transaction("rw", db$1.users, function () { + for (var i = 0; i < 10; ++i) { + db$1.users.add({ id: 3 + i, first: "First" + i, last: "Last" + i, username: "user" + i, email: ["user" + i + "@abc.se"] }); + } + // Using algorithm + count() + db$1.users.where("first").startsWithIgnoreCase("first").count(function (count) { + QUnit.equal(count, 10, "Counting all 10"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").limit(5).count(function (count) { + QUnit.equal(count, 5, "algorithm + count(): limit(5).count()"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).count()"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "algorithm + count(): offset(6).limit(4)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).limit(4)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(17).limit(4).count(function (count) { + QUnit.equal(count, 0, "algorithm + count(): offset(17).limit(4)"); + }); + // Using algorithm + toArray() + db$1.users.where("first").startsWithIgnoreCase("first").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "algorithm + toArray(): limit(5)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "algorithm + toArray(): offset(6).limit(4)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7).limit(4)"); + }); + db$1.users.where("first").startsWithIgnoreCase("first").offset(17).limit(4).toArray(function (a) { + QUnit.equal(a.length, 0, "algorithm + toArray(): offset(17).limit(4)"); + }); + // Using IDBKeyRange + count() + db$1.users.where("first").startsWith("First").count(function (count) { + QUnit.equal(count, 10, "IDBKeyRange + count() - count all 10"); + }); + db$1.users.where("first").startsWith("First").limit(5).count(function (count) { + QUnit.equal(count, 5, "IDBKeyRange + count(): limit(5)"); + }); + db$1.users.where("first").startsWith("First").offset(7).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7)"); + }); + db$1.users.where("first").startsWith("First").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "IDBKeyRange + count(): offset(6)"); + }); + db$1.users.where("first").startsWith("First").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7).limit(4)"); + }); + db$1.users.where("first").startsWith("First").offset(17).limit(4).count(function (count) { + QUnit.equal(count, 0, "IDBKeyRange + count(): offset(17).limit(4)"); + }); + // Using IDBKeyRange + toArray() + db$1.users.where("first").startsWith("First").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "IDBKeyRange + toArray(): limit(5)"); + }); + db$1.users.where("first").startsWith("First").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7)"); + }); + db$1.users.where("first").startsWith("First").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "IDBKeyRange + toArray(): offset(6).limit(4)"); + }); + db$1.users.where("first").startsWith("First").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7).limit(4)"); + }); + db$1.users.where("first").startsWith("First").offset(17).limit(4).toArray(function (a) { + QUnit.equal(a.length, 0, "IDBKeyRange + toArray(): offset(17).limit(4)"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("first", 1, function () { + db$1.users.orderBy("last").first(function (karlCeder) { + QUnit.equal(karlCeder.first, "Karl", "Got Karl"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("last", function () { + db$1.users.orderBy("last").last(function (david) { + QUnit.equal(david.first, "David", "Got David"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("and", 2, function () { + db$1.transaction("r", db$1.users, function () { + db$1.users.where("first").equalsIgnoreCase("david").and(function (user) { + return user.email.indexOf("apa") >= 0; + }).first(function (user) { + QUnit.equal(user, null, "Found no user with first name 'david' and email 'apa'"); + }); + db$1.users.where("first").equalsIgnoreCase("david").and(function (user) { + return user.email.indexOf("daw@thridi.com") >= 0; + }).first(function (user) { + QUnit.equal(user.first, "David", "Found user with first name 'david' and email 'daw@thridi.com'"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("reverse", function () { + db$1.transaction("r", db$1.users, function () { + db$1.users.orderBy("first").reverse().first(function (user) { + QUnit.equal(user.first, "Karl", "Got Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + if (!supports("multiEntry")) { + QUnit.test("distinct", function () { + return QUnit.ok(true, "SKIPPED - MULTIENTRY UNSUPPORTED"); + }); + } else { + QUnit.asyncTest("distinct", function () { + db$1.transaction("r", db$1.users, function () { + db$1.users.where("email").startsWithIgnoreCase("d").toArray(function (a) { + QUnit.equal(a.length, 2, "Got two duplicates of David since he has two email addresses starting with 'd' (Fails on IE10, IE11 due to not supporting multivalued array indexes)"); + }); + db$1.users.where("email").startsWithIgnoreCase("d").distinct().toArray(function (a) { + QUnit.equal(a.length, 1, "Got single instance of David since we used the distinct() method. (Fails on IE10, IE11 due to not supporting multivalued array indexes)"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + } + QUnit.asyncTest("modify", function () { + db$1.transaction("rw", db$1.users, function () { + var currentTime = new Date(); + db$1.users.toCollection().modify({ + lastUpdated: currentTime + }).then(function (count) { + QUnit.equal(count, 2, "Promise supplied the number of modifications made"); + }); + db$1.users.toArray(function (a) { + QUnit.equal(a.length, 2, "Length ok"); + QUnit.equal(a[0].first, "David", "First is David"); + QUnit.equal(a[0].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on David"); + QUnit.equal(a[1].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("modify-using-function", function () { + db$1.transaction("rw", db$1.users, function () { + var currentTime = new Date(); + db$1.users.toCollection().modify(function (user) { + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$1.users.toArray(function (a) { + QUnit.equal(a.length, 2); + QUnit.equal(a[0].first, "David"); + QUnit.equal(a[0].fullName, "David Fahlander", "Could modify David with a getter function"); + QUnit.equal(a[0].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on David"); + QUnit.equal(a[1].lastUpdated.getTime(), currentTime.getTime(), "Could set new member lastUpdated on Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("modify-causing-error", 2, function () { + db$1.transaction("rw", db$1.users, function () { + var currentTime = new Date(); + db$1.users.toCollection().modify(function (user) { + user.id = 1; + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$1.users.toArray(function (a) { + QUnit.ok(false, "Should not come here, beacuse we should get error when setting all primkey to 1"); + }); + }).catch(Dexie.ModifyError, function (e) { + QUnit.ok(true, "Got ModifyError: " + e); + QUnit.equal(e.successCount, 1, "Succeeded with the first entry but not the second"); + }).catch(function (e) { + QUnit.ok(false, "Another error than the expected was thrown: " + e); + }).finally(QUnit.start); + }); + // Issue #594 (A Safari issue) + // + // The test below fails in Safari 10 and 11. Collection.modify currently uses IDBCursor.update(). + // This seems not to work in Safari if the cursor is iterating an index (using where() with Dexie). + // I tried to replace IDBCursor.update() with the equivalent IDBObjectStore.put() but we got the + // same issue then as well. + // + // Before enabling this test, Safari must have solved the issue (not yet reported to the webkit team), + // or we could do another implementation of Collection.modify() that performs the modification afterwards + // of iterating the collection. + // + /*promisedTest("modify-with-where(issue-594)", async ()=>{ + db.users.add({ id: 3, first: "David", last: "Fahlander2", username: "dfahlander2", email: ["david2@awarica.com"], pets: [] }); + db.users.add({ id: 4, first: "David", last: "Fahlander3", username: "dfahlander3", email: ["david3@awarica.com"], pets: [] }); + const numDavids = (await db.users.where('first').equals("David").toArray()).length; + equal(numDavids, 3, "There should be 3 Davids"); + const numModifications = await db.users.where('first').equals("David").modify((object) => { object.anotherProperty = 'test'; }); + equal(numModifications, 3, "There should have been 3 modifications"); + });*/ + QUnit.asyncTest("delete", 2, function () { + db$1.users.orderBy("id").delete().then(function (count) { + QUnit.equal(count, 2, "All two records deleted"); + return db$1.users.count(function (count) { + QUnit.equal(count, 0, "No users in collection anymore"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("delete(2)", 3, function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$1.users.where("first").equalsIgnoreCase("david").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both davids)"); + }); + db$1.users.toArray(function (a) { + QUnit.equal(a.length, 1, "Deleted one user"); + QUnit.equal(a[0].first, "Karl", "Only Karl is there now"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("delete(3, combine with OR)", 3, function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$1.users.where("first").equals("dAvid").or("username").equals("kceder").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both dAvid Helenius and Karl Cedersköld)"); + }); + db$1.users.toArray(function (a) { + QUnit.equal(a.length, 1, "Only one item left since dAvid and Karl have been deleted"); + QUnit.equal(a[0].first, "David", "Only David Fahlander is there now!"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("keys", function () { + db$1.users.orderBy("first").keys(function (a) { + QUnit.ok(a.length, 2); + QUnit.equal(a[0], "David", "First is David"); + QUnit.equal(a[1], "Karl", "Second is Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("uniqueKeys", function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "David", last: "Helenius", username: "dahel" }); + db$1.users.orderBy("first").keys(function (a) { + QUnit.ok(a.length, 3, "when not using uniqueKeys, length is 3"); + QUnit.equal(a[0], "David", "First is David"); + QUnit.equal(a[1], "David", "Second is David"); + QUnit.equal(a[2], "Karl", "Third is Karl"); + }); + db$1.users.orderBy("first").uniqueKeys(function (a) { + QUnit.ok(a.length, 2, "when using uniqueKeys, length is 2"); + QUnit.equal(a[0], "David", "First is David"); + QUnit.equal(a[1], "Karl", "Second is Karl"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("primaryKeys", function () { + db$1.users.orderBy("last").primaryKeys(function (a) { + QUnit.ok(a.length, 2); + QUnit.equal(a[0], 2, "Second is Karl"); + QUnit.equal(a[1], 1, "First is David"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("primaryKeys2", function () { + db$1.users.orderBy("first").primaryKeys(function (a) { + QUnit.ok(a.length, 2); + QUnit.equal(a[0], 1, "First is David"); + QUnit.equal(a[1], 2, "Second is Karl"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("eachKey and eachUniqueKey", function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "Ylva", last: "Fahlander", username: "yfahlander" }); + var a = []; + db$1.users.orderBy("last").eachKey(function (lastName) { + a.push(lastName); + }).then(function () { + QUnit.equal(a.length, 3, "When using eachKey, number of keys are 3"); + }); + var a2 = []; + db$1.users.orderBy("last").eachUniqueKey(function (lastName) { + a2.push(lastName); + }).then(function () { + QUnit.equal(a2.length, 2, "When using eachUniqueKey, number of keys are 2"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("or", 14, function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "Apan", last: "Japan", username: "apanjapan" }); + db$1.users.where("first").equalsIgnoreCase("david").or("last").equals("Japan").sortBy("first", function (a) { + QUnit.equal(a.length, 2, "Got two users"); + QUnit.equal(a[0].first, "Apan", "First is Apan"); + QUnit.equal(a[1].first, "David", "Second is David"); + }); + db$1.users.where("first").equalsIgnoreCase("david").or("last").equals("Japan").or("id").equals(2).sortBy("id", function (a) { + QUnit.equal(a.length, 3, "Got three users"); + QUnit.equal(a[0].first, "David", "First is David"); + QUnit.equal(a[1].first, "Karl", "Second is Karl"); + QUnit.equal(a[2].first, "Apan", "Third is Apan"); + }); + var userArray = []; + db$1.users.where("id").anyOf(1, 2, 3, 4).or("username").anyOf("dfahlander", "kceder", "apanjapan").each(function (user) { + QUnit.ok(true, "Found: " + JSON.stringify(user)); + userArray.push(user); + }).then(function () { + QUnit.equal(userArray.length, 3, "Got all three users"); + QUnit.ok(userArray.some(function (user) { + return user.first === "David"; + }), "David was found"); + QUnit.ok(userArray.some(function (user) { + return user.first === "Karl"; + }), "Karl was found"); + QUnit.ok(userArray.some(function (user) { + return user.first === "Apan"; + }), "Apan was found"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("or-issue#15-test", function () { + var db = new Dexie("MyDB_issue15"); + db.version(1).stores({ + phones: "++id, additionalFeatures, android, availability, battery, camera, connectivity, description, display, hardware, id, images, name, sizeAndWeight, storage" + }); + db.on('populate', function () { + QUnit.ok(true, "on(populate) called"); + for (var i = 0; i < 100; ++i) { + db.phones.add({ id: 3 + i, name: "Name" + randomString(16), additionalFeatures: [randomString(10)], android: 1, availability: 0, battery: 1, camera: 1 }); + } + function randomString(count) { + var ms = []; + for (var i = 0; i < count; ++i) { + ms.push(String.fromCharCode(32 + Math.floor(Math.random() * 96))); + } + return ms.join(''); + } + }); + db.open().catch(function (err) { + QUnit.ok(false, "DB ERROR: " + err); + }); + var numRuns = 10; + for (var i = 0; i < numRuns; ++i) { + db.phones.where("name").startsWithIgnoreCase("name").or("id").below(50).toArray(function (a) { + QUnit.equal(a.length, 100, "Found 100 phones"); + }).catch(function (err) { + QUnit.ok(false, "error:" + err.stack); + }).finally(function () { + if (--numRuns == 0) { + // All test runs finished. Delete DB and exit unit test. + db.delete(); + QUnit.start(); + } + }); + } + }); + QUnit.asyncTest("until", function () { + db$1.transaction("rw", db$1.users, function () { + db$1.users.add({ id: 3, first: "Apa1", username: "apa1" }); + db$1.users.add({ id: 4, first: "Apa2", username: "apa2" }); + db$1.users.add({ id: 5, first: "Apa3", username: "apa3" }); + // Checking that it stops immediately when first item is the stop item: + db$1.users.orderBy(":id").until(function (user) { + return user.first == "David"; + }).toArray(function (a) { + QUnit.equal(0, a.length, "Stopped immediately because David has ID 1"); + }); + // Checking that specifying includeStopEntry = true will include the stop entry. + db$1.users.orderBy(":id").until(function (user) { + return user.first == "David"; + }, true).toArray(function (a) { + QUnit.equal(1, a.length, "Got the stop entry when specifying includeStopEntry = true"); + QUnit.equal("David", a[0].first, "Name is David"); + }); + // Checking that when sorting on first name and stopping on David, we'll get the apes. + db$1.users.orderBy("first").until(function (user) { + return user.first == "David"; + }).toArray(function (a) { + QUnit.equal(3, a.length, "Got 3 users only (3 apes) because the Apes comes before David and Karl when ordering by first name"); + QUnit.equal("apa1", a[0].username, "First is apa1"); + QUnit.equal("apa2", a[1].username, "Second is apa2"); + QUnit.equal("apa3", a[2].username, "Third is apa3"); + }); + // Checking that reverse() affects the until() method as expected: + db$1.users.orderBy("first").reverse().until(function (user) { + return user.username == "apa2"; + }).toArray(function (a) { + QUnit.equal(3, a.length, "Got 3 users only (David, Karl and Apa3)"); + QUnit.equal("Karl", a[0].first, "When reverse(), First is Karl."); + QUnit.equal("David", a[1].first, "When reverse(), Second is David"); + QUnit.equal("Apa3", a[2].first, "When reverse(), Third is Apa3"); + }); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("firstKey", function () { + db$1.users.orderBy('last').firstKey(function (key) { + QUnit.equal("Cedersköld", key, "First lastName is Cedersköld"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("lastKey", function () { + db$1.users.orderBy('last').lastKey(function (key) { + QUnit.equal("Fahlander", key, "Last lastName is Fahlander"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("firstKey on primary key", function () { + db$1.users.toCollection().firstKey(function (key) { + QUnit.equal(key, 1, "First key is 1"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("lastKey on primary key", function () { + db$1.users.toCollection().lastKey(function (key) { + QUnit.equal(key, 2, "lastKey is 2"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("Promise chain from within each() operation", 2, function () { + db$1.transaction('r', db$1.users, function () { + db$1.users.each(function (user) { + db$1.users.where('id').equals(user.id).first(function (usr) { + return db$1.users.where('id').equals(usr.id).first(); + }).then(function (u) { + return u; + }).then(function (u2) { + QUnit.equal(u2.id, user.id, "Could get the same user after some chains of Promise.resolve()"); + }); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + + var __awaiter = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$2 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _this = undefined; + var db$2 = new Dexie("TestDBWhereClause"); + db$2.version(1).stores({ + folders: "++id,&path", + files: "++id,filename,extension,[filename+extension],folderId", + people: "[name+number],name,number", + friends: "++id,name,age", + chart: '[patno+row+col], patno', + chaps: "++id,[name+number]" + }); + var Folder = db$2.folders.defineClass({ + id: Number, + path: String, + description: String + }); + var File = db$2.files.defineClass({ + id: Number, + filename: String, + extension: String, + folderId: Number + }); + File.prototype.getFullPath = function () { + var file = this; + return db$2.folders.get(this.folderId, function (folder) { + return folder.path + "/" + file.filename + (file.extension || ""); + }); + }; + Folder.prototype.getFiles = function () { + return db$2.files.where('folderId').equals(this.id).toArray(); + }; + var Chart = db$2.chart.defineClass({ + patno: Number, + row: Number, + col: Number, + sym: Number + }); + Chart.prototype.save = function () { + return db$2.chart.put(this); + }; + var firstFolderId = 0; + var lastFolderId = 0; + var firstFileId = 0; + var lastFileId = 0; + db$2.on("populate", function () { + var folders = db$2.table("folders"); + var files = db$2.table("files"); + folders.add({ path: "/", description: "Root folder" }).then(function (id) { + firstFolderId = id; + }); + folders.add({ path: "/usr" }); // 2 + folders.add({ path: "/usr/local" }); // 3 + folders.add({ path: "/usr/local/bin" }).then(function (id) { + files.add({ filename: "Hello", folderId: id }).then(function (fileId) { + firstFileId = fileId; + }); + files.add({ filename: "hello", extension: ".exe", folderId: id }); + }); + folders.add({ path: "/usr/local/src" }).then(function (id) { + files.add({ filename: "world", extension: ".js", folderId: id }); + files.add({ filename: "README", extension: ".TXT", folderId: id }); + }); + folders.add({ path: "/usr/local/var" }); // 6 + folders.add({ path: "/USR/local/VAR" }); // 7 + folders.add({ path: "/var" }); // 8 + folders.add({ path: "/var/bin" }).then(function (id) { + lastFolderId = id; + return files.add({ filename: "hello-there", extension: ".exe", folderId: id }); + }).then(function (id) { + lastFileId = id; + }); + }); + QUnit.module("WhereClause", { + setup: function () { + QUnit.stop(); + resetDatabase(db$2).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + spawnedTest('Issue#31 Compound Index with anyOf', function () { + var items; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports('compound')) return [2 /*return*/, QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")]; + return [4 /*yield*/, db$2.people.bulkAdd([{ + name: 0, + number: 0, + tag: "A" + }, { + name: -1, + number: 0, + tag: "B" + }, { + name: -2, + number: 0, + tag: "C" + }, { + name: -3, + number: 0, + tag: "D" + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.people.where('[name+number]').anyOf([[-2, 0], [-3, 0]]) // https://github.com/dfahlander/Dexie.js/issues/31 + .toArray()]; + case 2: + items = _a.sent(); + QUnit.equal(items.length, 2, "It should contain 2 items."); + QUnit.equal(items[0].tag, "D", "First we should get D"); + QUnit.equal(items[1].tag, "C", "then we should get C"); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("startsWithAnyOf()", function () { + function runTheTests(mippler) { + /// + // + // Basic Flow: + // + return mippler(db$2.folders.where('path').startsWithAnyOf('/usr/local', '/var')).toArray(function (result) { + QUnit.equal(result.length, 6, "Query should match 6 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local'; + }), '/usr/local'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var'; + }), '/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + // + // Require a slash at beginning (and use an array of strings as argument instead) + // + return mippler(db$2.folders.where('path').startsWithAnyOf(['/usr/local/', '/var/'])).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 4, "Query should match 4 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + // + // Some specialities + // + return Dexie.Promise.all(mippler(db$2.folders.where('path').startsWithAnyOf([])).count(), // Empty + mippler(db$2.folders.where('path').startsWithAnyOf('/var', '/var', '/var')).count(), // Duplicates + mippler(db$2.folders.where('path').startsWithAnyOf('')).count(), // Empty string should match all + mippler(db$2.folders).count(), mippler(db$2.folders.where('path').startsWithAnyOf('nonexisting')).count() // Non-existing match + ); + }).then(function (results) { + QUnit.equal(results[0], 0, "startsWithAnyOf([]).count() == 0"); + QUnit.equal(results[1], 2, "startsWithAnyOf('/var', '/var', '/var') == 2"); + QUnit.equal(results[2], results[3], "startsWithAnyOf('').count() == db.folders.count()"); + QUnit.equal(results[4], 0, "startsWithAnyOf('nonexisting').count() == 0"); + // + // Error handling + // + return mippler(db$2.folders.where('path').startsWithAnyOf([null, '/'])).toArray(function (res) { + QUnit.ok(false, "Should not succeed to have null in parameter"); + }).catch(function (e) { + QUnit.ok(true, "As expected: failed to have null in arguments: " + e); + }); + }); + } + // Run tests without transaction and without reverse() + runTheTests(function (x) { + return x; + }).then(function () { + QUnit.ok(true, "FINISHED NORMAL TEST!"); + // Run tests with reverse() + return runTheTests(function (x) { + return x.reverse(); + }); + }).then(function () { + QUnit.ok(true, "FINISHED REVERSE TEST!"); + // Run tests within a transaction + return db$2.transaction('r', db$2.folders, db$2.files, function () { + return runTheTests(function (x) { + return x; + }); + }); + }).then(function () { + QUnit.ok(true, "FINISHED TRANSACTION TEST!"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("anyOf()", function () { + db$2.transaction("r", db$2.files, db$2.folders, function () { + db$2.files.where("filename").anyOf("hello", "hello-there", "README", "gösta").toArray(function (a) { + QUnit.equal(a.length, 3, "Should find 3 files"); + QUnit.equal(a[0].filename, "README", "First match is README because capital R comes before lower 'h' in lexical sort"); + QUnit.equal(a[1].filename, "hello", "Second match is hello"); + QUnit.equal(a[2].filename, "hello-there", "Third match is hello-there"); + a[0].getFullPath().then(function (fullPath) { + QUnit.equal(fullPath, "/usr/local/src/README.TXT", "Full path of README.TXT is: " + fullPath); + }); + a[1].getFullPath().then(function (fullPath) { + QUnit.equal(fullPath, "/usr/local/bin/hello.exe", "Full path of hello.exe is: " + fullPath); + }); + a[2].getFullPath().then(function (fullPath) { + QUnit.equal("/var/bin/hello-there.exe", fullPath, "Full path of hello-there.exe is: " + fullPath); + }); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("anyOf(integerArray)", function () { + // Testing bug #11 Integer Indexes in anyOf handled incorrectly + db$2.files.put({ id: 9000, filename: "new file 1", folderId: firstFolderId }); + db$2.files.put({ id: 10000, filename: "new file 2", folderId: firstFolderId }); + db$2.files.where('id').anyOf([9000, 11000]).toArray(function (a) { + QUnit.equal(a.length, 1, "Should be only one found entry"); + QUnit.equal(a[0].id, 9000, "Item no 9000 should be found"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("anyOf(emptyArray)", function () { + db$2.files.where('id').anyOf([]).toArray(function (a) { + QUnit.equal(a.length, 0, "Should be empty"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("equalsIgnoreCase()", function () { + db$2.files.where("filename").equalsIgnoreCase("hello").toArray(function (a) { + QUnit.equal(a.length, 2, "Got two files"); + QUnit.equal(a[0].filename, "Hello", "First file is Hello"); + QUnit.equal(a[1].filename, "hello", "Second file is hello"); + QUnit.start(); + }); + }); + QUnit.asyncTest("equalsIgnoreCase() 2", function () { + var folder = new Folder(); + folder.path = "/etc"; + folder.description = "Slasktratten"; + db$2.folders.add(folder).then(function (folderId) { + var filenames = ["", "\t ", "AA", "AAron", "APAN JAPAN", "APAN japaö", "APGALEN", "APaLAT", "APaÖNSKAN", "APalster", "Aaron", "Apan JapaN", "Apan Japaa", "Apan Japan", "Gösta", "apan JA", "apan JAPA", "apan JAPAA", "apan JAPANer", "apan JAPAÖ", "apan japan", "apan japanER", "östen"]; + var fileArray = filenames.map(function (filename) { + var file = new File(); + file.filename = filename; + file.folderId = folderId; + return file; + }); + db$2.transaction("rw", db$2.files, function () { + fileArray.forEach(function (file) { + db$2.files.add(file); + }); + db$2.files.where("filename").equalsIgnoreCase("apan japan").toArray(function (a) { + QUnit.equal(a.length, 4, "There should be 4 files with that name"); + QUnit.equal(a[0].filename, "APAN JAPAN", "APAN JAPAN"); + QUnit.equal(a[1].filename, "Apan JapaN", "Apan JapaN"); + QUnit.equal(a[2].filename, "Apan Japan", "Apan Japan"); + QUnit.equal(a[3].filename, "apan japan", "apan japan"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + }).finally(QUnit.start); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + QUnit.start(); + }); + }); + QUnit.asyncTest("equalsIgnoreCase() 2 descending", function () { + var folder = new Folder(); + folder.path = "/etc"; + folder.description = "Slasktratten"; + db$2.folders.add(folder).then(function (folderId) { + var filenames = ["", "\t ", "AA", "AAron", "APAN JAPAN", "APAN japaö", "APGALEN", "APaLAT", "APaÖNSKAN", "APalster", "Aaron", "Apan JapaN", "Apan Japaa", "Apan Japan", "Gösta", "apan JA", "apan JAPA", "apan JAPAA", "apan JAPANer", "apan JAPAÖ", "apan japan", "apan japanER", "östen"]; + var fileArray = filenames.map(function (filename) { + var file = new File(); + file.filename = filename; + file.folderId = folderId; + return file; + }); + db$2.transaction("rw", db$2.files, function () { + fileArray.forEach(function (file) { + db$2.files.add(file); + }); + db$2.files.where("filename").equalsIgnoreCase("apan japan").and(function (f) { + return f.folderId === folderId; + }) // Just for fun - only look in the newly created /etc folder. + .reverse().toArray(function (a) { + QUnit.equal(a.length, 4, "There should be 4 files with that name in " + folder.path); + QUnit.equal(a[0].filename, "apan japan", "apan japan"); + QUnit.equal(a[1].filename, "Apan Japan", "Apan Japan"); + QUnit.equal(a[2].filename, "Apan JapaN", "Apan JapaN"); + QUnit.equal(a[3].filename, "APAN JAPAN", "APAN JAPAN"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack || e); + QUnit.start(); + }).finally(QUnit.start); + }); + }); + QUnit.asyncTest("equalsIgnoreCase() 3 (first key shorter than needle)", function () { + if (typeof idbModules !== 'undefined' && Dexie.dependencies.indexedDB === idbModules.shimIndexedDB) { + // Using indexedDBShim. + QUnit.ok(false, "This test would hang with IndexedDBShim as of 2015-05-07"); + QUnit.start(); + return; + } + db$2.transaction("rw", db$2.files, function () { + db$2.files.clear(); + db$2.files.add({ filename: "Hello-there-", folderId: 1 }); + db$2.files.add({ filename: "hello-there-", folderId: 1 }); + db$2.files.add({ filename: "hello-there-everyone", folderId: 1 }); + db$2.files.add({ filename: "hello-there-everyone-of-you!", folderId: 1 }); + // Ascending + db$2.files.where("filename").equalsIgnoreCase("hello-there-everyone").toArray(function (a) { + QUnit.equal(a.length, 1, "Should find one file"); + QUnit.equal(a[0].filename, "hello-there-everyone", "First file is " + a[0].filename); + }); + // Descending + db$2.files.where("filename").equalsIgnoreCase("hello-there-everyone").reverse().toArray(function (a) { + QUnit.equal(a.length, 1, "Should find one file"); + QUnit.equal(a[0].filename, "hello-there-everyone", "First file is " + a[0].filename); + }); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("startsWithIgnoreCase()", function () { + db$2.transaction("r", db$2.folders, function () { + db$2.folders.count(function (count) { + QUnit.ok(true, "Number of folders in database: " + count); + db$2.folders.where("path").startsWithIgnoreCase("/").toArray(function (a) { + QUnit.equal(a.length, count, "Got all folder objects because all of them starts with '/'"); + }); + }); + db$2.folders.where("path").startsWithIgnoreCase("/usr").toArray(function (a) { + QUnit.equal(a.length, 6, "6 folders found: " + a.map(function (folder) { + return '"' + folder.path + '"'; + }).join(', ')); + }); + db$2.folders.where("path").startsWithIgnoreCase("/usr").reverse().toArray(function (a) { + QUnit.equal(a.length, 6, "6 folders found in reverse mode: " + a.map(function (folder) { + return '"' + folder.path + '"'; + }).join(', ')); + }); + }).then(function () { + QUnit.ok(true, "Transaction complete"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("queryingNonExistingObj", function () { + db$2.files.where("filename").equals("fdsojifdsjoisdf").toArray(function (a) { + QUnit.equal(a.length, 0, "File fdsojifdsjoisdf was not found"); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(QUnit.start); + }); + if (!supports("compound")) { + QUnit.test("compound-index", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + QUnit.test("compound-primkey (Issue #37)", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + QUnit.test("Issue #31 - Compound Index with anyOf", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + QUnit.test("Erratic behavior of between #190", function () { + return QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED"); + }); + } else { + QUnit.asyncTest("compound-index", 2, function () { + db$2.transaction("r", db$2.files, function () { + db$2.files.where("[filename+extension]").equals(["README", ".TXT"]).toArray(function (a) { + QUnit.equal(a.length, 1, "Found one file by compound index search"); + QUnit.equal(a[0].filename, "README", "The found file was README.TXT"); + }); + }).catch(function (e) { + QUnit.ok(false, e + ". Expected to fail on IE10/IE11 - no support compound indexs."); + }).finally(QUnit.start); + }); + QUnit.asyncTest("compound-primkey (Issue #37)", function () { + db$2.transaction('rw', db$2.people, function () { + db$2.people.add({ name: "Santaclaus", number: 123 }); + db$2.people.add({ name: "Santaclaus", number: 124 }); + db$2.people.add({ name: "Santaclaus2", number: 1 }); + return db$2.people.get(["Santaclaus", 123]); + }).then(function (santa) { + QUnit.ok(!!santa, "Got santa"); + QUnit.equal(santa.name, "Santaclaus", "Santa's name is correct"); + QUnit.equal(santa.number, 123, "Santa's number is correct"); + return db$2.people.where("[name+number]").between(["Santaclaus", 1], ["Santaclaus", 200]).toArray(); + }).then(function (santas) { + QUnit.equal(santas.length, 2, "Got two santas"); + }).catch(function (e) { + QUnit.ok(false, "Failed (will fail in IE without polyfill):" + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Issue #31 - Compound Index with anyOf", function () { + db$2.files.where("[filename+extension]").anyOf([["hello", ".exe"], ["README", ".TXT"]]).toArray(function (a) { + QUnit.equal(a.length, 2, "Should find two files"); + QUnit.equal(a[0].filename, "README", "First comes the uppercase README.TXT"); + QUnit.equal(a[1].filename, "hello", "Second comes the lowercase hello.exe"); + }).catch(function (e) { + QUnit.ok(false, "Failed (will fail in IE without polyfill):" + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Erratic behavior of between #190", function () { + db$2.transaction("rw", db$2.chart, function () { + var chart = []; + for (var r = 1; r <= 2; r++) { + for (var c = 1; c <= 150; c++) { + chart.push({ patno: 1, + row: r, + col: c, + sym: 1 }); + } + } + db$2.chart.bulkAdd(chart); + }).then(function () { + var grid = [], + x1 = 91, + x2 = 130; + return db$2.chart.where("[patno+row+col]").between([1, 1, x1], [1, 1, x2], true, true).each(function (cell) { + grid.push(cell.sym); + }).then(function () { + QUnit.equal(grid.length, 40, "Should find 40 cells"); + //console.log("range " + x1 + "-" + x2 + " found " + grid.length); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e + " (Will fail in IE and Edge due to lack of compound primary keys)"); + }).finally(QUnit.start); + }); + } + QUnit.asyncTest("above, aboveOrEqual, below, belowOrEqual, between", 32, function () { + db$2.folders.where('id').above(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 4, "Four folders have id above 5"); + QUnit.equal(a[0].path, "/usr/local/var"); + QUnit.equal(a[1].path, "/USR/local/VAR"); + QUnit.equal(a[2].path, "/var"); + QUnit.equal(a[3].path, "/var/bin"); + }).then(function () { + return db$2.folders.where('id').aboveOrEqual(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 5, "Five folders have id above or equal 5"); + QUnit.equal(a[0].path, "/usr/local/src"); + QUnit.equal(a[1].path, "/usr/local/var"); + QUnit.equal(a[2].path, "/USR/local/VAR"); + QUnit.equal(a[3].path, "/var"); + QUnit.equal(a[4].path, "/var/bin"); + }); + }).then(function () { + return db$2.folders.where('id').below(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 4, "Four folders have id below 5"); + QUnit.equal(a[0].path, "/"); + QUnit.equal(a[1].path, "/usr"); + QUnit.equal(a[2].path, "/usr/local"); + QUnit.equal(a[3].path, "/usr/local/bin"); + }); + }).then(function () { + return db$2.folders.where('id').belowOrEqual(firstFolderId + 4).toArray(function (a) { + QUnit.equal(a.length, 5, "Five folders have id below or equal to 5"); + QUnit.equal(a[0].path, "/"); + QUnit.equal(a[1].path, "/usr"); + QUnit.equal(a[2].path, "/usr/local"); + QUnit.equal(a[3].path, "/usr/local/bin"); + QUnit.equal(a[4].path, "/usr/local/src"); + }); + }).then(function () { + return db$2.folders.where('id').between(firstFolderId, firstFolderId + 1).toArray(function (a) { + QUnit.equal(a.length, 1, "One folder between 1 and 2"); + QUnit.equal(a[0].id, firstFolderId, "Found item is number 1"); + }); + }).then(function () { + return db$2.folders.where('id').between(firstFolderId, firstFolderId + 1, true, false).toArray(function (a) { + QUnit.equal(a.length, 1, "One folder between 1 and 2 (including lower but not upper)"); + QUnit.equal(a[0].id, firstFolderId, "Found item is number 1"); + }); + }).then(function () { + return db$2.folders.where('id').between(firstFolderId, firstFolderId + 1, false, true).toArray(function (a) { + QUnit.equal(a.length, 1, "One folder between 1 and 2 (including upper but not lower)"); + QUnit.equal(a[0].id, firstFolderId + 1, "Found item is number 2"); + }); + }).then(function () { + return db$2.folders.where('id').between(firstFolderId, firstFolderId + 1, false, false).toArray(function (a) { + QUnit.equal(a.length, 0, "Zarro folders between 1 and 2 (neither including lower nor upper)"); + }); + }).then(function () { + return db$2.folders.where('id').between(firstFolderId, firstFolderId + 1, true, true).toArray(function (a) { + QUnit.equal(a.length, 2, "Two folder between 1 and 2 (including both lower and upper)"); + QUnit.equal(a[0].id, firstFolderId, "Number 1 among found items"); + QUnit.equal(a[1].id, firstFolderId + 1, "Number 2 among found items"); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("notEqual", function () { + db$2.folders.where('path').notEqual("/usr/local").sortBy("path", function (result) { + result = result.map(function (x) { + return x.path; + }); + QUnit.equal(JSON.stringify(result, null, 4), JSON.stringify(["/", "/USR/local/VAR", "/usr", + //"/usr/local" + "/usr/local/bin", "/usr/local/src", "/usr/local/var", "/var", "/var/bin"], null, 4), "/usr/local should be removed"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("noneOf", function () { + db$2.folders.where('path').noneOf("/usr/local", "/", "/var/bin", "not existing key").sortBy("path", function (result) { + result = result.map(function (x) { + return x.path; + }); + QUnit.equal(JSON.stringify(result, null, 4), JSON.stringify([ + //"/", + "/USR/local/VAR", "/usr", + //"/usr/local" + "/usr/local/bin", "/usr/local/src", "/usr/local/var", "/var"], null, 4), "Only items not specified in query should come into result"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("noneOf keys", function () { + db$2.folders.where('path').noneOf("/usr/local", "/", "/var/bin", "not existing key").keys(function (result) { + result = result.sort(function (a, b) { + return a < b ? -1 : a === b ? 0 : 1; + }); + QUnit.equal(JSON.stringify(result, null, 4), JSON.stringify([ + //"/", + "/USR/local/VAR", "/usr", + //"/usr/local" + "/usr/local/bin", "/usr/local/src", "/usr/local/var", "/var"], null, 4), "Only keys not specified in query should come into result"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("inAnyOfRanges", function () { + db$2.transaction('rw', db$2.friends, function () { + db$2.friends.bulkAdd([{ name: "Simon", age: 3 }, { name: "Tyra", age: 0 }, { name: "David", age: 42 }, { name: "Ylva", age: 40 }, { name: "Ann-Sofie", age: 72 }]).then(function () { + //equal(errors.length, 0, "bulkAdd() succeeded"); + return db$2.friends.where('age').inAnyRange([[0, 3], [65, Infinity]]).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 2, "Should give us two persons"); + QUnit.equal(result[0].name, "Tyra", "First is Tyra"); + QUnit.equal(result[1].name, "Ann-Sofie", "Second is Ann-Sofie"); + return db$2.friends.where("age").inAnyRange([[0, 3], [65, Infinity]], { includeUppers: true }).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 3, "Should give us three persons"); + QUnit.equal(result[0].name, "Tyra", "First is Tyra"); + QUnit.equal(result[1].name, "Simon", "Second is Simon"); + QUnit.equal(result[2].name, "Ann-Sofie", "Third is Ann-Sofie"); + return db$2.friends.where("age").inAnyRange([[0, 3], [65, Infinity]], { includeLowers: false }).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 1, "Should give us one person"); + QUnit.equal(result[0].name, "Ann-Sofie", "Ann-Sofie is the only match"); + return db$2.friends.where("age").inAnyRange([[40, 40], [40, 40], [40, 41], [41, 41], [42, 42]], { includeUppers: true }).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 2, "Should give us two persons"); + QUnit.equal(result[0].name, "Ylva", "First is Ylva"); + QUnit.equal(result[1].name, "David", "Second is David"); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("anyOfIgnoreCase", function () { + db$2.transaction('r', db$2.folders, db$2.files, function () { + db$2.folders.where('path').anyOfIgnoreCase("/usr/local/var", "/").toArray(function (result) { + QUnit.equal(result.length, 3); + QUnit.equal(result[0].path, "/"); + QUnit.equal(result[1].path, "/USR/local/VAR"); + QUnit.equal(result[2].path, "/usr/local/var"); + return db$2.folders.where('path').anyOfIgnoreCase("/usr/local/var", "/").reverse().toArray(); + }).then(function (result) { + QUnit.equal(result.length, 3); + QUnit.equal(result[0].path, "/usr/local/var"); + QUnit.equal(result[1].path, "/USR/local/VAR"); + QUnit.equal(result[2].path, "/"); + return db$2.files.where('filename').anyOfIgnoreCase(["hello", "world", "readme"]).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 4); + QUnit.equal(result[0].filename, "Hello"); + QUnit.equal(result[1].filename, "README"); + QUnit.equal(result[2].filename, "hello"); + QUnit.equal(result[3].filename, "world"); + }); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("anyOfIgnoreCase(2)", function () { + db$2.files.where('filename').anyOfIgnoreCase(["hello", "world", "readme"]).toArray(function (result) { + QUnit.equal(result.length, 4); + QUnit.equal(result[0].filename, "Hello"); + QUnit.equal(result[1].filename, "README"); + QUnit.equal(result[2].filename, "hello"); + QUnit.equal(result[3].filename, "world"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("startsWithAnyOfIgnoreCase()", function () { + function runTheTests(mippler) { + /// + // + // Basic Flow: + // + return mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase('/usr/local', '/var')).toArray(function (result) { + QUnit.equal(result.length, 7, "Query should match 7 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/USR/local/VAR'; + }), '/USR/local/VAR'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local'; + }), '/usr/local'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var'; + }), '/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + // + // Require a slash at beginning (and use an array of strings as argument instead) + // + return mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase(['/usr/local/', '/var/'])).toArray(); + }).then(function (result) { + QUnit.equal(result.length, 5, "Query should match 5 folders"); + QUnit.ok(result.some(function (x) { + return x.path == '/USR/local/VAR'; + }), '/USR/local/VAR'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/bin'; + }), '/usr/local/bin'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/src'; + }), '/usr/local/src'); + QUnit.ok(result.some(function (x) { + return x.path == '/usr/local/var'; + }), '/usr/local/var'); + QUnit.ok(result.some(function (x) { + return x.path == '/var/bin'; + }), '/var/bin'); + // + // Some specialities + // + return Dexie.Promise.all(mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase([])).count(), // Empty + mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase('/var', '/var', '/var')).count(), // Duplicates + mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase('')).count(), // Empty string should match all + mippler(db$2.folders).count(), mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase('nonexisting')).count() // Non-existing match + ); + }).then(function (results) { + QUnit.equal(results[0], 0, "startsWithAnyOfIgnoreCase([]).count() == 0"); + QUnit.equal(results[1], 2, "startsWithAnyOfIgnoreCase('/var', '/var', '/var').count() == 2"); + QUnit.equal(results[2], results[3], "startsWithAnyOfIgnoreCase('').count() == db.folders.count()"); + QUnit.equal(results[4], 0, "startsWithAnyOfIgnoreCase('nonexisting').count() == 0"); + // + // Error handling + // + return mippler(db$2.folders.where('path').startsWithAnyOfIgnoreCase([null, '/'])).toArray(function (res) { + QUnit.ok(false, "Should not succeed to have null in parameter"); + }).catch(function (e) { + QUnit.ok(true, "As expected: failed to have null in arguments: " + e); + }); + }); + } + // Run tests without transaction and without reverse() + runTheTests(function (x) { + return x; + }).then(function () { + QUnit.ok(true, "FINISHED NORMAL TEST!"); + // Run tests with reverse() + return runTheTests(function (x) { + return x.reverse(); + }); + }).then(function () { + QUnit.ok(true, "FINISHED REVERSE TEST!"); + // Run tests within a transaction + return db$2.transaction('r', db$2.folders, db$2.files, function () { + return runTheTests(function (x) { + return x; + }); + }); + }).then(function () { + QUnit.ok(true, "FINISHED TRANSACTION TEST!"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + promisedTest("where({key: value})", function () { + return __awaiter(_this, void 0, void 0, function () { + var readme, noResult, ullaBella1, ullaBella2, ullaBella3; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$2.files.where({ filename: "README" }).first()]; + case 1: + readme = _a.sent(); + QUnit.ok(readme, 'Should get a result for db.files.get({filename: "README"});'); + QUnit.equal(readme.extension, ".TXT", "Should get README.TXT"); + return [4 /*yield*/, db$2.files.get({ filename: "README", extension: ".TXT" })]; + case 2: + readme = _a.sent(); + QUnit.ok(readme, 'Should get a result for db.files.get({filename: "README", extension: ".TXT"});'); + return [4 /*yield*/, db$2.files.get({ filename: "apa", extension: "otto" })]; + case 3: + noResult = _a.sent(); + QUnit.ok(!noResult, "Should not get a result when querying non-existing stuff"); + // Friends have single indexes on "name" and "age" + return [4 /*yield*/, db$2.friends.add({ name: "Ulla Bella", number: 888, age: 88 })]; + case 4: + // Friends have single indexes on "name" and "age" + _a.sent(); + // People have compound index for [name, number] + return [4 /*yield*/, db$2.chaps.add({ name: "Ulla Bella", number: 888, age: 88 })]; + case 5: + // People have compound index for [name, number] + _a.sent(); + // Folders haven't indexed any of "name", "number" or "age" + return [4 /*yield*/, db$2.folders.add({ name: "Ulla Bella", number: 888, age: 88 })]; + case 6: + // Folders haven't indexed any of "name", "number" or "age" + _a.sent(); + return [4 /*yield*/, db$2.friends.get({ name: "Ulla Bella", number: 888 })]; + case 7: + ullaBella1 = _a.sent(); + QUnit.ok(!!ullaBella1, "Should be able to query multiple columns even when only one of them is indexed"); + return [4 /*yield*/, db$2.chaps.get({ name: "Ulla Bella", number: 888 })]; + case 8: + ullaBella2 = _a.sent(); + QUnit.ok(!!ullaBella2, "Should be able to query multiple columns. This time utilizing compound index."); + return [4 /*yield*/, db$2.chaps.get({ number: 888, name: "Ulla Bella" })]; + case 9: + ullaBella3 = _a.sent(); + QUnit.ok(!!ullaBella3, "Should be able to utilize compound index no matter the order of criterias."); + return [4 /*yield*/, db$2.folders.get({ name: "Ulla Bella", number: 888 }).then(function (ulla) { + QUnit.ok(false, "Should not get Ulla Bella when no index was found"); + }).catch('SchemaError', function (e) { + QUnit.ok(true, "Got SchemaError because we're not utilizing any index at all: " + e); + })]; + case 10: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("orderBy(['idx1','idx2'])", function () { + return __awaiter(_this, void 0, void 0, function () { + var files; + return __generator$2(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("compound")) { + QUnit.ok(true, "Browser does not support compound indexes. Ignoring test."); + return [2 /*return*/]; + } + db$2.files.add({ filename: "hello", extension: ".bat" }); + return [4 /*yield*/, db$2.files.orderBy(["filename", "extension"]).toArray()]; + case 1: + files = _a.sent(); + QUnit.equal(files.length, 5, "Should be 5 files in total that has both filename and extension"); + QUnit.equal(files.map(function (f) { + return f.filename + f.extension; + }).join(','), "README.TXT,hello.bat,hello.exe,hello-there.exe,world.js", 'Files should be ordered according to the orderBy query'); + return [2 /*return*/]; + } + }); + }); + }); + + var __awaiter$1 = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$3 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _this$1 = undefined; + var db$3 = new Dexie("TestDBTrans"); + db$3.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + QUnit.module("transaction", { + setup: function () { + QUnit.stop(); + resetDatabase(db$3).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + var NativePromise = window.Promise; + QUnit.asyncTest("Transaction should work when returning native Promise in transaction scope", function () { + if (!NativePromise) { + QUnit.ok(true, "Current Browser doesn't have a native Promise"); + return QUnit.start(); + } + db$3.transaction('rw', db$3.users, function (trans) { + QUnit.ok(Dexie.currentTransaction === trans, "First argument to transaction callback should be the transaction instance itself"); + return NativePromise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + }).then(function () { + return db$3.users.add({ username: "barfoo" }); // Will only work on Chrome, Opera and Edge as of Oktober 6, 2016. + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + return db$3.users.count(); + }); + }).then(function (count) { + QUnit.ok(true, "User count: " + count + ". REJOICE! YOUR BROWSER'S INDEXEDDB PLAYS BALL WITH PROMISES!"); + }).catch('TransactionInactiveError', function (e) { + QUnit.ok(true, "Your browser has native incompatibility between native Promise and IndexedDB. This is why we still avoid returning native promises."); + }).catch(function (e) { + QUnit.ok(false, "Failed: " + (e.stack || e)); + }).finally(QUnit.start); + }); + QUnit.asyncTest("empty transaction block", function () { + db$3.transaction('rw', db$3.users, db$3.pets, function () { + QUnit.ok(true, "Entering transaction block but dont start any transaction"); + // Leave it empty. + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + setTimeout(QUnit.start, 10); + }); + }); + QUnit.asyncTest("db.transaction()", function () { + db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "arne" }); + return db$3.users.get("arne", function (user) { + QUnit.equal(user.username, "arne", "Got user arne the line after adding it - we must be in a transaction"); + QUnit.ok(Dexie.currentTransaction != null, "Current Transaction must be set"); + }); + }).then(function () { + QUnit.ok(Dexie.currentTransaction == null, "Current Transaction must be null even when transaction scope returned a Promise that was bound to the transaction"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Table not in transaction", function () { + db$3.pets.add({ kind: "dog" }).then(function () { + return db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "arne" }); + return db$3.pets.get(1, function (pet) { + QUnit.ok(false, "Should not be able to get a pet because pets is not in transaction"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because I made an error"); + }).catch(function (err) { + QUnit.ok(true, "Got error since we tried using a table not in transaction: " + err.stack); + }); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Table not in transaction 2", function () { + return db$3.transaction('rw', db$3.users, function () { + db$3.pets.add({ kind: "dog" }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because I made an error"); + }).catch(function (err) { + QUnit.ok(true, "Got error since we tried using a table not in transaction: " + err.stack); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Write into readonly transaction", function () { + return db$3.transaction('r', db$3.users, function () { + db$3.users.add({ username: "arne" }).then(function () { + QUnit.ok(false, "Should not be able to get a here because we tried to write to users when in a readonly transaction"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit because I made an error"); + }).catch(function (err) { + QUnit.ok(true, "Got error since we tried to write to users when in a readonly transaction: " + err.stack); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Inactive transaction", function () { + return db$3.transaction('rw', db$3.users, function () { + return new Dexie.Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie.currentTransaction.complete(function () { + QUnit.ok(true, "Transaction committing too early..."); + // Resolve the promise after transaction commit. + // Flow will continue in the same Transaction scope but with an + // inactive transaction + resolve(); + }); + }).then(function () { + // Now when transaction has already committed, try to add a user with the current transaction: + return db$3.users.add({ username: "arne" }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }).catch(function (err) { + QUnit.ok(true, "Got error because the transaction has already committed: " + err.stack); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Inactive transaction 2", function () { + return db$3.transaction('rw', db$3.users, function () { + // First make an operation so that transaction is internally created (this is the thing differing from the previous test case + return db$3.users.add({ username: "arne" }).then(function () { + // Create a custom promise that will use setTimeout() so that IDB transaction will commit + return new Dexie.Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie.currentTransaction.complete(function () { + QUnit.ok(true, "Transaction committing too early..."); + resolve(); + }); + }); + }).then(function () { + // Now when transaction has already committed, try to add a user with the current transaction: + return db$3.users.add({ username: "arne" }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }); + }).then(function () { + QUnit.ok(false, "Should not be able to get a here transaction has become inactive"); + }).catch(function (err) { + QUnit.ok(true, "Got error because the transaction has already committed: " + err.stack); + }).finally(QUnit.start); + }); + QUnit.asyncTest("sub-transactions", function () { + var parentTrans; + function addUser(user, pets) { + return db$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + QUnit.ok(parentTrans._reculock > 0, "Parent transaction is locked"); + db$3.users.add(user); + pets.forEach(function (pet) { + db$3.pets.add(pet).then(function (petId) { + return db$3.petsPerUser.add({ user: user.username, pet: petId }); + }); + }); + }).then(function () { + return db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: user.username + "2" }); + return "hello..."; + }); + }); + } + db$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + var trans = Dexie.currentTransaction; + parentTrans = Dexie.currentTransaction; + QUnit.ok(trans._reculock === 0, "Main transaction not locked yet"); + addUser({ username: "user1" }, [{ kind: "dog" }, { kind: "cat" }]).then(function () { + db$3.users.get("someoneelse", function (someone) { + QUnit.equal(someone.username, "someoneelse", "Someonelse was recently added"); + }); + }); + QUnit.ok(trans._reculock > 0, "Main transaction is now locked"); + db$3.users.get("someoneelse", function (someone) { + QUnit.ok(!someone, "Someoneelse not yet added"); + }); + db$3.users.add({ username: "someoneelse" }); + return addUser({ username: "user2" }, [{ kind: "giraff" }]).then(function (val) { + QUnit.ok(trans._reculock == 0, "Main transaction not locked anymore"); + return val; + }); + }).then(function (retval) { + QUnit.equal(retval, "hello...", "Return value went all the way down to transaction resolvance"); + QUnit.ok(Dexie.currentTransaction == null, "Dexie.currentTransaction is null"); + db$3.users.count(function (count) { + QUnit.equal(count, 5, "There are five users in db"); + }); + db$3.pets.count(function (count) { + QUnit.equal(count, 3, "There are three pets in db"); + }); + db$3.petsPerUser.count(function (count) { + QUnit.equal(count, 3, "There are three pets-to-user relations"); + }); + }).then(function () { + QUnit.ok(Dexie.currentTransaction == null, "Dexie.currentTransaction is null"); + // Start an outer transaction + return db$3.transaction('rw', db$3.users, function () { + // Do an add operation + db$3.users.add({ username: "sune" }); //.then(function () { + // Start an inner transaction + db$3.transaction('rw', db$3.users, function () { + // Do an add-operation that will result in ConstraintError: + db$3.users.add({ username: "sune" }); + }).then(function () { + QUnit.ok(false, "Transaction shouldn't have committed"); + }).catch("ConstraintError", function (err) { + QUnit.ok(true, "Got ContraintError when trying to add multiple users with same username"); + }).catch(function (err) { + QUnit.ok(false, "Got unknown error: " + err); + }); + //}); + }).catch("ConstraintError", function (err) { + // Yes, it should fail beause of limited rollback support on nested transactions: + // https://github.com/dfahlander/Dexie.js/wiki/Dexie.transaction()#limitations-with-nested-transactions + QUnit.ok(true, "Got constraint error on outer transaction as well"); + }); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Three-level sub transactions", function () { + db$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + db$3.users.add({ username: "ojsan" }); + db$3.transaction('rw', db$3.users, db$3.pets, function () { + db$3.users.add({ username: "ojsan2" }); + db$3.users.toCollection().delete(); + db$3.transaction('r', db$3.users, function () { + db$3.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie.currentTransaction.abort(); + }); + }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Table not in main transactions", function () { + Dexie.Promise.resolve().then(function () { + return db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "bertil" }); + db$3.transaction('rw', db$3.users, db$3.pets, function () { + db$3.pets.add({ kind: "cat" }); + }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Transaction is not in read-mode", function () { + db$3.transaction('r', db$3.users, db$3.pets, function () { + db$3.users.toArray(); + db$3.transaction('rw', db$3.users, db$3.pets, function () { + db$3.pets.add({ kind: "cat" }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); + }); + // + // Testing the "!" mode + // + QUnit.asyncTest("'!' mode: Table not in main transactions", function () { + var counter = 0; + db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "bertil" }); + db$3.transaction('rw!', db$3.users, db$3.pets, function () { + db$3.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error in inner transaction: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + Dexie.currentTransaction.abort(); // Aborting outer transaction should not abort inner. + }).then(function () { + QUnit.ok(false, "Outer transaction should not complete"); + }).catch(function (err) { + QUnit.ok(true, "Got Abort Error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }); + QUnit.asyncTest("'!' mode: Transaction is not in read-mode", function () { + var counter = 0; + db$3.transaction('r', db$3.users, db$3.pets, function () { + db$3.users.toArray(); + db$3.transaction('rw!', db$3.users, db$3.pets, function () { + db$3.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }).then(function () { + QUnit.ok(true, "Outer transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }); + QUnit.asyncTest("'!' mode: Transaction bound to different db instance", function () { + var counter = 0; + var db2 = new Dexie("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.delete().then(function () { + return db2.open(); + }).then(function () { + return db$3.transaction('rw', "users", "pets", function () { + db2.transaction('rw!', "users", "pets", function () { + QUnit.ok(true, "Possible to enter a transaction in db2"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + console.log("finally() in db2.transaction(). counter == " + counter); + }); + }); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + console.log("finally() in db.transaction(). counter == " + counter); + }); + }); + // + // Testing the "?" mode + // + QUnit.asyncTest("'?' mode: Table not in main transactions", function () { + var counter = 0; + db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "bertil" }); + db$3.transaction('rw?', db$3.users, db$3.pets, function () { + db$3.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error in inner transaction: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + Dexie.currentTransaction.abort(); // Aborting outer transaction should not abort inner. + }).then(function () { + QUnit.ok(false, "Outer transaction should not complete"); + }).catch(function (err) { + QUnit.ok(true, "Got Abort Error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }); + QUnit.asyncTest("'?' mode: Transaction is not in read-mode", function () { + var counter = 0; + db$3.transaction('r', db$3.users, db$3.pets, function () { + db$3.users.toArray(); + db$3.transaction('rw?', db$3.users, db$3.pets, function () { + db$3.pets.add({ kind: "cat" }); + }).then(function () { + QUnit.ok(true, "Inner transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }).then(function () { + QUnit.ok(true, "Outer transaction complete"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) QUnit.start(); + }); + }); + QUnit.asyncTest("'?' mode: Transaction bound to different db instance", function () { + var counter = 0; + var db2 = new Dexie("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.open(); + db$3.transaction('rw', "users", "pets", function () { + db2.transaction('rw?', "users", "pets", function () { + QUnit.ok(true, "Possible to enter a transaction in db2"); + }).catch(function (err) { + QUnit.ok(false, "Got error: " + err); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + }); + }).finally(function () { + if (++counter == 2) db2.delete().then(QUnit.start); + }); + }); + QUnit.asyncTest("'?' mode: Three-level sub transactions", function () { + db$3.transaction('rw', db$3.users, db$3.pets, db$3.petsPerUser, function () { + db$3.users.add({ username: "ojsan" }); + db$3.transaction('rw?', db$3.users, db$3.pets, function () { + db$3.users.add({ username: "ojsan2" }); + db$3.users.toCollection().delete(); + db$3.transaction('r?', db$3.users, function () { + db$3.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie.currentTransaction.abort(); + }); + }); + }); + }).then(function () { + QUnit.ok(false, "Shouldnt work"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + err); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Transactions in multiple databases", function () { + var logDb = new Dexie("logger"); + logDb.version(1).stores({ + log: "++,time,type,message" + }); + var lastLogAddPromise; + logDb.open().then(function () { + return db$3.transaction('rw', db$3.pets, function () { + // Test that a non-transactional add in the other DB can coexist with + // the current transaction on db: + logDb.log.add({ time: new Date(), type: "info", message: "Now adding a dog" }); + db$3.pets.add({ kind: "dog" }).then(function (petId) { + // Test that a transactional add in the other DB can coexist with + // the current transaction on db: + lastLogAddPromise = logDb.transaction('rw!', logDb.log, function () { + logDb.log.add({ time: new Date(), type: "info", message: "Added dog got key " + petId }); + }); + }); + }); + }).then(function () { + return lastLogAddPromise; // Need to wait for the transaction of the other database to complete as well. + }).then(function () { + return logDb.log.toArray(); + }).then(function (logItems) { + QUnit.equal(logItems.length, 2, "Log has two items"); + QUnit.equal(logItems[0].message, "Now adding a dog", "First message in log is: " + logItems[0].message); + QUnit.ok(logItems[1].message.indexOf("Added dog got key ") === 0, "Second message in log is: " + logItems[1].message); + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + return logDb.delete(); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Issue #71 If returning a Promise from from a sub transaction, parent transaction will abort", function () { + db$3.transaction('rw', db$3.users, db$3.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + QUnit.ok(true, "Now adding Gunnar in parent transaction"); + db$3.users.add({ username: "Gunnar" }).then(function () { + QUnit.ok(true, "First add on parent transaction finished. Now adding another object in parent transaction."); + db$3.pets.add({ kind: "cat", name: "Garfield" }).then(function () { + QUnit.ok(true, "Successfully added second object in parent transaction."); + }).catch(function (err) { + QUnit.ok(false, "Failed to add second object in parent transaction: " + err.stack || err); + }); + }); + db$3.transaction('rw', db$3.users, function () { + QUnit.ok(true, "Entered sub transaction"); + return db$3.users.add({ username: "JustAnnoyingMyParentTransaction" }).then(function () { + QUnit.ok(true, "Add on sub transaction succeeded"); + }).catch(function (err) { + QUnit.ok(false, "Failed to add object in sub transaction: " + err.stack || err); + }); + }); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Issue #91 Promise.resolve() from within parent transaction", function () { + db$3.transaction('rw', db$3.users, db$3.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + var trans = Dexie.currentTransaction; + return db$3.transaction('rw', db$3.users, function () { + QUnit.ok(true, "Entered sub transaction"); + QUnit.ok(Dexie.currentTransaction !== trans, "We are not in parent transaction"); + QUnit.ok(Dexie.currentTransaction.parent === trans, "...but in a sub transaction"); + return Dexie.Promise.resolve(3); + }).then(function (result) { + QUnit.equal(result, 3, "Got 3"); + QUnit.ok(Dexie.currentTransaction === trans, "Now we are in parent transaction"); + db$3.users.add({ username: "Gunnar" }); + return db$3.users.where("username").equals("Gunnar").first(); + }).then(function (result) { + QUnit.ok(!!result, "Got result"); + QUnit.equal(result.username, "Gunnar", "Got the Gunnar we expected"); + return Dexie.Promise.resolve(result); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e.stack); + }); + }).then(function (result) { + QUnit.ok(!!result, "Got result"); + QUnit.equal(result.username, "Gunnar", "Got the Gunnar we expected"); + }).catch(function (e) { + QUnit.ok(false, "Error at root scope: " + e.stack); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Issue #95 Nested transactions fails if parent transaction don't execute any operation", function () { + function smallChild() { + return db$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering small child"); + return db$3.users.add({ + username: 123, + value: 'val' + }).then(function (res) { + QUnit.ok(true, "smallChild() could add user with primary key " + res); + return res; + }).catch(function (err) { + QUnit.ok(false, 'SCCA' + err); + }); + }).then(function (res) { + QUnit.ok(true, "smallChild's 3rd level nested transaction commited with result " + res); + }).catch(function (err) { + QUnit.ok(false, 'SCTR' + err); + }); + } + function middleChild() { + return db$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering middle child"); + return db$3.pets.add({ + id: 321, + value: 'anotherval' + }).catch(function (err) { + QUnit.ok(false, 'MCCA' + err); + }); + }).catch(function (err) { + QUnit.ok(false, 'MCTR' + err); + }); + } + function bigParent() { + // Nesting transaction without starting the real indexedDB transaction cause an error? + return db$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering root transaction"); + return db$3.transaction('rw', db$3.users, db$3.pets, function () { + console.log("Entering first sub transaction"); + return smallChild().then(function () { + return middleChild(); + }).catch(function (err) { + QUnit.ok(false, 'BPCA ' + err); + }); + }).catch(function (err) { + QUnit.ok(false, 'BPTRI ' + err); + }); + }).catch(function (err) { + QUnit.ok(false, 'BPTRX ' + err); + }); + } + bigParent().then(function (res) { + QUnit.ok(true, "done"); + }).catch(function (e) { + QUnit.ok(false, "Final error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Issue #91 / #95 with Dexie.Promise.resolve() mixed in here and there...", function () { + QUnit.ok(!Dexie.currentTransaction, "There is no ongoing transaction"); + db$3.transaction('rw', db$3.pets, function () { + var rootLevelTransaction = Dexie.currentTransaction; + QUnit.ok(true, "Entered root transaction scope"); + return db$3.transaction('rw', db$3.pets, function () { + QUnit.ok(true, "Entered sub scope"); + var level2Transaction = Dexie.currentTransaction; + QUnit.ok(level2Transaction.parent === rootLevelTransaction, "Level2 transaction's parent is the root level transaction"); + return db$3.transaction('rw', db$3.pets, function () { + QUnit.ok(true, "Entered sub of sub scope"); + var innermostTransaction = Dexie.currentTransaction; + QUnit.ok(!!innermostTransaction, "There is an ongoing transaction (direct in 3rd level scope)"); + QUnit.ok(innermostTransaction.parent === level2Transaction, "Parent is level2 transaction"); + return Dexie.Promise.resolve().then(function () { + QUnit.ok(true, "Sub of sub scope: Promise.resolve().then() called"); + QUnit.ok(!!Dexie.currentTransaction, "There is an ongoing transaction"); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return db$3.pets.add({ + id: 123, + value: 'val' + }).then(function (resultId) { + QUnit.ok(true, "Sub of sub scope: add() resolved"); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(resultId).then(function (res) { + return Dexie.Promise.resolve(res); + }); + }).then(function (resultId) { + QUnit.ok(true, "Sub if sub scope: Promise.resolve() after add() resolve"); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(resultId); + }); + }).then(function () { + QUnit.ok(true, "sub of sub scope chaining further in promise chains..."); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(db$3.pets.get(123)); + }).then(function (pet) { + QUnit.ok(true, "sub of sub scope chaining further in promise chains 2..."); + QUnit.ok(Dexie.currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie.Promise.resolve(pet.id); + }); + }).then(function (resultId) { + QUnit.ok(true, "Innermost transaction completed"); + QUnit.ok(Dexie.currentTransaction == level2Transaction, "We should now be executing within level 2 sub transaction"); + return Dexie.Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.ok(Dexie.currentTransaction == level2Transaction, "We should still be executing within level 2 sub transaction"); + return Dexie.Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.equal(resultId, 123, "Result was 123 as expected"); + }).then(function () { + return db$3.transaction('rw', db$3.pets, function () { + var innermostTransaction2 = Dexie.currentTransaction; + QUnit.ok(innermostTransaction2.parent == level2Transaction, "Another 3rd level transaction has parent set to our level2 transaction"); + return db$3.pets.add({ + id: 321, + value: 'val' + }).then(function (resultId2) { + return Dexie.Promise.resolve(resultId2); + }).then(function (resultId2) { + QUnit.ok(Dexie.currentTransaction === innermostTransaction2, "We're still in the innermostTransaction (second one)"); + return Dexie.Promise.resolve(resultId2).then(function (x) { + QUnit.ok(Dexie.currentTransaction === innermostTransaction2, "We're still in the innermostTransaction (second one)"); + return x; + }); + }); + }).then(function (resultId2) { + QUnit.equal(resultId2, 321, "Result2 was 321 as expected"); + QUnit.ok(Dexie.currentTransaction === level2Transaction, "We should still be executing within level 2 sub transaction"); + return "finalResult"; + }); + }); + }).then(function (x) { + QUnit.ok(Dexie.currentTransaction === rootLevelTransaction, "Now we're at the root level transaction and can do some more stuff here"); + return db$3.pets.clear().then(function () { + return x; + }).then(function (y) { + QUnit.ok(true, "Could clear the pets table for example."); + return y; + }).catch(function (e) { + QUnit.ok(false, "oops, this was not what I expected!: " + e); + }); + }); + }).then(function (finalResult) { + QUnit.equal(finalResult, "finalResult", "Got the final result"); + QUnit.ok(!Dexie.currentTransaction, "No ongoing transaction now"); + QUnit.ok(true, "done"); + }).catch(function (error) { + QUnit.ok(false, error.stack); + }).finally(QUnit.start); + QUnit.ok(!Dexie.currentTransaction, "After main transaction scope: Still no ongoing transaction at this scope"); + }); + QUnit.asyncTest("Issue #137 db.table() does not respect current transaction", function () { + db$3.transaction('rw', db$3.users, function () { + db$3.users.add({ username: "erictheviking", color: "blue" }).then(function () { + db$3.table('users').get('erictheviking', function (eric) { + QUnit.ok(eric, "Got back an object"); + QUnit.equal(eric.color, "blue", "eric.color is still blue. If red, the getter must have been run from another transaction."); + }); + db$3.users.put({ username: "erictheviking", color: "red" }); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Dexie.currentTransaction in CRUD hooks", 53, function () { + function CurrentTransChecker(scope, trans) { + return function () { + QUnit.ok(Dexie.currentTransaction === trans, "Dexie.currentTransaction correct in " + scope); + }; + } + function onCreating(primKey, obj, transaction) { + QUnit.ok(!!Dexie.currentTransaction, "Dexie.currentTransaction should exist in creating"); + QUnit.ok(Dexie.currentTransaction === transaction, "Dexie.currentTransaction correct in creating"); + this.onerror = CurrentTransChecker("creating.onerror", transaction); + this.onsuccess = CurrentTransChecker("creating.onsuccess", transaction); + } + function onReading(obj) { + QUnit.ok(!!Dexie.currentTransaction, "Dexie.currentTransaction should exist in reading"); + return obj; + } + function onUpdating(modifications, primKey, obj, transaction) { + QUnit.ok(Dexie.currentTransaction === transaction, "Dexie.currentTransaction correct in updating"); + this.onerror = CurrentTransChecker("updating.onerror", transaction); + this.onsuccess = CurrentTransChecker("updating.onsuccess", transaction); + } + function onDeleting(primKey, obj, transaction) { + QUnit.ok(Dexie.currentTransaction === transaction, "Dexie.currentTransaction correct in deleting"); + this.onsuccess = CurrentTransChecker("deleting.onsuccess", transaction); + } + db$3.users.hook.creating.subscribe(onCreating); + db$3.users.hook.reading.subscribe(onReading); + db$3.users.hook.updating.subscribe(onUpdating); + db$3.users.hook.deleting.subscribe(onDeleting); + function doTheTests() { + return __awaiter$1(this, void 0, void 0, function () { + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$3.users.add({ username: "monkey1" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.users.add({ username: "monkey1" }).catch(function (ex) { + QUnit.ok(true, "Should fail adding a second monkey1"); + })]; + case 2: + _a.sent(); // Trigger creating.onerror + // Test bulkAdd as well: + QUnit.ok(true, "Testing bulkAdd"); + return [4 /*yield*/, db$3.users.bulkAdd([{ username: "monkey1" }, { username: "monkey2" }]).then(function () { + return QUnit.ok(false, "Should get error on one of the adds"); + }).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got BulkError"); + QUnit.ok(e.failures.length === 1, "One error out of two: " + e); + })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.users.where("username").equals("monkey1").modify({ + name: "Monkey 1" + })]; + case 4: + _a.sent(); + return [4 /*yield*/, db$3.users.where("username").equals("monkey1").modify(function (user) { + user.username = "monkey2"; // trigger updating.onerror + }).catch(function (ex) { + QUnit.ok(true, "Should fail modifying primary key"); + })]; + case 5: + _a.sent(); + return [4 /*yield*/, db$3.users.toArray()]; + case 6: + _a.sent(); + return [4 /*yield*/, db$3.users.delete("monkey2")]; + case 7: + _a.sent(); + return [4 /*yield*/, db$3.users.delete("monkey1")]; + case 8: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + } + + doTheTests().then(function () { + var _this = this; + QUnit.ok(true, "Now in an explicit transaction block..."); + return db$3.transaction('rw', db$3.users, function () { + return __awaiter$1(_this, void 0, void 0, function () { + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, doTheTests()]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + }).catch(function (ex) { + QUnit.ok(false, ex); + }).then(function () { + db$3.users.hook.creating.unsubscribe(onCreating); + db$3.users.hook.reading.unsubscribe(onReading); + db$3.users.hook.updating.unsubscribe(onUpdating); + db$3.users.hook.deleting.unsubscribe(onDeleting); + QUnit.start(); + }); + }); + function sleep(ms) { + return new Promise(function (resolve) { + return setTimeout(resolve, ms); + }); + } + promisedTest("waitFor()", function () { + return __awaiter$1(_this$1, void 0, void 0, function () { + var _this = this; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$3.transaction('rw', db$3.users, function (trans) { + return __awaiter$1(_this, void 0, void 0, function () { + var _this = this; + var result; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + // Wait for a promise: + return [4 /*yield*/, trans.waitFor(sleep(100))]; + case 1: + // Wait for a promise: + _a.sent(); + // Do an operation on transaction + return [4 /*yield*/, trans.users.put({ username: "testingtesting" })]; + case 2: + // Do an operation on transaction + _a.sent(); + return [4 /*yield*/, trans.waitFor(sleep(100))]; + case 3: + _a.sent(); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 4: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should be able to continue transaction after waiting for non-indexedDB promise"); + QUnit.ok(true, "Waiting spin count:" + trans._spinCount); + // With timeout + return [4 /*yield*/, Dexie.waitFor(sleep(2000), 10) // Timeout of 10 ms. + .then(function () { + return QUnit.ok(false, "Should have timed out!"); + }).catch('TimeoutError', function (ex) { + return QUnit.ok(true, "Timed out as expected"); + })]; + case 5: + // With timeout + _a.sent(); + // Wait for function + return [4 /*yield*/, Dexie.waitFor(function () { + return __awaiter$1(_this, void 0, void 0, function () { + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Dexie.currentTransaction === null, "We should not be in the transaction zone here because transaction can be in a temporary inactive state here"); + return [4 /*yield*/, sleep(10)]; + case 1: + _a.sent(); + QUnit.ok(true, "Slept 10 ms"); + // Let's test if we can access the transaction from here. + // The transaction should be alive indeed but not in an active state. + return [4 /*yield*/, trans.users.count().then(function () { + // This happens on IE11 + QUnit.ok(true, "Could access transaction within the wait callback. Nice for you, but you were just lucky!"); + }).catch(function (ex) { + // This happens on Firefox and Chrome + QUnit.ok(true, "Could NOT access transaction within the wait callback. As expected. Error: " + ex); + })]; + case 2: + // Let's test if we can access the transaction from here. + // The transaction should be alive indeed but not in an active state. + _a.sent(); + QUnit.ok(Dexie.currentTransaction === null, "We should not be in the transaction zone here because transaction can be in inactive state here"); + return [2 /*return*/]; + } + }); + }); + })]; + case 6: + // Wait for function + _a.sent(); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 7: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should still be able to operate on the transaction"); + QUnit.ok(true, "Waiting spin count:" + trans._spinCount); + QUnit.ok(Dexie.currentTransaction === trans, "Zone info should still be correct"); + // Subtransaction + return [4 /*yield*/, db$3.transaction('r', db$3.users, function (subTrans) { + var count; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(subTrans !== trans, "Should be in a sub transaction"); + QUnit.ok(Dexie.currentTransaction === subTrans, "Should be in a sub transaction"); + return [4 /*yield*/, trans.users.count()]; + case 1: + count = _a.sent(); + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + return [4 /*yield*/, subTrans.waitFor(sleep(10))]; + case 2: + _a.sent(); + QUnit.ok(true, "Should be able to call waitFor() on sub transaction"); + return [4 /*yield*/, trans.users.count()]; + case 3: + count = _a.sent(); + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + return [2 /*return*/]; + } + }); + })]; + case 8: + // Subtransaction + _a.sent(); + // Calling waitFor multiple times in parallell + return [4 /*yield*/, Promise.all([trans.waitFor(sleep(10)), trans.waitFor(sleep(10)), trans.waitFor(sleep(10))])]; + case 9: + // Calling waitFor multiple times in parallell + _a.sent(); + QUnit.ok(true, "Could wait for several tasks in parallell"); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 10: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should still be able to operate on the transaction"); + return [2 /*return*/]; + } + }); + }); + }).then(function () { + return QUnit.ok(true, "Transaction committed"); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("Dexie.waitFor() outside transaction", function () { + return __awaiter$1(_this$1, void 0, void 0, function () { + var _this = this; + var result, codeExecuted; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, Dexie.waitFor(sleep(10).then(function () { + return true; + }))]; + case 1: + result = _a.sent(); + QUnit.ok(result, "Could call waitFor outside a transaction as well"); + codeExecuted = false; + return [4 /*yield*/, Dexie.waitFor(function () { + return __awaiter$1(_this, void 0, void 0, function () { + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, sleep(10)]; + case 1: + _a.sent(); + codeExecuted = true; + return [2 /*return*/]; + } + }); + }); + })]; + case 2: + _a.sent(); + QUnit.ok(codeExecuted, "Could call waitFor(function) outside a transation as well"); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("Dexie.waitFor() TransactionInactiveError", function () { + return __awaiter$1(_this$1, void 0, void 0, function () { + var _this = this; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$3.transaction('r', db$3.users, function () { + return __awaiter$1(_this, void 0, void 0, function () { + var err_1; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, sleep(100)]; + case 1: + _a.sent(); // Force transaction to become inactive + _a.label = 2; + case 2: + _a.trys.push([2, 4,, 5]); + return [4 /*yield*/, Dexie.waitFor(sleep(10))]; + case 3: + _a.sent(); + QUnit.ok(false, 'After sleeping, transaction just cannot be alive.'); + return [3 /*break*/, 5]; + case 4: + err_1 = _a.sent(); + QUnit.ok(err_1.name == 'TransactionInactiveError' || err_1.name == 'InvalidStateError', "Got TransactionInactiveError or InvalidStateError as expected"); + return [3 /*break*/, 5]; + case 5: + return [2 /*return*/]; + } + }); + }); + }).then(function () { + QUnit.ok(false, 'The transaction should not possibly succeed even though catching, because it was too late.'); + }).catch('PrematureCommitError', function (err) { + QUnit.ok(true, 'Got PrematureCommitError as expected'); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("Promise.follow() should omit promises spawned under Dexie.ignoreTransaction()", function () { + return __awaiter$1(_this$1, void 0, void 0, function () { + var resolve, reject, p, log; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + p = new Promise(function (res, rej) { + resolve = res;reject = rej; + }); + log = []; + return [4 /*yield*/, db$3.transaction('r', db$3.users, function () { + // Since we do not return a promise here, + // Promise.follow() will be used for awaitint all tasks. + // However, tasks spawned under Dexie.ignoreTransacion() should not be included in promises to wait for. + Dexie.ignoreTransaction(function () { + return new Dexie.Promise(function (resolve) { + return setTimeout(resolve, 50); + }).then(function () { + return db$3.pets.put({ kind: "dog" }); + }).then(function () { + return db$3.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: " + numPets); + log.push("inner-task-done"); + }).then(resolve, reject); + }); + // The following promise should be awaited for though (because new Promise is spawned from withing a zone or sub-zone to current transaction.) + new Dexie.Promise(function (resolve) { + return setTimeout(resolve, 25); + }).then(function () { + //return db.users.get(1); + }).then(function () { + QUnit.ok(true, "followed promise done"); + log.push("spawned-promise-done"); + }).catch(function (e) { + QUnit.ok(false, e); + }); + })]; + case 1: + _a.sent(); + log.push("outer-task-done"); + QUnit.ok(true, "transaction done"); + return [4 /*yield*/, p]; + case 2: + _a.sent(); + QUnit.equal(log.join(','), "spawned-promise-done,outer-task-done,inner-task-done", "outer-task-done should have happened before inner-task-done"); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("db.transaction() should not wait for non-awaited new top-level transactions to commit", function () { + return __awaiter$1(_this$1, void 0, void 0, function () { + var resolve, reject, p, log; + return __generator$3(this, function (_a) { + switch (_a.label) { + case 0: + p = new Promise(function (res, rej) { + resolve = res;reject = rej; + }); + log = []; + return [4 /*yield*/, db$3.transaction('r', db$3.users, function () { + // Since we do not return a promise here, + // Promise.follow() will be used for awaitint all tasks. + // However, if we spawn a new top-level transaction. It should be omitted and not waited for: + db$3.transaction('rw!', db$3.pets, function () { + return db$3.pets.put({ kind: "dog" }).then(function () { + return db$3.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: " + numPets); + }).then(function () { + return Dexie.waitFor(sleep(50)); // In IE, it sometimes happens that outer transaction is slow to commit (even though it doesnt to anything) + }).then(function () { + log.push("inner-transaction-done"); + }).then(resolve, reject); + }); + })]; + case 1: + _a.sent(); + log.push("outer-transaction-done"); + QUnit.ok(true, "transaction done"); + return [4 /*yield*/, p]; + case 2: + _a.sent(); + QUnit.equal(log.join(','), "outer-transaction-done,inner-transaction-done", "outer-transaction-done should have happened before inner-transaction-done"); + return [2 /*return*/]; + } + }); + }); + }); + + var __awaiter$2 = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$4 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _this$2 = undefined; + var async$1 = Dexie.async; + QUnit.module("open", { + setup: function () { + QUnit.stop(); + Dexie.delete("TestDB").then(function () { + QUnit.start(); + }).catch(function (e) { + QUnit.ok(false, "Could not delete database"); + }); + }, + teardown: function () { + QUnit.stop(); + Dexie.delete("TestDB").then(QUnit.start); + } + }); + var timeout = async$1(function (promise, ms) { + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, Promise.race([promise, new Promise(function (resolve, reject) { + return setTimeout(function () { + return reject("timeout"); + }, ms); + })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("multiple db should not block each other", function () { + var db1, db2, e_1; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("versionchange")) { + QUnit.ok(true, "SKIPPED - versionchange UNSUPPORTED"); + return [2 /*return*/]; + } + db1 = new Dexie("TestDB"), db2 = new Dexie("TestDB"); + db1.version(1).stores({ + foo: 'bar' + }); + db2.version(1).stores({ + foo: 'bar' + }); + return [4 /*yield*/, db1.open()]; + case 1: + _a.sent(); + QUnit.ok(true, "db1 should open"); + return [4 /*yield*/, db2.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "db2 should open"); + _a.label = 3; + case 3: + _a.trys.push([3, 5,, 6]); + return [4 /*yield*/, timeout(db1.delete(), 1500)]; + case 4: + _a.sent(); + QUnit.ok(true, "Succeeded to delete db1 while db2 was open"); + return [3 /*break*/, 6]; + case 5: + e_1 = _a.sent(); + db1.close(); + db2.close(); + QUnit.ok(false, "Could not delete db1 - " + e_1); + return [3 /*break*/, 6]; + case 6: + return [2 /*return*/]; + } + }); + }); + spawnedTest("Using db on node should be rejected with MissingAPIError", function () { + var db, e_2, e_3; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie('TestDB', { + indexedDB: undefined, + IDBKeyRange: undefined + }); + db.version(1).stores({ foo: 'bar' }); + _a.label = 1; + case 1: + _a.trys.push([1, 3,, 4]); + return [4 /*yield*/, db.foo.toArray()]; + case 2: + _a.sent(); + QUnit.ok(false, "Should not get any result because API is missing."); + return [3 /*break*/, 4]; + case 3: + e_2 = _a.sent(); + QUnit.ok(e_2 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + e_2.name); + return [3 /*break*/, 4]; + case 4: + _a.trys.push([4, 6,, 7]); + return [4 /*yield*/, db.open()]; + case 5: + _a.sent(); + return [3 /*break*/, 7]; + case 6: + e_3 = _a.sent(); + QUnit.ok(e_3 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + e_3.name); + return [3 /*break*/, 7]; + case 7: + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("open, add and query data without transaction", 6, function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ employees: "++id,first,last" }); + QUnit.ok(true, "Simple version() and stores() passed"); + db.open().catch(function (e) { + QUnit.ok(false, "Could not open database: " + (e.stack || e)); + QUnit.start(); + }); + db.employees.add({ first: "David", last: "Fahlander" }).then(function () { + QUnit.ok(true, "Could add employee"); + db.employees.where("first").equals("David").toArray(function (a) { + QUnit.ok(true, "Could retrieve employee based on where() clause"); + var first = a[0].first; + var last = a[0].last; + QUnit.ok(first == "David" && last == "Fahlander", "Could get the same object"); + QUnit.equal(a.length, 1, "Length of returned answer is 1"); + QUnit.ok(a[0].id, "Got an autoincremented id value from the object"); + db.close(); + QUnit.start(); + }); + }); + }); + QUnit.asyncTest("open, add and query data using transaction", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ employees: "++id,first,last" }); + db.open().catch(function () { + QUnit.ok(false, "Could not open database"); + QUnit.start(); + }); + db.transaction("rw", db.employees, function () { + // Add employee + db.employees.add({ first: "David", last: "Fahlander" }); + // Query employee + db.employees.where("first").equals("David").toArray(function (a) { + QUnit.equal(a.length, 1, "Could retrieve employee based on where() clause"); + var first = a[0].first; + var last = a[0].last; + QUnit.ok(first == "David" && last == "Fahlander", "Could get the same object"); + QUnit.equal(a.length, 1, "Length of returned answer is 1"); + QUnit.ok(a[0].id, "Got an autoincremented id value from the object"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(function () { + db.close(); + QUnit.start(); + }); + }); + QUnit.asyncTest("test-if-database-exists", 3, function () { + var db = new Dexie("TestDB"); + var db2 = null; + return db.open().then(function () { + // Could open database without specifying any version. An existing database was opened. + QUnit.ok(false, "Expected database not to exist but it existed indeed"); + db.close(); + }).catch(Dexie.NoSuchDatabaseError, function (err) { + // An error happened. Database did not exist. + QUnit.ok(true, "Database did not exist"); + db = new Dexie("TestDB"); + db.version(1).stores({ dummy: "" }); + return db.open(); + }).then(function () { + // Database was created. Now open another instance to test if it exists + QUnit.ok(true, "Could create a dummy database"); + db2 = new Dexie("TestDB"); + return db2.open(); + }).then(function () { + QUnit.ok(true, "Dummy Database did exist."); + db2.close(); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err.stack || err); + }).finally(function () { + db.delete().then(function () { + if (db2) return db2.delete(); + }).finally(QUnit.start); + }); + }); + QUnit.asyncTest("open database without specifying version or schema", Dexie.Observable ? 1 : 10, function () { + if (Dexie.Observable) { + QUnit.ok(true, "Dexie.Observable currently not compatible with this mode"); + return QUnit.start(); + } + var db = new Dexie("TestDB"); + var db2 = null; + db.open().then(function () { + QUnit.ok(false, "Should not be able to open a non-existing database when not specifying any version schema"); + }).catch(function (err) { + QUnit.ok(true, "Got error when trying to open non-existing DB: " + err); + // Create a non-empty database that we later on will open in other instance (see next then()-clause)... + db = new Dexie("TestDB"); + db.version(1).stores({ friends: "++id,name", pets: "++,name,kind" }); + return db.open(); + }).then(function () { + QUnit.ok(true, "Could create TestDB with specified version schema."); + db2 = new Dexie("TestDB"); // Opening another instans without specifying schema + return db2.open().then(function () { + QUnit.equal(db2.tables.length, 2, "We got two tables in database"); + QUnit.ok(db2.tables.every(function (table) { + return table.name == "friends" || table.name == "pets"; + }), "db2 contains the tables friends and pets"); + QUnit.equal(db2.table("friends").schema.primKey.name, "id", "Primary key of friends is 'id'"); + QUnit.ok(true, "Primary key of friends is auto-incremented: " + db2.table("friends").schema.primKey.auto); // Just logging. Not important for functionality. I know this fails on IE11. + QUnit.equal(db2.table("friends").schema.indexes[0].name, "name", "First index of friends table is the 'name' index"); + QUnit.ok(!db2.table("pets").schema.primKey.name, "Primary key of pets has no name (not inline)"); + QUnit.ok(true, "Primary key of pets is auto-incremented: " + db2.table("pets").schema.primKey.auto); // Just logging. Not important for functionality. I know this fails on IE11. + QUnit.equal(db2.table("pets").schema.indexes.length, 2, "Pets table has two indexes"); + }); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(function () { + db.close(); + if (db2) db2.close(); + QUnit.start(); + }); + }); + QUnit.asyncTest("Dexie.getDatabaseNames", 13, function () { + var defaultDatabases = []; + var db1, db2; + Dexie.getDatabaseNames(function (names) { + defaultDatabases = [].slice.call(names, 0); + QUnit.ok(true, "Current databases: " + (defaultDatabases.length ? defaultDatabases.join(',') : "(none)")); + db1 = new Dexie("TestDB1"); + db1.version(1).stores({}); + return db1.open(); + }).then(function () { + // One DB created + QUnit.ok(true, "TestDB1 successfully created"); + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length + 1, "Another DB has been created"); + QUnit.ok(names.indexOf("TestDB1") !== -1, "Database names now contains TestDB1"); + db2 = new Dexie("TestDB2"); + db2.version(1).stores({}); + return db2.open(); + }).then(function () { + QUnit.ok(true, "TestDB2 successfully created"); + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length + 2, "Yet another DB has been created"); + QUnit.ok(names.indexOf("TestDB2") !== -1, "Database names now contains TestDB2"); + return db1.delete(); + }).then(function () { + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length + 1, "A database has been deleted"); + QUnit.ok(!names.indexOf("TestDB1") !== -1, "TestDB1 not in database list anymore"); + return db2.delete(); + }).then(function () { + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.equal(names.length, defaultDatabases.length, "All of our databases have been deleted"); + QUnit.ok(!names.indexOf("TestDB2") !== -1, "TestDB2 not in database list anymore"); + }).then(function (names) { + return Dexie.exists("nonexistingDB"); + }).then(function (exists) { + QUnit.ok(!exists, "'nonexistingDB' should not exist indeed"); + return Dexie.getDatabaseNames(); + }).then(function (names) { + QUnit.ok(!names.indexOf("nonexistingDB") !== -1, "nonexistingDB must not have been recorded when calling Dexie.exists()"); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(function () { + (db1 ? db1.delete() : Dexie.Promise.resolve()).finally(function () { + (db2 ? db2.delete() : Dexie.Promise.resolve()).finally(QUnit.start); + }); + }); + }); + QUnit.asyncTest("Issue #76 Dexie inside Web Worker", function () { + // + // Imports to include from the web worker: + // + var imports = window.workerImports || ["../dist/dexie.js"]; + // + // Code to execute in the web worker: + // + var CodeToExecuteInWebWorker = "function CodeToExecuteInWebWorker(ok, done) {\n ok(true, \"Could enter the web worker\");\n\n Dexie.delete(\"codeFromWorker\").then(function() {\n var db = new Dexie(\"codeFromWorker\");\n ok(true, \"Could create a Dexie instance from within a web worker\");\n\n db.version(1).stores({ table1: \"++\" });\n ok(true, \"Could define schema\");\n\n db.open();\n ok(true, \"Could open the database\");\n \n return db.transaction('rw', db.table1, function() {\n ok(true, \"Could create a transaction\");\n db.table1.add({ name: \"My first object\" }).then(function(id) {\n ok(true, \"Could add object that got id \" + id);\n // Verify we workaround Safari issues with getAll() in workers\n // ... as discussed in PR #579.\n return db.table1.toArray();\n }).then(function(){\n ok(true, \"Could all toArray() on a table (verified workaround for Safari 10.1 issue with getAll())\");\n }).catch(function(err) {\n ok(false, \"Got error: \" + err);\n });\n });\n }).then(function () {\n ok(true, \"Transaction committed\");\n }).catch(function(err) {\n ok(false, \"Transaction failed: \" + err.stack);\n }).finally(done);\n }"; + // + // Frameworking... + // + if (!window.Worker) { + QUnit.ok(false, "WebWorkers not supported"); + QUnit.start(); + return; + } + var worker = new Worker(window.workerSource || "worker.js"); + worker.postMessage({ + imports: imports, + code: CodeToExecuteInWebWorker.toString() + }); + worker.onmessage = function (e) { + switch (e.data[0]) { + case "ok": + QUnit.ok(e.data[1], e.data[2]); + break; + case "done": + worker.terminate(); + QUnit.start(); + break; + } + }; + worker.onerror = function (e) { + worker.terminate(); + QUnit.ok(false, "Worker errored: " + e.message); + QUnit.start(); + }; + }); + QUnit.asyncTest("Issue#100 - not all indexes are created", function () { + var db = new Dexie("TestDB"); + db.version(20).stores({ + t: 'id,displayName,*displayNameParts,isDeleted,countryRef,[countryRef+isDeleted],autoCreated,needsReview,[autoCreated+isDeleted],[needsReview+isDeleted],[autoCreated+needsReview+isDeleted],[autoCreated+countryRef+needsReview+isDeleted],[autoCreated+countryRef+needsReview+isDeleted],[autoCreated+robotsNoIndex+isDeleted],[autoCreated+needsReview+robotsNoIndex+isDeleted],[autoCreated+countryRef+robotsNoIndex+isDeleted],[autoCreated+countryRef+needsReview+robotsNoIndex+isDeleted]' + }); + db.open().then(function () { + return Dexie.Promise.all(db.t.orderBy("id").first(), db.t.orderBy("displayName").first(), db.t.orderBy("displayNameParts").first(), db.t.orderBy("isDeleted").first(), db.t.orderBy("countryRef").first(), db.t.orderBy("[countryRef+isDeleted]").first(), db.t.orderBy("autoCreated").first(), db.t.orderBy("needsReview").first(), db.t.orderBy("[autoCreated+isDeleted]").first(), db.t.orderBy("[needsReview+isDeleted]").first(), db.t.orderBy("[autoCreated+needsReview+isDeleted]").first(), db.t.orderBy("[autoCreated+countryRef+needsReview+isDeleted]").first(), db.t.orderBy("[autoCreated+robotsNoIndex+isDeleted]").first(), db.t.orderBy("[autoCreated+needsReview+robotsNoIndex+isDeleted]").first(), db.t.orderBy("[autoCreated+countryRef+robotsNoIndex+isDeleted]").first(), db.t.orderBy("[autoCreated+countryRef+needsReview+robotsNoIndex+isDeleted]").first()); + }).then(function (res) { + QUnit.ok(false, "Should not succeed with creating the same index twice"); + }).catch(function (err) { + QUnit.ok(true, "Catched error trying to create duplicate indexes: " + err); + return db.t.toArray(); + }).then(function (a) { + QUnit.ok(false, "Database should have failed here"); + }).catch(function (err) { + QUnit.ok(true, "Got exception when trying to work agains DB: " + err); + }).then(function () { + // Close the database and open dynamically to check that + // it should not exist when failed to open. + db.close(); + db = new Dexie("TestDB"); + return db.open(); + }).then(function () { + QUnit.ok(false, "Should not succeed to open the database. It should not have been created."); + QUnit.equal(db.tables.length, 0, "At least expect no tables to have been created on the database"); + }).catch(function (err) { + QUnit.ok(true, "Should not succeed to dynamically open db because it should not exist"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Dexie.exists", function () { + var db = null; + Dexie.exists("TestDB").then(function (result) { + QUnit.equal(result, false, "Should not exist yet"); + db = new Dexie("TestDB"); + db.version(1).stores({ + some: "schema" + }); + return db.open(); + }).then(function () { + return Dexie.exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should exist now and has another open connection."); + db.close(); + return Dexie.exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should still exist"); + return Dexie.delete("TestDB"); + }).then(function () { + return Dexie.exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, false, "Should have been deleted now"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("No auto-open", function () { + var db = new Dexie("TestDB", { autoOpen: false }); + db.version(1).stores({ foo: "id" }); + db.foo.toArray(function (res) { + QUnit.ok(false, "Should not get result. Should have failed."); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Should catch DatabaseClosedError"); + }).then(function () { + db.open(); + return db.foo.toArray(); + }).then(function (res) { + QUnit.equal(res.length, 0, "Got an answer now when opened."); + db.close(); + var openPromise = db.open().then(function () { + //console.log("Why are we here? " + Dexie.Promise.reject().stack); + QUnit.ok(false, "Should not succeed to open because we closed it during the open sequence."); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Got DatabaseClosedError from the db.open() call."); + }); + var queryPromise = db.foo.toArray().then(function () { + QUnit.ok(false, "Should not succeed to query because we closed it during the open sequence."); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Got DatabaseClosedError when querying: " + e); + }); + db.close(); + return Promise.all([openPromise, queryPromise]); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("db.close", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ foo: "id" }); + db.foo.toArray(function (res) { + QUnit.equal(res.length, 0, "Database auto-opened and I got a result from my query"); + }).then(function () { + db.close(); + return db.foo.toArray(); + }).catch(function (e) { + QUnit.ok(e instanceof Dexie.DatabaseClosedError, "Should catch DatabaseClosedError"); + return db.open(); + }).then(function () { + console.log("The call to db.open() completed"); + return db.foo.toArray(); + }).then(function (res) { + QUnit.equal(res.length, 0, "Database re-opened and I got a result from my query"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(function () { + db.delete().catch(function (e) { + return console.error(e); + }).finally(QUnit.start); + }); + }); + spawnedTest("db.open several times", 2, function () { + var db; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie("TestDB"); + db.version(1).stores({ foo: "id" }); + db.on('populate', function () { + throw "Failed in populate"; + }); + db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + }); + return [4 /*yield*/, db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("#306 db.on('ready') subscriber should be called also if db is already open", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ foo: "id" }); + db.on('ready', function () { + QUnit.ok(true, "Early db.on('ready') subscriber called."); + }); + var lateSubscriberCalled = false; + db.open().then(function () { + QUnit.ok(true, "db successfully opened"); + db.on('ready', function () { + lateSubscriberCalled = true; + }); + }).then(function () { + QUnit.ok(lateSubscriberCalled, "Late db.on('ready') subscriber should also be called."); + }).catch(function (err) { + QUnit.ok(false, err.stack || err); + }).finally(QUnit.start); + }); + promisedTest("#392 db.on('ready') don't fire if subscribed while waiting other promise-returning subscriber", function () { + return __awaiter$2(_this$2, void 0, void 0, function () { + var _this = this; + var db, first, second, third; + return __generator$4(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie('TestDB'); + db.version(1).stores({ foobar: 'id' }); + first = false, second = false, third = false; + // first is registered before open + db.on('ready', function () { + return __awaiter$2(_this, void 0, void 0, function () { + return __generator$4(this, function (_a) { + first = true; + // second is registered while first is executing + db.on('ready', function () { + second = true; + }); + return [2 /*return*/]; + }); + }); + }); + return [4 /*yield*/, db.open()]; + case 1: + _a.sent(); + db.on('ready', function () { + return third = true; + }); + return [4 /*yield*/, Dexie.Promise.resolve()]; + case 2: + _a.sent(); + QUnit.ok(first, "First subscriber should have been called"); + QUnit.ok(second, "Second subscriber should have been called"); + QUnit.ok(third, "Third subscriber should have been called"); + return [2 /*return*/]; + } + }); + }); + }); + + var __generator$5 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var db$4 = new Dexie("TestYieldDb"); + var async$2 = Dexie.async; + var spawn = Dexie.spawn; + db$4.version(1).stores({ + friends: '++id,name,*groups', + pets: '++id,name' + }); + QUnit.module("yield", { + setup: function () { + QUnit.stop(); + resetDatabase(db$4).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + QUnit.asyncTest("db.transaction() with yield", async$2(function () { + var finallyWasReached, e_1; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + finallyWasReached = false; + _a.label = 1; + case 1: + _a.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, db$4.transaction('rw', 'friends', 'pets', function () { + var catId, dogId, gurra, gurrasPets; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$4.pets.add({ name: "Tito", kind: "cat" })]; + case 1: + catId = _a.sent(); + return [4 /*yield*/, db$4.pets.add({ name: "Josephina", kind: "dog" })]; + case 2: + dogId = _a.sent(); + // Add a friend who owns the pets + db$4.friends.add({ name: "Gurra G", pets: [catId, dogId] }); + return [4 /*yield*/, db$4.friends.where('name').equals("Gurra G").first()]; + case 3: + gurra = _a.sent(); + QUnit.ok(!!gurra, "Gurra could be found with yield"); + return [4 /*yield*/, db$4.pets.where('id').anyOf(gurra.pets).toArray()]; + case 4: + gurrasPets = _a.sent(); + QUnit.equal(gurrasPets.length, 2, "Gurras all two pets could be retrieved via yield"); + QUnit.equal(gurrasPets[0].kind, "cat", "Gurras first pet is a cat"); + QUnit.equal(gurrasPets[1].kind, "dog", "Gurras second pet is a dog"); + return [2 /*return*/]; + } + }); + })]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: + e_1 = _a.sent(); + QUnit.ok(false, "Caught error: " + e_1); + return [3 /*break*/, 5]; + case 4: + finallyWasReached = true; + return [7 /*endfinally*/]; + case 5: + QUnit.ok(finallyWasReached, "finally was reached"); + QUnit.start(); + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Catching indexedDB error event", 2, async$2(function () { + var e_2; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3,, 4]); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 4]; + case 3: + e_2 = _a.sent(); + QUnit.equal(e_2.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + return [3 /*break*/, 4]; + case 4: + QUnit.start(); + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Catching error prevents transaction from aborting", 5, async$2(function () { + var _a, _b; + return __generator$5(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0,, 4, 5]); + return [4 /*yield*/, db$4.transaction('rw', 'pets', function () { + var e_3; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3,, 4]); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 4]; + case 3: + e_3 = _a.sent(); + QUnit.equal(e_3.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + return [3 /*break*/, 4]; + case 4: + return [2 /*return*/]; + } + }); + })]; + case 1: + _c.sent(); + QUnit.ok(true, "Should come here - transaction committed because we caught the error"); + _a = QUnit.ok; + return [4 /*yield*/, db$4.pets.get(1)]; + case 2: + _a.apply(void 0, [_c.sent(), "A pet with ID 1 exists in DB"]); + _b = QUnit.equal; + return [4 /*yield*/, db$4.pets.get(1)]; + case 3: + _b.apply(void 0, [_c.sent().name, "Tidi", "It was Tidi in the first position"]); + return [3 /*break*/, 5]; + case 4: + QUnit.start(); + return [7 /*endfinally*/]; + case 5: + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Transaction not committing when not catching error event", 4, async$2(function () { + var e_4, _a; + return __generator$5(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, 4, 5]); + return [4 /*yield*/, db$4.transaction('rw', 'pets', function () { + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [2 /*return*/]; + } + }); + })]; + case 1: + _b.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 5]; + case 2: + e_4 = _b.sent(); + QUnit.ok(true, "Transaction should fail"); + QUnit.equal(e_4.name, "ConstraintError", "Error caught was a ConstraintError!"); + _a = QUnit.equal; + return [4 /*yield*/, db$4.pets.count()]; + case 3: + _a.apply(void 0, [_b.sent(), 0, "Pets table should still be empty because transaction failed"]); + return [3 /*break*/, 5]; + case 4: + QUnit.start(); + return [7 /*endfinally*/]; + case 5: + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding a non-promise", async$2(function () { + var x, e_5; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, 3]; + case 1: + x = _a.sent(); + QUnit.equal(x, 3, "Could yield a non-promise"); + return [3 /*break*/, 4]; + case 2: + e_5 = _a.sent(); + QUnit.ok(false, "Yielding a non-Thenable wasn't be allowed"); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an array with a mix of values and thenables", async$2(function () { + var results, e_6; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, Dexie.Promise.resolve(3)]]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return [3 /*break*/, 4]; + case 2: + e_6 = _a.sent(); + QUnit.ok(false, "Got exception when trying to do yield an array of mixed values/promises"); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an array of non-promises only", async$2(function () { + var results, e_7; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, 3]]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return [3 /*break*/, 4]; + case 2: + e_7 = _a.sent(); + QUnit.ok(false, e_7); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an empty array", async$2(function () { + var results, e_8; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, []]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 0, "Yielded array is of size 0"); + return [3 /*break*/, 4]; + case 2: + e_8 = _a.sent(); + QUnit.ok(false, e_8); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an array of different kind of any kind of promise", function () { + spawn(function () { + var results; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, [Promise.resolve(1), Dexie.Promise.resolve(2), Promise.resolve(3)]]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Throw after yield 1", function () { + spawn(function () { + var e_9; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2,, 3]); + return [4 /*yield*/, Promise.resolve(3)]; + case 1: + _a.sent(); + QUnit.ok(true, "yielded a value"); + throw "error"; + case 2: + e_9 = _a.sent(); + QUnit.ok(e_9 === "error", "Catched exception: " + e_9); + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Throw after yield 2", function () { + Promise.resolve(spawn(function () { + var e_10; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2,, 3]); + return [4 /*yield*/, 3]; + case 1: + _a.sent(); + QUnit.ok(true, "yielded a value"); + throw "error"; + case 2: + e_10 = _a.sent(); + QUnit.ok(e_10 === "error", "Catched exception: " + e_10); + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/, 4]; + } + }); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Throw before yield", function () { + Promise.resolve(spawn(function () { + return __generator$5(this, function (_a) { + try { + throw "error"; + } catch (e) { + QUnit.ok(e === "error", "Catched exception: " + e); + } + return [2 /*return*/, 4]; + }); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Catch rejected promise", function () { + spawn(function () { + var e_11; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2,, 3]); + return [4 /*yield*/, new Promise(function (resolve, reject) { + reject("fault fault!"); + })]; + case 1: + _a.sent(); + QUnit.ok(false, "Shouldn't come here"); + return [3 /*break*/, 3]; + case 2: + e_11 = _a.sent(); + QUnit.ok(e_11 === "fault fault!", "Catched exception: " + e_11); + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Catch rejected promise in an array", function () { + spawn(function () { + var e_12; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2,, 3]); + return [4 /*yield*/, [1, 2, new Promise(function (resolve, reject) { + reject("fault fault!"); + }), 4]]; + case 1: + _a.sent(); + QUnit.ok(false, "Shouldn't come here"); + return [3 /*break*/, 3]; + case 2: + e_12 = _a.sent(); + QUnit.ok(e_12 === "fault fault!", "Catched exception: " + e_12); + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Should allow returning a promise", function () { + spawn(function () { + return __generator$5(this, function (_a) { + return [2 /*return*/, Promise.resolve(3)]; + }); + }).then(function (result) { + QUnit.equal(result, 3, "Returning a directly should also be allowed"); + }).catch(function (e) { + QUnit.ok(false, e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Should be able to do 'return yield Promise.resolve(x);'", function () { + spawn(function () { + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, Promise.resolve(3)]; + case 1: + return [2 /*return*/, _a.sent()]; + } + }); + }).then(function () { + QUnit.ok(true, "Should be able to do 'return yield Promise.resolve(x);'"); + }).catch(function (e) { + QUnit.ok(false, "Error occurred: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Arrow functions and let", async$2(function () { + var x, y; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, [1, 2, Promise.resolve(3)]]; + case 1: + x = _a.sent(); + y = x.map(function (a) { + return a - 1; + }); + QUnit.equal(y[0], 0); + QUnit.equal(y[1], 1); + QUnit.equal(y[2], 2); + QUnit.start(); + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Calling sub async function", async$2(function () { + var addFriend, deleteFriends, foo, bar, numDeleted, e_13; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + addFriend = async$2(function addFriend(friend) { + var friendId; + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$4.friends.add(friend)]; + case 1: + friendId = _a.sent(); + return [4 /*yield*/, db$4.friends.get(friendId)]; + case 2: + return [2 /*return*/, _a.sent()]; + } + }); + }); + deleteFriends = async$2(function deleteFriends() { + return __generator$5(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$4.friends.where('name').anyOf("Foo", "Bar").delete()]; + case 1: + return [2 /*return*/, _a.sent()]; + } + }); + }); + _a.label = 1; + case 1: + _a.trys.push([1, 5, 6, 7]); + return [4 /*yield*/, addFriend({ name: "Foo" })]; + case 2: + foo = _a.sent(); + return [4 /*yield*/, addFriend({ name: "Bar" })]; + case 3: + bar = _a.sent(); + QUnit.ok(foo.name == "Foo", "Foo got its name"); + QUnit.ok(bar.name == "Bar", "Bar got its name"); + return [4 /*yield*/, deleteFriends()]; + case 4: + numDeleted = _a.sent(); + QUnit.ok(true, numDeleted + " friends successfully deleted"); + return [3 /*break*/, 7]; + case 5: + e_13 = _a.sent(); + QUnit.ok(false, e_13); + return [3 /*break*/, 7]; + case 6: + QUnit.start(); + return [7 /*endfinally*/]; + case 7: + return [2 /*return*/]; + } + }); + })); + + var keys = Object.keys; + var isArray = Array.isArray; + var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global; + function extend(obj, extension) { + if (typeof extension !== 'object') return obj; + keys(extension).forEach(function (key) { + obj[key] = extension[key]; + }); + return obj; + } + var getProto = Object.getPrototypeOf; + var _hasOwn = {}.hasOwnProperty; + function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); + } + function props(proto, extension) { + if (typeof extension === 'function') extension = extension(getProto(proto)); + keys(extension).forEach(function (key) { + setProp(proto, key, extension[key]); + }); + } + var defineProperty = Object.defineProperty; + function setProp(obj, prop, functionOrGetSet, options) { + defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options)); + } + function derive(Child) { + return { + from: function (Parent) { + Child.prototype = Object.create(Parent.prototype); + setProp(Child.prototype, "constructor", Child); + return { + extend: props.bind(null, Child.prototype) + }; + } + }; + } + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + function getPropertyDescriptor(obj, prop) { + var pd = getOwnPropertyDescriptor(obj, prop), + proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); + } + + /** Generate an object (hash map) based on given array. + * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to + * instert on the resulting object for each item in the array. If this function returns a falsy value, the + * current item wont affect the resulting object. + */ + + function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } catch (ex) { + onerror && onerror(ex); + } + } + + var concat = [].concat; + function flatten(a) { + return concat.apply([], a); + } + //https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm + var intrinsicTypes = "Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set".split(',').concat(flatten([8, 16, 32, 64].map(function (num) { + return ["Int", "Uint", "Float"].map(function (t) { + return t + num + "Array"; + }); + }))).filter(function (t) { + return _global[t]; + }).map(function (t) { + return _global[t]; + }); + + // If first argument is iterable or array-like, return it as an array + var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator; + var getIteratorOf = iteratorSymbol ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); + } : function () { + return null; + }; + var NO_CHAR_ARRAY = {}; + // Takes one or several arguments and returns an array based on the following criteras: + // * If several arguments provided, return arguments converted to an array in a way that + // still allows javascript engine to optimize the code. + // * If single argument is an array, return a clone of it. + // * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special + // case to the two bullets below. + // * If single argument is an iterable, convert it to an array and return the resulting array. + // * If single argument is array-like (has length of type number), convert it to an array. + function getArrayOf(arrayLike) { + var i, a, x, it; + if (arguments.length === 1) { + if (isArray(arrayLike)) return arrayLike.slice(); + if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike]; + if (it = getIteratorOf(arrayLike)) { + a = []; + while (x = it.next(), !x.done) a.push(x.value); + return a; + } + if (arrayLike == null) return [arrayLike]; + i = arrayLike.length; + if (typeof i === 'number') { + a = new Array(i); + while (i--) a[i] = arrayLike[i]; + return a; + } + return [arrayLike]; + } + i = arguments.length; + a = new Array(i); + while (i--) a[i] = arguments[i]; + return a; + } + + function nop() {} + function mirror(val) { + return val; + } + + function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; + } + + // By default, debug will be true only if platform is a web platform and its page is served from localhost. + // When debug = true, error's stacks will contain asyncronic long stacks. + var debug = typeof location !== 'undefined' && + // By default, use debug mode if served from localhost. + /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); + + var libraryFilter = function () { + return true; + }; + var NEEDS_THROW_FOR_STACK = !new Error("").stack; + function getErrorWithStack() { + "use strict"; + + if (NEEDS_THROW_FOR_STACK) try { + // Doing something naughty in strict mode here to trigger a specific error + // that can be explicitely ignored in debugger's exception settings. + // If we'd just throw new Error() here, IE's debugger's exception settings + // will just consider it as "exception thrown by javascript code" which is + // something you wouldn't want it to ignore. + getErrorWithStack.arguments; + throw new Error(); // Fallback if above line don't throw. + } catch (e) { + return e; + } + return new Error(); + } + function prettyStack(exception, numIgnoredFrames) { + var stack = exception.stack; + if (!stack) return ""; + numIgnoredFrames = numIgnoredFrames || 0; + if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length; + return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) { + return "\n" + frame; + }).join(''); + } + + var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'PrematureCommit', 'ForeignAwait']; + var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone']; + var errorList = dexieErrorNames.concat(idbDomErrorNames); + var defaultTexts = { + VersionChanged: "Database version changed by other database connection", + DatabaseClosed: "Database has been closed", + Abort: "Transaction aborted", + TransactionInactive: "Transaction has already completed or failed" + }; + // + // DexieError - base class of all out exceptions. + // + function DexieError(name, msg) { + // Reason we don't use ES6 classes is because: + // 1. It bloats transpiled code and increases size of minified code. + // 2. It doesn't give us much in this case. + // 3. It would require sub classes to call super(), which + // is not needed when deriving from Error. + this._e = getErrorWithStack(); + this.name = name; + this.message = msg; + } + derive(DexieError).from(Error).extend({ + stack: { + get: function () { + return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2)); + } + }, + toString: function () { + return this.name + ": " + this.message; + } + }); + function getMultiErrorMessage(msg, failures) { + return msg + ". Errors: " + failures.map(function (f) { + return f.toString(); + }).filter(function (v, i, s) { + return s.indexOf(v) === i; + }) // Only unique error strings + .join('\n'); + } + // + // ModifyError - thrown in Collection.modify() + // Specific constructor because it contains members failures and failedKeys. + // + function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + } + derive(ModifyError).from(DexieError); + function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = failures; + this.message = getMultiErrorMessage(msg, failures); + } + derive(BulkError).from(DexieError); + // + // + // Dynamically generate error names and exception classes based + // on the names in errorList. + // + // + // Map of {ErrorName -> ErrorName + "Error"} + var errnames = errorList.reduce(function (obj, name) { + return obj[name] = name + "Error", obj; + }, {}); + // Need an alias for DexieError because we're gonna create subclasses with the same name. + var BaseException = DexieError; + // Map of {ErrorName -> exception constructor} + var exceptions = errorList.reduce(function (obj, name) { + // Let the name be "DexieError" because this name may + // be shown in call stack and when debugging. DexieError is + // the most true name because it derives from DexieError, + // and we cannot change Function.name programatically without + // dynamically create a Function object, which would be considered + // 'eval-evil'. + var fullName = name + "Error"; + function DexieError(msgOrInner, inner) { + this._e = getErrorWithStack(); + this.name = fullName; + if (!msgOrInner) { + this.message = defaultTexts[name] || fullName; + this.inner = null; + } else if (typeof msgOrInner === 'string') { + this.message = msgOrInner; + this.inner = inner || null; + } else if (typeof msgOrInner === 'object') { + this.message = msgOrInner.name + " " + msgOrInner.message; + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name] = DexieError; + return obj; + }, {}); + // Use ECMASCRIPT standard exceptions where applicable: + exceptions.Syntax = SyntaxError; + exceptions.Type = TypeError; + exceptions.Range = RangeError; + var exceptionMap = idbDomErrorNames.reduce(function (obj, name) { + obj[name + "Error"] = exceptions[name]; + return obj; + }, {}); + + var fullNameExceptions = errorList.reduce(function (obj, name) { + if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name]; + return obj; + }, {}); + fullNameExceptions.ModifyError = ModifyError; + fullNameExceptions.DexieError = DexieError; + fullNameExceptions.BulkError = BulkError; + + /* + * Copyright (c) 2014-2017 David Fahlander + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + */ + // + // Promise and Zone (PSD) for Dexie library + // + // I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by + // https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. + // + // In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another + // tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use + // another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task + // engine that is indexedDB compliant across all browsers. + // Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. + // Also with inspiration from bluebird, asyncronic stacks in debug mode. + // + // Specific non-standard features of this Promise class: + // * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as + // native async / await. + // * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame + // and below + all promises that those promises creates or awaits. + // * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). + // + // David Fahlander, https://github.com/dfahlander + // + // Just a pointer that only this module knows about. + // Used in Promise constructor to emulate a private constructor. + var INTERNAL = {}; + // Async stacks (long stacks) must not grow infinitely. + var LONG_STACKS_CLIP_LIMIT = 100; + var MAX_LONG_STACKS = 20; + var ZONE_ECHO_LIMIT = 7; + var nativePromiseInstanceAndProto = function () { + try { + // Be able to patch native async functions + return new Function("let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];")(); + } catch (e) { + var P = _global.Promise; + return P ? [P.resolve(), P.prototype, P.resolve()] : []; + } + }(); + var resolvedNativePromise = nativePromiseInstanceAndProto[0]; + var nativePromiseProto = nativePromiseInstanceAndProto[1]; + var resolvedGlobalPromise = nativePromiseInstanceAndProto[2]; + var nativePromiseThen = nativePromiseProto && nativePromiseProto.then; + var NativePromise$2 = resolvedNativePromise && resolvedNativePromise.constructor; + + var patchGlobalPromise = !!resolvedGlobalPromise; + var stack_being_generated = false; + /* The default function used only for the very first promise in a promise chain. + As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks + emulated in this module. For indexedDB compatibility, this means that every method needs to + execute at least one promise before doing an indexedDB operation. Dexie will always call + db.ready().then() for every operation to make sure the indexedDB event is started in an + indexedDB-compatible emulated micro task loop. + */ + var schedulePhysicalTick = resolvedGlobalPromise ? function () { + resolvedGlobalPromise.then(physicalTick); + } : _global.setImmediate ? + // setImmediate supported. Those modern platforms also supports Function.bind(). + setImmediate.bind(null, physicalTick) : _global.MutationObserver ? + // MutationObserver supported + function () { + var hiddenDiv = document.createElement("div"); + new MutationObserver(function () { + physicalTick(); + hiddenDiv = null; + }).observe(hiddenDiv, { attributes: true }); + hiddenDiv.setAttribute('i', '1'); + } : + // No support for setImmediate or MutationObserver. No worry, setTimeout is only called + // once time. Every tick that follows will be our emulated micro tick. + // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug + function () { + setTimeout(physicalTick, 0); + }; + // Configurable through Promise.scheduler. + // Don't export because it would be unsafe to let unknown + // code call it unless they do try..catch within their callback. + // This function can be retrieved through getter of Promise.scheduler though, + // but users must not do Promise.scheduler = myFuncThatThrowsException + var asap$$1 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } + }; + var isOutsideMicroTick = true; + var needsNewPhysicalTick = true; + var unhandledErrors = []; + var rejectingErrors = []; + var currentFulfiller = null; + var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions + var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: globalError, + pgp: false, + env: {}, + finalize: function () { + this.unhandleds.forEach(function (uh) { + try { + globalError(uh[0], uh[1]); + } catch (e) {} + }); + } + }; + var PSD = globalPSD; + var microtickQueue = []; // Callbacks to call in this or next physical tick. + var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. + var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. + function Promise$1(fn) { + if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler. + // A library may set `promise._lib = true;` after promise is created to make resolve() or reject() + // execute the microtask engine implicitely within the call to resolve() or reject(). + // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack + // only contains library code when calling resolve() or reject(). + // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from + // global scope (event handler, timer etc)! + this._lib = false; + // Current async scope + var psd = this._PSD = PSD; + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; // Number of previous promises (for long stacks) + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) throw new TypeError('Not a function'); + // Private constructor (INTERNAL, state, value). + // Used internally by Promise.resolve() and Promise.reject(). + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError(). + return; + } + this._state = null; // null (=pending), false (=rejected) or true (=resolved) + this._value = null; // error or result + ++psd.ref; // Refcounting current scope + executePromiseTask(this, fn); + } + // Prepare a property descriptor to put onto Promise.prototype.then + var thenProp = { + get: function () { + var psd = PSD, + microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + if (possibleAwait) decrementExpectedAwaits(); + var rv = new Promise$1(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; // For idempotense, see setter below. + return then; + }, + // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then + // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor. + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? thenProp : // Restore to original property descriptor. + { + get: function () { + return value; // Getter returning provided value (behaves like value is just changed) + }, + set: thenProp.set // Keep a setter that is prepared to restore original. + }); + } + }; + props(Promise$1.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + // A little tinier version of then() that don't have to create a resulting promise. + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) return this.then(null, onRejected); + // First argument is the Error type to catch + var type = arguments[0], + handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + // Catching errors by its constructor type (similar to java / c++ / c#) + // Sample: promise.catch(TypeError, function (e) { ... }); + return err instanceof type ? handler(err) : PromiseReject(err); + }) : this.then(null, function (err) { + // Catching errors by the error.name property. Makes sense for indexedDB where error type + // is always DOMError but where e.name tells the actual error type. + // Sample: promise.catch('ConstraintError', function (e) { ... }); + return err && err.name === type ? handler(err) : PromiseReject(err); + }); + }, + finally: function (onFinally) { + return this.then(function (value) { + onFinally(); + return value; + }, function (err) { + onFinally(); + return PromiseReject(err); + }); + }, + stack: { + get: function () { + if (this._stack) return this._stack; + try { + stack_being_generated = true; + var stacks = getStack(this, [], MAX_LONG_STACKS); + var stack = stacks.join("\nFrom previous: "); + if (this._state !== null) this._stack = stack; // Stack may be updated on reject. + return stack; + } finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? new Promise$1(function (resolve, reject) { + var handle = setTimeout(function () { + return reject(new exceptions.Timeout(msg)); + }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } + }); + if (typeof Symbol !== 'undefined' && Symbol.toStringTag) setProp(Promise$1.prototype, Symbol.toStringTag, 'Promise'); + // Now that Promise.prototype is defined, we have all it takes to set globalPSD.env. + // Environment globals snapshotted on leaving global zone + globalPSD.env = snapShot(); + function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; + } + // Promise Static Properties + props(Promise$1, { + all: function () { + var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like. + .map(onPossibleParallellAsync); // Handle parallell async/awaits + return new Promise$1(function (resolve, reject) { + if (values.length === 0) resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { + return Promise$1.resolve(a).then(function (x) { + values[i] = x; + if (! --remaining) resolve(values); + }, reject); + }); + }); + }, + resolve: function (value) { + if (value instanceof Promise$1) return value; + if (value && typeof value.then === 'function') return new Promise$1(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new Promise$1(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new Promise$1(function (resolve, reject) { + values.map(function (value) { + return Promise$1.resolve(value).then(resolve, reject); + }); + }); + }, + PSD: { + get: function () { + return PSD; + }, + set: function (value) { + return PSD = value; + } + }, + //totalEchoes: {get: ()=>totalEchoes}, + //task: {get: ()=>task}, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { + return asap$$1; + }, + set: function (value) { + asap$$1 = value; + } + }, + rejectionMapper: { + get: function () { + return rejectionMapper; + }, + set: function (value) { + rejectionMapper = value; + } // Map reject failures + }, + follow: function (fn, zoneProps) { + return new Promise$1(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize() + psd.onunhandled = reject; // Triggered directly on unhandled promises of this library. + psd.finalize = callBoth(function () { + var _this = this; + // Unhandled standard or 3rd part promises are put in PSD.unhandleds and + // examined upon scope completion while unhandled rejections in this Promise + // will trigger directly through psd.onunhandled + run_at_end_of_this_or_next_physical_tick(function () { + _this.unhandleds.length === 0 ? resolve() : reject(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } + }); + /** + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. + * + * Makes no guarantees about asynchrony. + */ + function executePromiseTask(promise, fn) { + // Promise Resolution Procedure: + // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + try { + fn(function (value) { + if (promise._state !== null) return; // Already settled + if (value === promise) throw new TypeError('A promise cannot be resolved with itself.'); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === 'function') { + executePromiseTask(promise, function (resolve, reject) { + value instanceof Promise$1 ? value._then(resolve, reject) : value.then(resolve, reject); + }); + } else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) endMicroTickScope(); + }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below + } catch (ex) { + handleRejection(promise, ex); + } + } + function handleRejection(promise, reason) { + rejectingErrors.push(reason); + if (promise._state !== null) return; + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + reason = rejectionMapper(reason); + promise._state = false; + promise._value = reason; + debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(function () { + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: function () { + return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack; + } + }); + }); + // Add the failure to a list of possibly uncaught errors + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) endMicroTickScope(); + } + function propagateAllListeners(promise) { + //debug && linkToPreviousPromise(promise); + var listeners = promise._listeners; + promise._listeners = []; + for (var i = 0, len = listeners.length; i < len; ++i) { + propagateToListener(promise, listeners[i]); + } + var psd = promise._PSD; + --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize(); + if (numScheduledCalls === 0) { + // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call, + // and that no deferreds where listening to this rejection or success. + // Since there is a risk that our stack can contain application code that may + // do stuff after this code is finished that may generate new calls, we cannot + // call finalizers here. + ++numScheduledCalls; + asap$$1(function () { + if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors + }, []); + } + } + function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch() + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap$$1(callListener, [cb, promise, listener]); + } + function callListener(cb, promise, listener) { + try { + // Set static variable currentFulfiller to the promise that is being fullfilled, + // so that we connect the chain of promises (for long stacks support) + currentFulfiller = promise; + // Call callback and resolve our listener with it's return value. + var ret, + value = promise._value; + if (promise._state) { + // cb is onResolved + ret = cb(value); + } else { + // cb is onRejected + if (rejectingErrors.length) rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise. + } + listener.resolve(ret); + } catch (e) { + // Exception thrown in callback. Reject our listener. + listener.reject(e); + } finally { + // Restore env and currentFulfiller. + currentFulfiller = null; + if (--numScheduledCalls === 0) finalizePhysicalTick(); + --listener.psd.ref || listener.psd.finalize(); + } + } + function getStack(promise, stacks, limit) { + if (stacks.length === limit) return stacks; + var stack = ""; + if (promise._state === false) { + var failure = promise._value, + errorName, + message; + if (failure != null) { + errorName = failure.name || "Error"; + message = failure.message || failure; + stack = prettyStack(failure, 0); + } else { + errorName = failure; // If error is undefined or null, show that. + message = ""; + } + stacks.push(errorName + (message ? ": " + message : "") + stack); + } + if (debug) { + stack = prettyStack(promise._stackHolder, 2); + if (stack && stacks.indexOf(stack) === -1) stacks.push(stack); + if (promise._prev) getStack(promise._prev, stacks, limit); + } + return stacks; + } + function linkToPreviousPromise(promise, prev) { + // Support long stacks by linking to previous completed promise. + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } + } + /* The callback to schedule with setImmediate() or setTimeout(). + It runs a virtual microtick and executes any callback registered in microtickQueue. + */ + function physicalTick() { + beginMicroTickScope() && endMicroTickScope(); + } + function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; + } + /* Executes micro-ticks without doing try..catch. + This can be possible because we only use this internally and + the registered functions are exception-safe (they do try..catch + internally before calling any external method). If registering + functions in the microtickQueue that are not exception-safe, this + would destroy the framework and make it instable. So we don't export + our asap method. + */ + function endMicroTickScope() { + var callbacks, i, l; + do { + while (microtickQueue.length > 0) { + callbacks = microtickQueue; + microtickQueue = []; + l = callbacks.length; + for (i = 0; i < l; ++i) { + var item = callbacks[i]; + item[0].apply(null, item[1]); + } + } + } while (microtickQueue.length > 0); + isOutsideMicroTick = true; + needsNewPhysicalTick = true; + } + function finalizePhysicalTick() { + var unhandledErrs = unhandledErrors; + unhandledErrors = []; + unhandledErrs.forEach(function (p) { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list. + var i = finalizers.length; + while (i) finalizers[--i](); + } + function run_at_end_of_this_or_next_physical_tick(fn) { + function finalizer() { + fn(); + tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); + } + tickFinalizers.push(finalizer); + ++numScheduledCalls; + asap$$1(function () { + if (--numScheduledCalls === 0) finalizePhysicalTick(); + }, []); + } + function addPossiblyUnhandledError(promise) { + // Only add to unhandledErrors if not already there. The first one to add to this list + // will be upon the first rejection so that the root cause (first promise in the + // rejection chain) is the one listed. + if (!unhandledErrors.some(function (p) { + return p._value === promise._value; + })) unhandledErrors.push(promise); + } + function markErrorAsHandled(promise) { + // Called when a reject handled is actually being called. + // Search in unhandledErrors for any promise whos _value is this promise_value (list + // contains only rejected promises, and only one item per error) + var i = unhandledErrors.length; + while (i) if (unhandledErrors[--i]._value === promise._value) { + // Found a promise that failed with this same error object pointer, + // Remove that since there is a listener that actually takes care of it. + unhandledErrors.splice(i, 1); + return; + } + } + function PromiseReject(reason) { + return new Promise$1(INTERNAL, false, reason); + } + + // + // variables used for native await support + // + var task = { awaits: 0, echoes: 0, id: 0 }; // The ongoing macro-task when using zone-echoing. + var taskCounter = 0; // ID counter for macro tasks. + var zoneStack = []; // Stack of left zones to restore asynchronically. + var zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions. + var totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then. + var zone_id_counter = 0; + function newScope(fn, props$$1, a1, a2) { + var parent = PSD, + psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + // Prepare for promise patching (done in usePSD): + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: Promise$1, + PromiseProp: { value: Promise$1, configurable: true, writable: true }, + all: Promise$1.all, + race: Promise$1.race, + resolve: Promise$1.resolve, + reject: Promise$1.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) // global then + } : {}; + if (props$$1) extend(psd, props$$1); + // unhandleds and onunhandled should not be specifically set here. + // Leave them on parent prototype. + // unhandleds.push(err) will push to parent's prototype + // onunhandled() will call parents onunhandled (with this scope's this-pointer though!) + ++parent.ref; + psd.finalize = function () { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2); + if (psd.ref === 0) psd.finalize(); + return rv; + } + // Function to call if scopeFunc returns NativePromise + // Also for each NativePromise in the arguments to Promise.all() + function incrementExpectedAwaits() { + if (!task.id) task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; + } + // Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called. + // Also call this when a native await calls then method on a promise. In that case, don't supply + // sourceTaskId because we already know it refers to current task. + function decrementExpectedAwaits(sourceTaskId) { + if (!task.awaits || sourceTaskId && sourceTaskId !== task.id) return; + if (--task.awaits === 0) task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0. + } + // Call from Promise.all() and Promise.race() + function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise$2) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; + } + function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; // Cancel zone echoing. + } + zoneStack.push(PSD); + switchToZone(targetZone, true); + } + function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); + } + function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (! --zoneEchoes || targetZone !== PSD)) { + // Enter or leave zone asynchronically as well, so that tasks initiated during current tick + // will be surrounded by the zone when they are invoked. + enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) return; + PSD = targetZone; // The actual zone switch occurs at this line. + // Snapshot on every leave from global zone. + if (currentZone === globalPSD) globalPSD.env = snapShot(); + if (patchGlobalPromise) { + // Let's patch the global and native Promises (may be same or may be different) + var GlobalPromise = globalPSD.env.Promise; + // Swich environments (may be PSD-zone or the global zone. Both apply.) + var targetEnv = targetZone.env; + // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed) + // Must be done on each zone change because the patched method contains targetZone in its closure. + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + // Leaving or entering global zone. It's time to patch / restore global Promise. + // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular. + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might + // not be accessing global.Promise but a local reference to it) + GlobalPromise.all = targetEnv.all; + GlobalPromise.race = targetEnv.race; + GlobalPromise.resolve = targetEnv.resolve; + GlobalPromise.reject = targetEnv.reject; + } + } + } + function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject, + nthen: nativePromiseProto.then, + gthen: GlobalPromise.prototype.then + } : {}; + } + function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } finally { + switchToZone(outerScope, false); + } + } + function enqueueNativeMicroTask(job) { + // + // Precondition: nativePromiseThen !== undefined + // + nativePromiseThen.call(resolvedNativePromise, job); + } + function nativeAwaitCompatibleWrap(fn, zone, possibleAwait) { + return typeof fn !== 'function' ? fn : function () { + var outerZone = PSD; + if (possibleAwait) incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } finally { + switchToZone(outerZone, false); + } + }; + } + function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone, false), nativeAwaitCompatibleWrap(onRejected, zone, false)); + }; + } + var UNHANDLEDREJECTION = "unhandledrejection"; + function globalError(err, promise) { + var rv; + try { + rv = promise.onuncatched(err); + } catch (e) {} + if (rv !== false) try { + var event, + eventData = { promise: promise, reason: err }; + if (_global.document && document.createEvent) { + event = document.createEvent('Event'); + event.initEvent(UNHANDLEDREJECTION, true, true); + extend(event, eventData); + } else if (_global.CustomEvent) { + event = new CustomEvent(UNHANDLEDREJECTION, { detail: eventData }); + extend(event, eventData); + } + if (event && _global.dispatchEvent) { + dispatchEvent(event); + if (!_global.PromiseRejectionEvent && _global.onunhandledrejection) + // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it. + try { + _global.onunhandledrejection(event); + } catch (_) {} + } + if (!event.defaultPrevented) { + console.warn("Unhandled rejection: " + (err.stack || err)); + } + } catch (e) {} + } + var rejection = Promise$1.reject; + + var __extends = undefined && undefined.__extends || function () { + var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return function (d, b) { + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + }(); + var __awaiter$4 = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$7 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _resolve = NativePromise$2.resolve.bind(NativePromise$2); + var _then = NativePromise$2.prototype.then; + var IdbPromiseIncompatibleError = /** @class */function (_super) { + __extends(IdbPromiseIncompatibleError, _super); + function IdbPromiseIncompatibleError() { + var _this = _super.call(this, "IndexedDB and Promise are incompatible on this browser") || this; + _this.name = "IdbPromiseIncompatibleError"; + return _this; + } + return IdbPromiseIncompatibleError; + }(Error); + function isIdbAndPromiseCompatible() { + return __awaiter$4(this, void 0, void 0, function () { + var _this = this; + var db; + return __generator$7(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie("idbPromiseCompatTest"); + db.version(1).stores({ foo: 'bar' }); + return [4 /*yield*/, db.transaction('r', db.foo, function () { + return __awaiter$4(_this, void 0, void 0, function () { + var x, p, i, result, ex_1; + return __generator$7(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db.foo.count()]; + case 1: + x = _a.sent(); + p = _resolve(0); + for (i = 0; i < 10; ++i) { + p = _then.call(p, function (x) { + return x + 1; + }); + } + return [4 /*yield*/, p]; + case 2: + result = _a.sent(); + console.log("Result: " + result + " (should be 10"); + _a.label = 3; + case 3: + _a.trys.push([3, 5,, 6]); + return [4 /*yield*/, db.foo.count()]; + case 4: + _a.sent(); + db.close(); + return [2 /*return*/, true]; + case 5: + ex_1 = _a.sent(); + db.close(); + throw new IdbPromiseIncompatibleError(); + case 6: + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + return [2 /*return*/, _a.sent()]; + } + }); + }); + } + + var __awaiter$3 = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$6 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _this$3 = undefined; + var idbAndPromiseCompatible = isIdbAndPromiseCompatible(); + var hasNativeAsyncFunctions = false; + try { + hasNativeAsyncFunctions = !!new Function("return (async ()=>{})();")().then; + } catch (e) {} + var db$5 = new Dexie("TestDBTranx"); + db$5.version(1).stores({ + items: "id" + }); + QUnit.module("asyncawait", { + setup: function (assert) { + var done = assert.async(); + resetDatabase(db$5).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(done); + }, + teardown: function () {} + }); + QUnit.test("Should be able to use global Promise within transaction scopes", function (assert) { + var done = assert.async(); + db$5.transaction('rw', db$5.items, function (trans) { + return window.Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$5.items.add({ id: "foobar" }); + }).then(function () { + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie.currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$5.items.get('foobar'); + }); + }).then(function (foobar) { + QUnit.equal(foobar.id, 'foobar', "Transaction should have lived throughout the Promise.resolve() chain"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + (e.stack || e)); + }).finally(done); + }); + QUnit.test("Should be able to use native async await", function (assert) { + var done = assert.async(); + Dexie.Promise.resolve(idbAndPromiseCompatible).then(function () { + var f = new Function('ok', 'equal', 'Dexie', 'db', "return db.transaction('rw', db.items, async ()=>{\n let trans = Dexie.currentTransaction;\n ok(!!trans, \"Should have a current transaction\");\n await db.items.add({id: 'foo'});\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of Dexie.Promise\");\n await Dexie.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of Dexie.Promise synch\");\n await window.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of global Promise\");\n await 3;\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of primitive(!)\");\n await db.transaction('r', db.items, async innerTrans => {\n ok(!!innerTrans, \"SHould have inner transaction\");\n equal(Dexie.currentTransaction, innerTrans, \"Inner transaction should be there\");\n equal(innerTrans.parent, trans, \"Parent transaction should be correct\");\n let x = await db.items.get(1);\n ok(Dexie.currentTransaction === innerTrans, \"Transaction persisted in inner transaction\");\n });\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of sub transaction\");\n await (async ()=>{\n return await db.items.get(1);\n })();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of async function\");\n await (async ()=>{\n await Promise.all([db.transaction('r', db.items, async() => {\n await db.items.get(1);\n await db.items.get(2);\n }), db.transaction('r', db.items, async() => {\n return await db.items.get(1);\n })]);\n })();\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of async function 2\");\n\n await window.Promise.resolve().then(()=>{\n ok(Dexie.currentTransaction === trans, \"Transaction persisted after window.Promise.resolve().then()\");\n return (async ()=>{})(); // Resolve with native promise\n }).then(()=>{\n ok(Dexie.currentTransaction === trans, \"Transaction persisted after native promise completion\");\n return window.Promise.resolve();\n }).then(()=>{\n ok(Dexie.currentTransaction === trans, \"Transaction persisted after window.Promise.resolve().then()\");\n return (async ()=>{})();\n });\n ok(Dexie.currentTransaction === trans, \"Transaction persisted between await calls of mixed promises\");\n \n try {\n let foo = await db.items.get('foo');\n ok(true, \"YOUR BROWSER HAS COMPATIBILITY BETWEEN NATIVE PROMISES AND INDEXEDDB!\");\n } catch (e) {\n ok(true, \"Browser has no compatibility between native promises and indexedDB.\");\n }\n })"); + return f(QUnit.ok, QUnit.equal, Dexie, db$5); + }).catch('IdbPromiseIncompatibleError', function (e) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails in idb transaction by reality"); + }).catch(function (e) { + if (hasNativeAsyncFunctions) QUnit.ok(false, "Error: " + (e.stack || e));else QUnit.ok(true, "This browser does not support native async functions"); + }).then(done); + }); + var NativePromise$1 = function () { + try { + return new Function("return (async ()=>{})().constructor")(); + } catch (e) { + return window.Promise; + } + }(); + QUnit.test("Must not leak PSD zone", function (assert) { + return __awaiter$3(this, void 0, void 0, function () { + var done, compatiblity, F; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + done = assert.async(); + return [4 /*yield*/, idbAndPromiseCompatible.catch(function (e) { + return false; + })]; + case 1: + compatiblity = _a.sent(); + if (!compatiblity) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\""); + done(); + return [2 /*return*/]; + } + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + done(); + return [2 /*return*/]; + } + F = new Function('ok', 'equal', 'Dexie', 'db', "\n ok(Dexie.currentTransaction === null, \"Should not have an ongoing transaction to start with\");\n var trans1, trans2;\n var p1 = db.transaction('r', db.items, async ()=> {\n var trans = trans1 = Dexie.currentTransaction;\n await db.items.get(1); // Just to prohibit IDB bug in Safari - must use transaction in initial tick!\n await 3;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.0 - after await 3\");\n await 4;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.0 - after await 4\");\n await 5;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.0 - after await 5\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.1 - after db.items.get(1)\");\n await 6;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.1 - after await 6\");\n await subFunc(1);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.2 - after async subFunc()\");\n await Promise.all([subFunc(11), subFunc(12), subFunc(13)]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.3 - after Promise.all()\");\n await subFunc2_syncResult();\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.4 - after async subFunc_syncResult()\");\n await Promise.all([subFunc2_syncResult(), subFunc2_syncResult(), subFunc2_syncResult()]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 1.5 - after Promise.all(sync results)\");\n });\n var p2 = db.transaction('r', db.items, async ()=> {\n var trans = trans2 = Dexie.currentTransaction;\n await db.items.get(1); // Just to prohibit IDB bug in Safari - must use transaction in initial tick!\n ok(trans1 !== trans2, \"Parallell transactions must be different from each other\");\n await 3;\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.0 - after await 3\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.1 - after db.items.get(1)\");\n await subFunc(2);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.2 - after async subFunc()\");\n await Promise.all([subFunc(21), subFunc(22), subFunc(23)]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.3 - after Promise.all()\");\n await subFunc2_syncResult();\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.4 - after async subFunc_syncResult()\");\n await Promise.all([subFunc2_syncResult(), subFunc2_syncResult(), subFunc2_syncResult()]);\n ok(Dexie.currentTransaction === trans, \"Should still be in same transaction 2.5 - after Promise.all(sync results)\");\n });\n //var p2 = Promise.resolve();\n ok(Dexie.currentTransaction === null, \"Should not have an ongoing transaction after transactions\");\n\n async function subFunc(n) {\n await 3;\n let result = await db.items.get(2);\n return result;\n }\n\n async function subFunc2_syncResult() {\n let result = await 3;\n return result;\n }\n \n return Promise.all([p1, p2]);\n "); + F(QUnit.ok, QUnit.equal, Dexie, db$5).catch(function (e) { + return QUnit.ok(false, e.stack || e); + }).then(done); + return [2 /*return*/]; + } + }); + }); + }); + QUnit.test("Must not leak PSD zone2", function (assert) { + return __awaiter$3(this, void 0, void 0, function () { + var done; + return __generator$6(this, function (_a) { + done = assert.async(); + QUnit.ok(Dexie.currentTransaction === null, "Should not have an ongoing transaction to start with"); + db$5.transaction('rw', db$5.items, function () { + var trans = Dexie.currentTransaction; + QUnit.ok(trans !== null, "Should have a current transaction"); + var otherZonePromise; + Dexie.ignoreTransaction(function () { + QUnit.ok(Dexie.currentTransaction == null, "No Transaction in this zone"); + function promiseFlow() { + return NativePromise$1.resolve().then(function () { + if (Dexie.currentTransaction !== null) QUnit.ok(false, "PSD zone leaked"); + return new NativePromise$1(function (resolve) { + return NativePromise$1.resolve().then(resolve); + }); + }); + } + + otherZonePromise = promiseFlow(); + for (var i = 0; i < 100; ++i) { + otherZonePromise = otherZonePromise.then(promiseFlow); + } + }); + // In parallell with the above 2*100 async tasks are being executed and verified, + // maintain the transaction zone below: + return db$5.items.get(1).then(function () { + return idbAndPromiseCompatible; + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 1"); + // Make sure native async functions maintains the zone: + var f = new Function('ok', 'equal', 'Dexie', 'trans', 'NativePromise', 'db', "return (async ()=>{\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.1\");\n await Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.2\");\n await Dexie.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.3\");\n await window.Promise.resolve();\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1.4\");\n await db.items.get(1);\n })()"); + return f(QUnit.ok, QUnit.equal, Dexie, trans, NativePromise$1, db$5); + }).catch(function (e) { + // Could not test native async functions in this browser. + if (e.name === 'IdbPromiseIncompatibleError') { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + } else if (hasNativeAsyncFunctions) QUnit.ok(false, "Error: " + (e.stack || e));else QUnit.ok(true, "This browser does not support native async functions"); + }).then(function () { + // NativePromise + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 2"); + return Promise.resolve(); + }).then(function () { + // window.Promise + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 3"); + return Dexie.Promise.resolve(); + }).then(function () { + // Dexie.Promise + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 4"); + return otherZonePromise; // wait for the foreign zone promise to complete. + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still same transaction 5"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + (e.stack || e)); + }).then(done); + return [2 /*return*/]; + }); + }); + }); + QUnit.test("Should be able to await Promise.all()", function (assert) { + return __awaiter$3(_this$3, void 0, void 0, function () { + var done, compatible; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + done = assert.async(); + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + done(); + return [2 /*return*/]; + } + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { + return false; + })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + done(); + return [2 /*return*/]; + } + new Function('ok', 'equal', 'Dexie', 'db', "return db.transaction('r', db.items, async (trans)=>{\n ok(Dexie.currentTransaction === trans, \"Correct initial transaction.\");\n await db.items.get(1); // Just to prohibit IDB bug in Safari - must use transaction in initial tick!\n var promises = [];\n for (var i=0; i<50; ++i) {\n promises.push(subAsync1(trans));\n }\n for (var i=0; i<50; ++i) {\n promises.push(subAsync2(trans));\n }\n await Promise.all(promises);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1 - after await Promise.all([100 promises...]);\");\n await Promise.all([1,2,3, db.items.get(2)]);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 2 - after Promise.all(1,2,3,db.items.get(2))\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 3 - after await db.items.get(1);\");\n await 3;\n ok(Dexie.currentTransaction === trans, \"Still same transaction 4 - after await 3;\");\n });\n\n async function subAsync1 (trans) {\n await 1;\n await 2;\n await 3;\n if (Dexie.currentTransaction !== trans) ok(false, \"Not in transaction\");\n }\n\n async function subAsync2 (trans) {\n await 1;\n await 2;\n if (Dexie.currentTransaction !== trans) ok(false, \"Not in transaction 2\");\n await db.items.get(1);\n }\n ")(QUnit.ok, QUnit.equal, Dexie, db$5).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).then(done); + return [2 /*return*/]; + } + }); + }); + }); + spawnedTest("Should use Promise.all where applicable", function () { + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { + var x, all; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, Promise.resolve(3)]; + case 1: + x = _a.sent(); + return [4 /*yield*/, db$5.items.bulkAdd([{ id: 'a' }, { id: 'b' }])]; + case 2: + _a.sent(); + return [4 /*yield*/, Promise.all([db$5.items.get('a'), db$5.items.get('b')])]; + case 3: + all = _a.sent(); + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + return [4 /*yield*/, Promise.all([db$5.items.get('a'), db$5.items.get('b')])]; + case 4: + all = _a.sent(); + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + return [2 /*return*/]; + } + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("Even when keeping a reference to global Promise, still maintain PSD zone states", function () { + var Promise; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + Promise = window.Promise; + return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { + var trans = Dexie.currentTransaction; + QUnit.ok(trans !== null, "Have a transaction"); + return Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still have the same current transaction."); + return Promise.resolve().then(function () { + return Promise.resolve(); + }); + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Still have the same current transaction after multiple global.Promise.resolve() calls"); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("Sub Transactions with async await", function () { + var compatible, e_1; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3,, 4]); + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { + return false; + })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, new Function('equal', 'ok', 'Dexie', 'db', "return (async ()=>{\n await db.items.bulkAdd([{id: 1}, {id:2}, {id: 3}]);\n let result = await db.transaction('rw', db.items, async ()=>{\n let items = await db.items.toArray();\n let numItems = await db.transaction('r', db.items, async ()=>{\n equal(await db.items.count(), await db.items.count(), \"Two awaits of count should equal\");\n equal(await db.items.count(), 3, \"Should be 3 items\");\n return await db.items.count();\n });\n let numItems2 = await db.transaction('r', db.items, async ()=>{\n equal(await db.items.count(), await db.items.count(), \"Two awaits of count should equal\");\n equal(await db.items.count(), 3, \"Should be 3 items\");\n return await db.items.count();\n });\n equal (numItems, numItems2, \"The total two inner transactions should be possible to run after each other\");\n return numItems;\n });\n equal (result, 3, \"Result should be 3\");\n })();")(QUnit.equal, QUnit.ok, Dexie, db$5)]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + QUnit.ok(e_1.name === 'SyntaxError', "No support for native async functions in this browser"); + return [3 /*break*/, 4]; + case 4: + return [2 /*return*/]; + } + }); + }); + promisedTest("Should patch global Promise within transaction scopes but leave them intact outside", function () { + return __awaiter$3(_this$3, void 0, void 0, function () { + var _this = this; + var GlobalPromise; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Promise !== Dexie.Promise, "At global scope. Promise should not be Dexie.Promise"); + QUnit.ok(window.Promise !== Dexie.Promise, "At global scope. Promise should not be Dexie.Promise"); + GlobalPromise = window.Promise; + return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { + return __awaiter$3(_this, void 0, void 0, function () { + return __generator$6(this, function (_a) { + QUnit.ok(Promise === Dexie.Promise, "Within transaction scope, Promise should be Dexie.Promise."); + QUnit.ok(window.Promise === Dexie.Promise, "Within transaction scope, window.Promise should be Dexie.Promise."); + QUnit.ok(GlobalPromise !== Promise, "Promises are different"); + QUnit.ok(GlobalPromise.resolve === Promise.resolve, "If holding a reference to the real global promise and doing Promise.resolve() it should be Dexie.Promise.resolve withing transaction scopes"); + QUnit.ok(GlobalPromise.reject === Promise.reject, "If holding a reference to the real global promise and doing Promise.reject() it should be Dexie.Promise.reject withing transaction scopes"); + QUnit.ok(GlobalPromise.all === Promise.all, "If holding a reference to the real global promise and doing Promise.all() it should be Dexie.Promise.all withing transaction scopes"); + QUnit.ok(GlobalPromise.race === Promise.race, "If holding a reference to the real global promise and doing Promise.race() it should be Dexie.Promise.race withing transaction scopes"); + return [2 /*return*/]; + }); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("Should be able to use transpiled async await", function () { + return __awaiter$3(_this$3, void 0, void 0, function () { + var _this = this; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$5.transaction('rw', db$5.items, function () { + return __awaiter$3(_this, void 0, void 0, function () { + var _this = this; + var trans; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + trans = Dexie.currentTransaction; + QUnit.ok(!!trans, "Should have a current transaction"); + return [4 /*yield*/, db$5.items.add({ id: 'foo' })]; + case 1: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of Dexie.Promise"); + return [4 /*yield*/, Promise.resolve()]; + case 2: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of Promise.resolve()"); + return [4 /*yield*/, 3]; + case 3: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after await 3"); + return [4 /*yield*/, db$5.transaction('r', db$5.items, function (innerTrans) { + return __awaiter$3(_this, void 0, void 0, function () { + var x; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(!!innerTrans, "Should have inner transaction"); + QUnit.equal(Dexie.currentTransaction, innerTrans, "Inner transaction should be there"); + QUnit.equal(innerTrans.parent, trans, "Parent transaction should be correct"); + return [4 /*yield*/, db$5.items.get(1)]; + case 1: + x = _a.sent(); + QUnit.ok(Dexie.currentTransaction === innerTrans, "Transaction persisted in inner transaction"); + return [2 /*return*/]; + } + }); + }); + })]; + case 4: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of sub transaction"); + return [4 /*yield*/, function () { + return __awaiter$3(_this, void 0, void 0, function () { + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$5.items.get(1)]; + case 1: + return [2 /*return*/, _a.sent()]; + } + }); + }); + }()]; + case 5: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of async function"); + return [4 /*yield*/, function () { + return __awaiter$3(_this, void 0, void 0, function () { + var _this = this; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, Promise.all([db$5.transaction('r', db$5.items, function () { + return __awaiter$3(_this, void 0, void 0, function () { + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$5.items.get(1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$5.items.get(2)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }), db$5.transaction('r', db$5.items, function () { + return __awaiter$3(_this, void 0, void 0, function () { + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$5.items.get(1)]; + case 1: + return [2 /*return*/, _a.sent()]; + } + }); + }); + })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }()]; + case 6: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of async function 2"); + return [4 /*yield*/, Promise.resolve().then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after window.Promise.resolve().then()"); + return function () { + return __awaiter$3(_this, void 0, void 0, function () { + return __generator$6(this, function (_a) { + return [2 /*return*/]; + }); + }); + }(); // Resolve with native promise + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after native promise completion"); + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted after window.Promise.resolve().then()"); + return function () { + return __awaiter$3(_this, void 0, void 0, function () { + return __generator$6(this, function (_a) { + return [2 /*return*/]; + }); + }); + }(); + })]; + case 7: + _a.sent(); + QUnit.ok(Dexie.currentTransaction === trans, "Transaction persisted between await calls of mixed promises"); + return [2 /*return*/]; + } + }); + }); + }).catch('PrematureCommitError', function () { + QUnit.ok(true, "PROMISE IS INCOMPATIBLE WITH INDEXEDDB (https://github.com/dfahlander/Dexie.js/issues/317). Ignoring test."); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("Should be able to use some simpe native async await even without zone echoing ", function () { + return __awaiter$3(_this$3, void 0, void 0, function () { + var compatible; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + return [2 /*return*/]; + } + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { + return false; + })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, new Function('ok', 'equal', 'Dexie', 'db', "return db.transaction('r', db.items, trans=> (async (trans) => {\n ok(Dexie.currentTransaction === trans, \"Correct initial transaction.\");\n await Promise.all([1,2,3, db.items.get(2), Promise.resolve()]);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 1 - after Promise.all(1,2,3,db.items.get(2))\");\n await db.items.get(1);\n ok(Dexie.currentTransaction === trans, \"Still same transaction 2 - after await db.items.get(1);\");\n })(trans));")(QUnit.ok, QUnit.equal, Dexie, db$5)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + var GlobalPromise = window.Promise; + promisedTest("Should behave outside transactions as well", function () { + return __awaiter$3(_this$3, void 0, void 0, function () { + var compatible; + return __generator$6(this, function (_a) { + switch (_a.label) { + case 0: + if (!hasNativeAsyncFunctions) { + QUnit.ok(true, "Browser doesnt support native async-await"); + return [2 /*return*/]; + } + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { + return false; + })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, new Function('ok', 'equal', 'Dexie', 'db', 'GlobalPromise', "async function doSomething() {\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n ok(window.Promise !== Dexie.Promise, \"window.Promise should be original\");\n ok(window.Promise === GlobalPromise, \"window.Promise should be original indeed\");\n await db.items.get(1);\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n await 3;\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n await db.items.put({id:1, aj: \"aj\"});\n ok(true, \"Could put an item\");\n await db.items.update(1, {aj: \"oj\"});\n ok(true, \"Could query an item\");\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n await 4;\n ok(!Dexie.currentTransaction, \"Should be at global scope.\");\n }\n\n return doSomething();\n ")(QUnit.ok, QUnit.equal, Dexie, db$5, GlobalPromise)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + }); + + var __generator$8 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var db$6 = new Dexie("TestDBException"); + db$6.version(1).stores({ users: "id,first,last,&username,&*email,*pets" }); + db$6.on("populate", function (trans) { + db$6.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$6.users.add({ id: 2, first: "Karl", last: "Cedersköld", username: "kceder", email: ["karl@ceder.what"], pets: [] }); + }); + QUnit.module("exception-handling", { + setup: function () { + QUnit.stop(); + resetDatabase(db$6).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + QUnit.asyncTest("Uncaught promise should signal 'unhandledrejection'", function () { + // We must not use finally or catch here because then we don't test what we should. + var onErrorSignals = 0; + function onerror(ev) { + ++onErrorSignals; + ev.preventDefault(); + } + var prevUnhandledRejection = window.onunhandledrejection; + window.onunhandledrejection = onerror; + db$6.users.add({ id: 1 }); + setTimeout(function () { + QUnit.equal(onErrorSignals, 1, "unhandledrejection should have been signaled"); + window.onunhandledrejection = prevUnhandledRejection; + QUnit.start(); + }, 100); + }); + spawnedTest("transaction should abort on collection error", function () { + var _a, _b; + return __generator$8(this, function (_c) { + switch (_c.label) { + case 0: + return [4 /*yield*/, db$6.transaction("rw", db$6.users, function () { + var id; + return __generator$8(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$6.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" })]; + case 1: + id = _a.sent(); + QUnit.equal(id, 3); + return [4 /*yield*/, db$6.users.where('id').equals(null).toArray()]; + case 2: + _a.sent(); + QUnit.ok(false, "Should not come here"); + return [2 /*return*/]; + } + }); + }).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e); + })]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$6.users.where('first').equals("Foo").count()]; + case 2: + _a.apply(void 0, [_c.sent(), 0, "Should not have succeeded to add when transaction was aborted"]); + return [4 /*yield*/, db$6.transaction("rw", db$6.users, function () { + db$6.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + db$6.users.where('id').equals(null).toArray(function (res) { + QUnit.ok(false, "Not possible to query null"); + }); + }).then(function () { + QUnit.ok(false, "Transaction shouldnt commit"); + }).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw TypeError"); + })]; + case 3: + _c.sent(); + _b = QUnit.equal; + return [4 /*yield*/, db$6.users.where('first').equals("Foo").count()]; + case 4: + _b.apply(void 0, [_c.sent(), 0, "Should not have succeeded to add when transaction was aborted"]); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("eventError-transaction-catch", function () { + db$6.transaction("rw", db$6.users, function () { + db$6.users.add({ id: 100, username: "dfahlander" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since an error should have occurred"); + }).catch(function (e) { + QUnit.ok(true, "Got transaction error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("eventError-request-catch", function () { + db$6.transaction("rw", db$6.users, function () { + db$6.users.add({ id: 100, username: "dfahlander" }).then(function () { + QUnit.ok(false, "Should not be able to add two users with same username"); + }).catch(function (e) { + QUnit.ok(true, "Got request error: " + e); + }); + db$6.users.add({ id: 101, first: "Trazan", last: "Apansson", username: "tapan", email: ["trazan@apansson.barnarne"], pets: ["monkey"] }).then(function (id) { + QUnit.ok(id > 2, "Could continue transaction and add Trazan since last error event was catched"); + }); + }).then(function () { + QUnit.ok(true, "Transaction should complete since the only error that occurred was catched"); + }).catch(function (e) { + QUnit.ok(false, "Should not get transaction error since we have catched the error. Got Transaction error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("exceptionThrown-transaction-catch", function () { + db$6.transaction("r", db$6.users, function () { + throw new SyntaxError("Why not throw an exception for a change?"); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since an error should have occurred"); + }).catch(TypeError, function (e) { + QUnit.ok(false, "Should not happen. The thrown error was not a TypeError"); + }).catch(SyntaxError, function (e) { + QUnit.ok(true, "Transaction got SyntaxError: " + e); + }).catch(function (e) { + QUnit.ok(false, "Should not come here! The error should already have been catched above()"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("exceptionThrown-request-catch", function () { + db$6.transaction("r", db$6.users, function () { + db$6.users.where("username").equals("apa").toArray(function () { + db$6.users.where("username").equals("kceder").toArray().then(function () { + return "a"; + }).then(function () { + NonExistingSymbol.EnotherIdioticError = "Why not make an exception for a change?"; + }); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not complete since an error should have occurred"); + }).catch(function (e) { + QUnit.ok(true, "Transaction got error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("exceptionThrown-iteration-should-abort-when-using-hook", function () { + function deletingHook() { + // Testing with + } + + db$6.users.hook('deleting', deletingHook); + db$6.transaction('rw', db$6.users, function () { + function deleteKarls() { + db$6.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }); + } + db$6.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(false, "Transaction should not complete!"); + }).catch(function (err) { + QUnit.ok(true, "Transaction aborted"); + }).finally(function () { + db$6.users.hook('deleting').unsubscribe(deletingHook); + QUnit.start(); + }); + }); + QUnit.asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () { + db$6.users.hook('deleting', function () { + // Testing with + }); + db$6.transaction('rw', db$6.users, function () { + function deleteKarls() { + db$6.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }).catch(function (err) { + // Catching error should prevent transaction from aborting. + }); + } + db$6.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(true, "Transaction completed"); + }).catch(function (err) { + QUnit.ok(false, "Transaction should not abort!"); + }).finally(QUnit.start); + }); + /*asyncTest("promise-test", function () { + var p = new Dexie.Promise(function (resolve, reject) { + setTimeout(function () { + reject("apa error"); + }, 0); + }); + p.catch(function (err) { + return Dexie.Promise.reject(err); + }); + p.then(function(){}).catch(function (err) { + return Dexie.Promise.reject(err); + }); + p.onuncatched = function () { + debugger; + } + p.finally(start); + });*/ + QUnit.asyncTest("exception in upgrader", function () { + // Create a database: + var db = new Dexie("TestUpgrader"); + db.version(1).stores({ cars: "++id,name,brand" }); + db.open().then(function () { + // Once it opens, close it and create an upgraded version that will fail to upgrade. + db.close(); + db = new Dexie("TestUpgrader"); + db.version(1).stores({ cars: "++id,name,brand" }); + db.version(2).upgrade(function () { + db.cars.add({ name: "My car", brand: "Pegeut" }); + }); + db.version(3).upgrade(function () { + throw new Error("Oops. Failing in upgrade function"); + }); + return db.open(); + }).catch(function (err) { + // Got error + QUnit.ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err); + // Create 3rd instance of db that will only read from the existing DB. + // What we want to check here is that the DB is there but is still + // only on version 1. + db = new Dexie("TestUpgrader"); + return db.open(); + }).then(function () { + QUnit.equal(db.verno, 1, "Database is still on version 1 since it failed to upgrade to version 2."); + }).finally(function () { + db.delete().then(QUnit.start); + }); + }); + QUnit.asyncTest("exception in on('populate')", function () { + // Create a database: + var db = new Dexie("TestUpgrader"); + db.version(1).stores({ cars: "++id,name,brand" }); + db.on('populate', function () { + throw new Error("Oops. Failing in upgrade function"); + }); + db.open().catch(function (err) { + // Got error + QUnit.ok(err.toString().indexOf("Oops. Failing in upgrade function") != -1, "Got error: " + err.stack); + // Create 3rd instance of db that will only read from the existing DB. + // What we want to check here is that the DB is there but is still + // only on version 1. + db = new Dexie("TestUpgrader"); + return db.open(); + }).then(function () { + QUnit.ok(false, "The database should not have been created"); + }).catch(function (err) { + QUnit.ok(err instanceof Dexie.NoSuchDatabaseError, "The database doesnt exist"); + }).finally(function () { + db.delete().then(QUnit.start); + }); + }); + QUnit.asyncTest("Error in on('populate') should abort database creation", function () { + var popufail = new Dexie("PopufailDB"); + popufail.version(1).stores({ users: "++id,first,last,&username,&*email,*pets" }); + popufail.on('populate', function () { + popufail.users.add({ first: NaN, last: undefined, username: function () {} }).catch(function (e) { + QUnit.ok(true, "Got error when catching add() operation: " + e); + return Dexie.Promise.reject(e); + }); + }); + popufail.open().catch(function (err) { + QUnit.ok(true, "Got error (as expected):" + err); + }); + popufail.users.count(function (count) { + QUnit.ok(false, "Could query database even though an error happened in the populate event!"); + }).catch(function (err) { + QUnit.ok(true, "Got error when trying to query: " + err); + }).finally(function () { + popufail.delete(); + QUnit.start(); + }); + }); + QUnit.asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(A)", function () { + function CustomError() {} + var wasCatched = false; + new Dexie.Promise(function (resolve, reject) { + setTimeout(function () { + reject(new Error("apa")); + }, 0); + }).then(function () { + QUnit.ok(false, "Should not come here"); + }).catch(CustomError, function (e) { + QUnit.ok(false, "Should not come here"); + }).catch(function (e) { + wasCatched = true; + }).finally(function () { + QUnit.ok(wasCatched, "The error was catched in the generic catcher"); + QUnit.start(); + }); + }); + QUnit.asyncTest("Issue#73 Catching default error where specific error has already been declared in a previous catch clause(B)", function () { + function CustomError() {} + var wasCatched = false; + Dexie.Promise.resolve(null).then(function () { + throw new Error("apa"); + }).then(function () { + QUnit.ok(false, "Should not come here"); + }).catch(CustomError, function (e) { + QUnit.ok(false, "Should not come here"); + }).catch(function (e) { + wasCatched = true; + }).finally(function () { + QUnit.ok(wasCatched, "The error was catched in the generic catcher"); + QUnit.start(); + }); + }); + QUnit.asyncTest("Issue #67 - Exception can be thrown in WhereClause methods", function () { + try { + Dexie.Promise.all([ + // WhereClause.equals() + db$6.users.where('first').equals(false) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.equals() returned as a failed Promise and not an exception."); + }), + // WhereClause.above() + db$6.users.where('first').above(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.above() returned as a failed Promise and not an exception."); + }), + // WhereClause.aboveOrEqual() + db$6.users.where('first').aboveOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.aboveOrEqual() returned as a failed Promise and not an exception."); + }), + // WhereClause.below() + db$6.users.where('first').below(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.below() returned as a failed Promise and not an exception."); + }), + // WhereClause.belowOrEqual() + db$6.users.where('first').belowOrEqual(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.belowOrEqual() returned as a failed Promise and not an exception."); + }), + // WhereClause.anyOf() + db$6.users.where('first').anyOf([undefined, null, false]) // Using a non-valid key (undefined, false) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.anyOf() returned as a failed Promise and not an exception."); + }), + // WhereClause.between() + db$6.users.where('first').between(false, true) // Using a non-valid key (boolean) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.between() returned as a failed Promise and not an exception."); + }), + // WhereClause.equalsIgnoreCase() + db$6.users.where('first').equalsIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.equalsIgnoreCase() returned as a failed Promise and not an exception."); + }), + // WhereClause.startsWith() + db$6.users.where('first').startsWith(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.startsWith() returned as a failed Promise and not an exception."); + }), + // WhereClause.startsWithIgnoreCase() + db$6.users.where('first').startsWithIgnoreCase(undefined) // Using a non-valid key (undefined) must fail but as a Promise rejection, not an exception. + .toArray().catch(function (err) { + QUnit.ok(true, "Invalid key passed to WhereClause.startsWithIgnoreCase() returned as a failed Promise and not an exception."); + })]).catch(function () { + QUnit.ok(false, "No promise should finally reject because we catch them all explicitely."); + }).finally(QUnit.start); + } catch (ex) { + QUnit.ok(false, "Error was not encapsulated as a Promise failure: " + (ex.stack || ex)); + QUnit.start(); + } + }); + QUnit.asyncTest("Issue #67 - Regression test - Transaction still fails if error in key", function () { + db$6.transaction('rw', db$6.users, function () { + db$6.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$6.users.where('first').above(undefined).delete(); + }); + }).then(function () { + QUnit.ok(false, "Transaction should not commit when we an unhandled error has happened"); + }).catch(function (err) { + QUnit.ok(true, "Good, transaction failed as expected"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Issue #69 Global exception handler for promises", function () { + var errorList = []; + function globalRejectionHandler(ev) { + console.log("Got error: " + ev.reason); + if (errorList.indexOf(ev.reason) === -1) errorList.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', globalRejectionHandler); + // The most simple case: Any Promise reject that is not catched should + // be handled by the global error listener. + new Dexie.Promise(function (resolve, reject) { + reject("first error (by reject)"); + }); + // Also if the rejection was caused by a throw... + new Dexie.Promise(function () { + throw "second error (throw)"; + }); + // But when catched it should not trigger the global event: + new Dexie.Promise(function (resolve, reject) { + reject("third error (catched)"); + }).catch(function (e) { + QUnit.ok(true, "Catched error explicitely: " + e); + }); + // If catching an explicit error type that was not thrown, it should be triggered + new Dexie.Promise(function (resolve, reject) { + reject("Simple error 1"); + }).catch(TypeError, function (e) { + QUnit.ok(false, "Error should not have been TypeError"); + }); // Real error slip away... should be handled by global handler + new Dexie.Promise(function (resolve, reject) { + reject(new TypeError("Type Error 1")); + }).catch(TypeError, function (e) { + QUnit.ok(true, "Catched the TypeError"); + // Now we have handled it. Not bubble to global handler! + }); + Dexie.Promise.resolve(Promise.reject(new Error("Converting a rejected standard promise to Dexie.Promise but don't catch it"))).finally(function () { + // With finally, it should yet trigger the global event: + return new Dexie.Promise(function (resolve, reject) { + reject("forth error (uncatched but with finally)"); + }); + }).finally(function () { + // From issue #43: + // Prepare by cleaning up any unfinished previous run: + Dexie.delete("testdb").then(function () { + // Now just do some Dexie stuff... + var db = new Dexie("testdb"); + db.version(1).stores({ table1: "id" }); + db.open().then(function () { + console.log("before"); + throw new Error("FOO"); // Here a generic error is thrown (not a DB error) + //console.log("after"); + }); + db.delete().finally(function () { + QUnit.equal(errorList.length, 6, "THere should be 6 global errors triggered"); + QUnit.equal(errorList[0], "first error (by reject)", "first error (by reject)"); + QUnit.equal(errorList[1], "second error (throw)", "second error (throw)"); + QUnit.equal(errorList[2], "Simple error 1", "Simple error 1"); + QUnit.equal(errorList[3].message, "Converting a rejected standard promise to Dexie.Promise but don't catch it", "Converting a rejected standard promise to Dexie.Promise but don't catch it"); + QUnit.equal(errorList[4], "forth error (uncatched but with finally)", "forth error (uncatched but with finally)"); + QUnit.equal(errorList[5].message, "FOO", "FOO"); + errorList.slice(6).map(function (e, i) { + return "Unexpected error: " + (i + 6 + ": " + e.stack); + }).forEach(function (txt) { + console.error(txt); + QUnit.ok(false, txt); + }); + // cleanup: + window.removeEventListener('unhandledrejection', globalRejectionHandler); + QUnit.start(); + }); + }); + }); + }); + + QUnit.module("upgrading"); + var Promise$2 = Dexie.Promise; + // tests: + // * separate tests with a commented line of --- up to column 80. + // * put test result checking as a then of the relevant db.open call. + // * db.close at the top of a new section. + // another top-level then should indicate another part of the sequence + // of upgrade actions. + // put db.delete() in its own clause. + QUnit.test("upgrade", function (assert) { + var done = assert.async(); + // To test: + // V Start with empty schema + // V Add indexes + // V Remove indexes + // V Specify the changed object stores only + // V Run an upgrader function + // V Run a series of upgrader functions (done when creating DB from scratch with ALL version specs and at least two of them have upgrader functions) + // V Add object store + // V Remove object store + // V Reverse order of specifying versions + // V Delete DB and open it with ALL version specs specified (check it will run in sequence) + // V Delete DB and open it with all version specs again but in reverse order + var DBNAME = "Upgrade-test"; + var db = null; + // Instead of expecting an empty database to have 0 tables, we read + // how many an empty database has. + // Reason: Addons may add meta tables. + var baseNumberOfTables = 0; + var baseTables = []; + // Ensure Dexie verno and backing IDB version are as expected. + function checkVersion(version) { + QUnit.equal(db.verno, version, "DB should be version " + version); + QUnit.equal(db.backendDB().version, version * 10, "idb should be version " + version * 10); + } + // Ensure object store names are as expected. + function checkObjectStores(expected) { + // Add baseTables. + expected = expected.concat(baseTables).sort(); + // Already sorted. + var idbNames = [].slice.call(db.backendDB().objectStoreNames); + var dexieNames = db.tables.map(function (t) { + return t.name; + }).sort(); + QUnit.deepEqual(dexieNames, expected, "Dexie.tables must match expected."); + if (supports("deleteObjectStoreAfterRead")) { + // Special treatment for IE/Edge where Dexie avoids deleting the actual store to avoid a bug. + // This special treatment in the unit tests may not need to be here if we can work around Dexie issue #1. + QUnit.deepEqual(idbNames, expected, "IDB object stores must match expected."); + } + } + Promise$2.resolve(function () { + return Dexie.delete(DBNAME); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Empty schema + db = new Dexie(DBNAME); + db.version(1).stores({}); + return db.open().then(function () { + QUnit.ok(true, "Could create empty database without any schema"); + // Set so add-on tables don't invalidate checks. + baseNumberOfTables = db.tables.length; + baseTables = db.tables.map(function (t) { + return t.name; + }); + }); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Adding version. + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 2"); + checkVersion(2); + //equal(db.verno, 2, "DB should be version 2"); + QUnit.equal(db.table("store1").schema.primKey.name, "id", "Primary key is 'id'"); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Adding an index to a store + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + // Adding the name index + db.version(3).stores({ store1: "++id,name" }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 3 (adding an index to a store)"); + checkVersion(3); + }); + }).then(function () { + // Testing that the added index is working indeed: + return db.transaction('rw', "store1", function () { + db.store1.add({ name: "apa" }); + db.store1.where("name").equals("apa").count(function (count) { + QUnit.equal(count, 1, "Apa was found by its new index (The newly added index really works!)"); + }); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Testing: + // 1. Place latest version first (order should not matter) + // 2. Removing the 'name' index. + db = new Dexie(DBNAME); + db.version(4).stores({ store1: "++id" }); + db.version(3).stores({ store1: "++id,name" }); + db.version(2).stores({ store1: "++id" }); + db.version(1).stores({}); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 4 (removing an index)"); + checkVersion(4); + QUnit.equal(db.tables[0].schema.indexes.length, 0, "No indexes in schema now when 'name' index was removed"); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Running an upgrader function. + db = new Dexie(DBNAME); + var upgraders = 0; + // (Need not to specify earlier versions than 4 because 'I have no users out there running on version below 4'.) + db.version(4).stores({ store1: "++id" }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function (trans) { + upgraders++; + var counter = 0; + db.store1.toCollection().modify(function (obj) { + // Since we have a new primary key we must make sure it's unique on all objects + obj.email = "user" + ++counter + "@abc.com"; + }); + }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 5 where an upgrader function was applied"); + checkVersion(5); + QUnit.equal(upgraders, 1, "1 upgrade function should have run."); + }); + }).then(function () { + return db.table("store1").toArray().then(function (array) { + QUnit.equal(array.length, 1, "We still have the object created in version 3 there"); + QUnit.equal(array[0].email, "user1@abc.com", "The object got its upgrade function running"); + QUnit.equal(array[0].id, 1, "The object still has the same primary key"); + QUnit.equal(array[0].name, "apa", "The object still has the name 'apa' that was given to it when it was created"); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Changing a property of an index + db = new Dexie(DBNAME); + db.version(5).stores({ store1: "++id,&email" }); + // Changing email index from unique to multi-valued + db.version(6).stores({ store1: "++id,*email" }).upgrade(function (t) { + t.table("store1").toCollection().modify(function (obj) { + // Turning single-valued unique email into an array of + // emails. + obj.email = [obj.email]; + }); + }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 6"); + checkVersion(6); + checkObjectStores(["store1"]); + }); + }).then(function () { + return db.table('store1').get(1, function (apaUser) { + QUnit.ok(Array.isArray(apaUser.email), "email is now an array"); + QUnit.equal(apaUser.email[0], "user1@abc.com", "First email is user1@abc.com"); + }); + }).then(function () { + // Test that it is now ok to add two different users with the same email, since we have removed the uniqueness requirement of the index + return db.table('store1').add({ name: "apa2", email: ["user1@abc.com"] }); + }).then(function () { + return db.table('store1').toArray().then(function (array) { + QUnit.equal(array.length, 2, "There are now two users in db"); + QUnit.equal(array[0].email[0], array[1].email[0], "The two users share the same email value"); + }); + }).then(function (array) { + db.close(); + // -------------------------------------------------------------------- + // Test: Only changed object stores need to be specified. + db = new Dexie(DBNAME); + // No need to specify an upgrade function when we know it's not + // gonna run (we are already on ver 5) + db.version(6).stores({ store1: "++id,*email" }); + db.version(7).stores({ store2: "uuid" }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 7"); + checkVersion(7); + checkObjectStores(["store1", "store2"]); + }); + }).then(function () { + db.close(); + // -------------------------------------------------------------------- + // Test: Object store removal. + db = new Dexie(DBNAME); + // Need to keep version 6 or add its missing stores to version 7, + // 7. Choosing to keep version 6. + db.version(6).stores({ store1: "++id,*email" }); + db.version(7).stores({ store2: "uuid" }); + // Deleting a version. + db.version(8).stores({ store1: null }); + return db.open().then(function () { + QUnit.ok(true, "Could upgrade to version 8 - deleting an object store"); + checkVersion(8); + checkObjectStores(["store2"]); + }); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Use a removed object store while running an upgrade function. + /*db = new Dexie(DBNAME); + db.version(7).stores({ store2: "uuid" }); + db.version(8).stores({ store1: null }); + db.version(9).stores({ store1: "++id,email" }); + db.version(10).stores({ store1: null }).upgrade(t => { + checkTransactionObjectStores(t, ["store1"]); + // TODO: actually use the object store. + ok(true, "Upgrade transaction contains deleted store."); + }); + return db.open().then(() => { + ok(true, "Could upgrade to version 10 - deleting an object store with upgrade function"); + checkVersion(10); + checkObjectStores(["store2"]); + });*/ + }).then(function () { + // Reset. + return db.delete(); + }).then(function () { + // -------------------------------------------------------------------- + // Test: + // 1. Upgrade transactions should have the correct object + // stores available. (future version) + db = new Dexie(DBNAME); + db.version(1).stores({ + store1: "++id,name" + }); + return db.open().then(function () { + // Populate db. + return db.store1.put({ name: "A B" }); + }); + }).then(function () { + db.close(); + // Add upgrade functions. + // Track number of upgrade functions run. + var upgraders = 0; + db.version(2).stores({ + store2: "++id,firstname,lastname" + }).upgrade(function (t) { + /*checkTransactionObjectStores(t, + ["store1", "store2"]);*/ + QUnit.ok(true, "Upgrade transaction has stores deleted later."); + upgraders++; + // TODO: copy value to store2. + }); + db.version(3).stores({ + store1: null, + store3: "++id" + }).upgrade(function (t) { + /*checkTransactionObjectStores(t, + ["store1", "store2", "store3"]);*/ + upgraders++; + // TODO: Add some value to store3. + }); + return db.open().then(function () { + checkVersion(3); + QUnit.equal(upgraders, 2, "2 upgrade functions should have run."); + checkObjectStores(["store2", "store3"]); + // TODO: Check that the data is as-expected. + }); + }).then(function () { + return db.delete(); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Dexie identifies the correct table name and schema given a + // sequence of versions to go through. + db = new Dexie(DBNAME); + db.version(1).stores({}); + db.version(2).stores({ store1: "++id" }); + // Adding the name index + db.version(3).stores({ store1: "++id,name" }); + db.version(4).stores({ store1: "++id" }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function (t) { + var counter = 0; + t.table("store1").toCollection().modify(function (obj) { + // Since we have a new primary key we must make sure + // it's unique on all objects + obj.email = "user" + ++counter + "@abc.com"; + }); + }); + // Changing email index from unique to multi-valued + db.version(6).stores({ store1: "++id,*email" }).upgrade(function (t) { + t.table("store1").toCollection().modify(function (obj) { + // Turning single-valued unique email into an array of + // emails. + obj.email = [obj.email]; + }); + }); + db.version(7).stores({ store2: "uuid" }); + db.version(8).stores({ store1: null }); + return db.open().then(function () { + QUnit.ok(true, "Could create new database"); + checkVersion(8); + checkObjectStores(["store2"]); + QUnit.equal(db.table("store2").schema.primKey.name, "uuid", "The prim key is uuid"); + }); + }).then(function () { + return db.delete(); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Order of version declaration should not matter. + db = new Dexie(DBNAME); + db.version(8).stores({ store1: null }); + db.version(7).stores({ store2: "uuid" }); + db.version(6).stores({ store1: "++id,*email" }).upgrade(function () { + db.store1.toCollection().modify(function (obj) { + obj.email = [obj.email]; // Turning single-valued unique email into an array of emails. + }); + }); + db.version(5).stores({ store1: "++id,&email" }).upgrade(function () { + var counter = 0; + db.store1.toCollection().modify(function (obj) { + // Since we have a new primary key we must make sure it's unique on all objects + obj.email = "user" + ++counter + "@abc.com"; + }); + }); + db.version(4).stores({ store1: "++id" }); + db.version(3).stores({ store1: "++id,name" }); // Adding the name index + db.version(2).stores({ store1: "++id" }); + db.version(1).stores({}); + return db.open().then(function () { + QUnit.ok(true, "Could create new database"); + checkVersion(8); + checkObjectStores(["store2"]); + QUnit.equal(db.table("store2").schema.primKey.name, "uuid", "The prim key is uuid"); + }); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(function () { + if (db) db.close(); + Dexie.delete(DBNAME).then(done); + }); + }); + QUnit.test("Issue #30 - Problem with existing db", function (assert) { + var done = assert.async(); + if (!supports("compound+multiEntry")) { + QUnit.ok(true, "SKIPPED - COMPOUND + MULTIENTRY UNSUPPORTED"); + return done(); + } + /// + var db; // Will be used as a migrated version of the db. + // Start by deleting the db if it exists: + Dexie.delete("raw-db").then(function () { + // Create a bare-bone indexedDB database with custom indexes of various kinds. + return new Dexie.Promise(function (resolve, reject) { + var indexedDB = Dexie.dependencies.indexedDB; + var rawdb, req; + function error(e) { + if (rawdb) rawdb.close(); + reject(e.target.error); + } + req = indexedDB.open("raw-db", 2); + req.onupgradeneeded = function (ev) { + try { + console.log("onupgradeneeded called"); + rawdb = req.result; + // Stores + var people = rawdb.createObjectStore("people", { keyPath: "_id", autoIncrement: false }); + var messages = rawdb.createObjectStore("messages", { autoIncrement: true }); + var umbrellas = rawdb.createObjectStore("umbrellas", { keyPath: ["date", "time"] }); + // Indexes: + messages.createIndex("text_index", "text", { unique: false, multiEntry: false }); + messages.createIndex("words_index", "words", { unique: false, multiEntry: true }); + messages.createIndex("id_index", "id", { unique: true, multiEntry: false }); + umbrellas.createIndex("size_color_index", ["size", "color"], { + unique: false, + multiEntry: false + }); + // Data: + people.add({ _id: "9AF56447-66CE-470A-A70F-674A32EF2D51", name: "Kalle" }); + messages.add({ text: "Here is a text", words: ["here", "is", "a", "text"], id: 1 }); + umbrellas.add({ + date: "2014-11-20", + time: "22:18", + size: 98, + color: "pink", + name: "My Fine Umbrella!" + }); + } catch (ex) { + if (rawdb) rawdb.close(); + reject(ex); + } + }; + req.onsuccess = function () { + console.log("onsuccess called"); + rawdb = req.result; + rawdb.close(); + resolve(); + }; + req.onerror = error; + }); + }).then(function () { + // Try open the database using Dexie: + db = new Dexie("raw-db", { addons: [] }); // Explicitely don't use addons here. Syncable would fail to open an existing db. + db.version(0.2).stores({ + people: "_id", + messages: "++,text,words,id,[size+color]", + umbrellas: "[date+time],[size+color]" + }); + return db.open(); + }).then(function () { + // Verify "people" data + return db.people.toArray(function (people) { + QUnit.equal(people.length, 1, "One person in people"); + QUnit.equal(people[0].name, "Kalle", "The persons' name is Kalle"); + }); + }).then(function () { + // Verify "messages" data + return db.messages.toArray(function (messages) { + QUnit.equal(messages.length, 1, "One message in messages"); + QUnit.equal(messages[0].text, "Here is a text", "The message has the correct text"); + QUnit.equal(messages[0].words.length, 4, "The message has 4 words"); + }); + }).then(function () { + // Verify "umbrellas" data + return db.umbrellas.toArray(function (umbrellas) { + QUnit.equal(umbrellas.length, 1, "One umbrella in umbrellas"); + QUnit.equal(umbrellas[0].name, "My Fine Umbrella!", "The umbrella has the correct name"); + QUnit.equal(umbrellas[0].date, "2014-11-20", "The umbrella has the correct date"); + QUnit.equal(umbrellas[0].time, "22:18", "The umbrella has the correct time"); + QUnit.equal(umbrellas[0].size, 98, "The umbrella has the currect size"); + QUnit.equal(umbrellas[0].color, "pink", "The umbrella has the correct color"); + }); + }).then(function () { + // Test messages indexes + return db.messages.orderBy("text").first(function (message) { + QUnit.ok(!!message, "Could find a message when iterating the 'text' index"); + }); + }).then(function () { + // Test words index + return db.messages.where("words").equals("is").first(function (message) { + QUnit.ok(!!message, "Could find a message when querying the 'words' index"); + }); + }).then(function () { + // Test id index + return db.messages.where("id").equals(1).count(function (count) { + QUnit.equal(count, 1, "Could count id's"); + }); + }).then(function () { + // Test umbrella compound primary key + return db.umbrellas.get(["2014-11-20", "22:18"], function (umbrella) { + QUnit.ok(!!umbrella, "Umbrella was found by compound primary key"); + QUnit.equal(umbrella.color, "pink", "Umbrella has the correct color"); + }); + }).then(function () { + // Test umbrella compound index + return db.umbrellas.where("[size+color]").above([98, "pina"]).count(function (count) { + QUnit.equal(count, 1, "Could count umbrellas based on a query on compound index"); + }); + }).then(function () { + // Now, let's upgrade the migrated database + db.close(); + db = new Dexie("raw-db"); + // First, as required with Dexie so far, specify the existing stores: + db.version(0.2).stores({ + people: "_id", + messages: "++,text,words,id,[size+color]", + umbrellas: "[date+time],[size+color]" + }); + // Then, add the 'name' index to people: + db.version(3).stores({ + people: "_id,name" + }); + return db.open(); + }).then(function () { + // Now test the new name index: + return db.people.where("name").equalsIgnoreCase("kalle").first(); + }).then(function (kalle) { + QUnit.ok(!!kalle, "Could find at least one object by its name index"); + QUnit.equal(kalle.name, "Kalle", "The found object was Kalle indeed"); + }).catch(function (err) { + QUnit.ok(false, "Error: " + err); + }).finally(function () { + if (db) db.close(); + Dexie.delete("raw-db").then(done); + }); + }); + + var __generator$9 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var async$3 = Dexie.async; + var db$7 = new Dexie("TestIssuesDB"); + db$7.version(1).stores({ + users: "id,first,last,&username,*&email,*pets", + keyless: ",name", + foo: "id" + // If required for your test, add more tables here + }); + QUnit.module("misc", { + setup: function () { + QUnit.stop(); + resetDatabase(db$7).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + // + // Misc Tests + // + QUnit.asyncTest("Adding object with falsy keys", function () { + db$7.keyless.add({ name: "foo" }, 1).then(function (id) { + QUnit.equal(id, 1, "Normal case ok - Object with key 1 was successfully added."); + return db$7.keyless.add({ name: "bar" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could add a numeric falsy value (0)"); + return db$7.keyless.add({ name: "foobar" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could add a string falsy value ('')"); + return db$7.keyless.put({ name: "bar2" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could put a numeric falsy value (0)"); + return db$7.keyless.put({ name: "foobar2" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could put a string falsy value ('')"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("#102 Passing an empty array to anyOf throws exception", async$3(function () { + var count, err_1; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, db$7.users.where("username").anyOf([]).count()]; + case 1: + count = _a.sent(); + QUnit.equal(count, 0, "Zarro items matched the query anyOf([])"); + return [3 /*break*/, 4]; + case 2: + err_1 = _a.sent(); + QUnit.ok(false, "Error when calling anyOf([]): " + err_1); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: + return [2 /*return*/]; + } + }); + })); + spawnedTest("#248 'modifications' object in 'updating' hook can be bizarre", function () { + function CustomDate(realDate) { + this._year = new Date(realDate).getFullYear(); + this._month = new Date(realDate).getMonth(); + this._day = new Date(realDate).getDate(); + this._millisec = new Date(realDate).getTime(); + //... + } + function creatingHook(primKey, obj) { + ++numCreating; + var date = obj.date; + if (date && date instanceof CustomDate) { + obj.date = new Date(date._year, date._month, date._day); + } + } + function updatingHook(modifications, primKey, obj) { + ++numUpdating; + var date = modifications.date; + if (date && date instanceof CustomDate) { + return { date: new Date(date._year, date._month, date._day) }; + } + } + function isDate(obj) { + // obj instanceof Date does NOT work with Safari when Date are retrieved from IDB. + return obj.getTime && obj.getDate && obj.getFullYear; + } + function readingHook(obj) { + if (obj.date && isDate(obj.date)) { + obj.date = new CustomDate(obj.date); + } + return obj; + } + var numCreating, numUpdating, testDate, testDate2, retrieved; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: + numCreating = 0, numUpdating = 0; + db$7.foo.hook('creating', creatingHook); + db$7.foo.hook('reading', readingHook); + db$7.foo.hook('updating', updatingHook); + testDate = new CustomDate(new Date(2016, 5, 11)); + QUnit.equal(testDate._year, 2016, "CustomDate has year 2016"); + QUnit.equal(testDate._month, 5, "CustomDate has month 5"); + QUnit.equal(testDate._day, 11, "CustomDate has day 11"); + testDate2 = new CustomDate(new Date(2016, 5, 12)); + _a.label = 1; + case 1: + _a.trys.push([1,, 4, 5]); + db$7.foo.add({ id: 1, date: testDate }); + return [4 /*yield*/, db$7.foo.get(1)]; + case 2: + retrieved = _a.sent(); + QUnit.ok(retrieved.date instanceof CustomDate, "Got a CustomDate object when retrieving object"); + QUnit.equal(retrieved.date._day, 11, "The CustomDate is on day 11"); + db$7.foo.put({ id: 1, date: testDate2 }); + return [4 /*yield*/, db$7.foo.get(1)]; + case 3: + retrieved = _a.sent(); + QUnit.ok(retrieved.date.constructor === CustomDate, "Got a CustomDate object when retrieving object"); + QUnit.equal(retrieved.date._day, 12, "The CustomDate is now on day 12"); + // Check that hooks has been called expected number of times + QUnit.equal(numCreating, 1, "creating hook called once"); + QUnit.equal(numUpdating, 1, "updating hook called once"); + return [3 /*break*/, 5]; + case 4: + db$7.foo.hook('creating').unsubscribe(creatingHook); + db$7.foo.hook('reading').unsubscribe(readingHook); + db$7.foo.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 5: + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("Issue: Broken Promise rejection #264", 1, function () { + db$7.open().then(function () { + return db$7.users.where('id').equals('does-not-exist').first(); + }).then(function (result) { + return Promise.reject(undefined); + }).catch(function (err) { + QUnit.equal(err, undefined, "Should catch the rejection"); + }).then(function (res) { + QUnit.start(); + }).catch(function (err) { + QUnit.start(); + }); + }); + QUnit.asyncTest("#323 @gitawego's post. Should not fail unexpectedly on readonly properties", function () { + var Foo = /** @class */function () { + function Foo() {} + Object.defineProperty(Foo.prototype, "synced", { + get: function () { + return false; + }, + enumerable: true, + configurable: true + }); + return Foo; + }(); + db$7.foo.mapToClass(Foo); + db$7.transaction('rw', db$7.foo, function () { + db$7.foo.put({ id: 1 }); + db$7.foo.where('id').equals(1).modify({ + synced: true + }); + }).catch(function (e) { + QUnit.ok(false, "Could not update it: " + (e.stack || e)); + }).then(function () { + QUnit.ok(true, "Could update it"); + return db$7.foo.get(1); + }).then(function (foo) { + return db$7.foo.get(1); + }).then(function (foo) { + console.log("Wow, it could get it even though it's mapped to a class that forbids writing that property."); + }).catch(function (e) { + QUnit.ok(true, "Got error from get: " + (e.stack || e)); + }).then(function () { + return db$7.foo.toArray(); + }).then(function (array) { + console.log("Got array of length: " + array.length); + }).catch(function (e) { + QUnit.ok(true, "Got error from toArray: " + (e.stack || e)); + return db$7.foo.each(function (item) { + return console.log(item); + }); + }).then(function (array) { + console.log("Could do each"); + }).catch(function (e) { + QUnit.ok(true, "Got error from each(): " + (e.stack || e)); + return db$7.foo.toCollection().sortBy('synced'); + }).then(function (array) { + console.log("Could do sortBy"); + }).catch(function (e) { + QUnit.ok(true, "Got error from sortBy(): " + (e.stack || e)); + }).finally(QUnit.start); + }); + spawnedTest("#360 DB unresponsive after multiple Table.update() or Collection.modify()", function () { + var NUM_UPDATES, result; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: + NUM_UPDATES = 2000; + return [4 /*yield*/, db$7.transaction('rw', db$7.foo, function () { + var i; + return __generator$9(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$7.foo.put({ id: 1, value: 0 })]; + case 1: + _a.sent(); + for (i = 0; i < NUM_UPDATES; ++i) { + db$7.foo.where('id').equals(1).modify(function (item) { + return ++item.value; + }); + } + return [4 /*yield*/, db$7.foo.get(1)]; + case 2: + return [2 /*return*/, _a.sent()]; + } + }); + })]; + case 1: + result = _a.sent(); + QUnit.equal(result.value, NUM_UPDATES, "Should have updated id 1 a " + NUM_UPDATES + " times"); + return [2 /*return*/]; + } + }); + }); + + QUnit.module("promise"); + //Dexie.debug = "dexie"; + function createDirectlyResolvedPromise() { + return new Dexie.Promise(function (resolve) { + resolve(); + }); + } + QUnit.asyncTest("Promise basics", function () { + new Dexie.Promise(function (resolve) { + return resolve("value"); + }).then(function (value) { + QUnit.equal(value, "value", "Promise should be resolved with 'value'"); + }).then(function () { + QUnit.start(); + }); + }); + QUnit.asyncTest("return Promise.resolve() from Promise.then(...)", function () { + new Dexie.Promise(function (resolve) { + return resolve("value"); + }).then(function (value) { + return Dexie.Promise.resolve(value); + }).then(function (value) { + QUnit.equal(value, "value", "returning Dexie.Promise.resolve() from then handler should work"); + QUnit.start(); + }); + }); + QUnit.asyncTest("return unresolved Promise from Promise.then(...)", function () { + new Dexie.Promise(function (resolve) { + return resolve("value"); + }).then(function (value) { + return new Dexie.Promise(function (resolve) { + return setTimeout(resolve, 0, "value"); + }); + }).then(function (value) { + QUnit.equal(value, "value", "When unresolved promise is resolved, this promise should resolve with its value"); + QUnit.start(); + }); + }); + QUnit.asyncTest("Compatibility with other promises", function () { + Dexie.Promise.resolve().then(function () { + return window.Promise.resolve(3); + }).then(function (x) { + QUnit.equal(x, 3, "returning a window.Promise should be ok"); + QUnit.start(); + }); + }); + QUnit.asyncTest("When to promise resolve", function () { + var Promise = Dexie.Promise; + var res = []; + Promise.follow(function () { + new Promise(function (resolve) { + return resolve(); + }).then(function () { + return res.push("B1"); + }); + res.push("A1"); + new Promise(function (resolve) { + return resolve(); + }).then(function () { + return res.push("B2"); + }); + res.push("A2"); + }).then(function () { + QUnit.equal(JSON.stringify(res), JSON.stringify(["A1", "A2", "B1", "B2"]), "Resolves come in expected order."); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Promise.follow()", function () { + var Promise = Dexie.Promise; + Promise.follow(function () { + Promise.resolve("test").then(function (x) { + return x + ":"; + }).then(function (x) { + return Promise.reject("rejection"); + }).then(function () { + return QUnit.ok(false, "Should not come here"); + }).catch(function (e) { + return QUnit.equal(e, "rejection", "Should catch rejection"); + }); + }).then(function () { + return QUnit.ok(true, "Scope ended"); + }).catch(function (e) { + return QUnit.ok(false, "Error: " + e.stack); + }).then(QUnit.start); + }); + QUnit.asyncTest("Promise.follow() 2", function () { + var Promise = Dexie.Promise; + Promise.follow(function () { + Promise.resolve("test").then(function (x) { + return x + ":"; + }).then(function (x) { + return Promise.reject("rejection"); + }).then(function () { + return QUnit.ok(false, "Should not come here"); + }); + }).then(function () { + return QUnit.ok(false, "Scope should not resolve"); + }).catch(function (e) { + return QUnit.ok(true, "Got error: " + e.stack); + }).then(QUnit.start); + }); + QUnit.asyncTest("Promise.follow() 3 (empty)", function () { + Dexie.Promise.follow(function () {}).then(function () { + return QUnit.ok(true, "Promise resolved when nothing was done"); + }).then(QUnit.start); + }); + QUnit.asyncTest("Promise.follow chained", function () { + var Promise = Dexie.Promise; + //Promise._rootExec(()=>{ + //Promise.scheduler = (fn, args) => setTimeout(fn, 0, args[0], args[1], args[2]); + Promise.follow(function () { + new Promise(function (resolve) { + return resolve(); + }).then(function () { + return Promise.follow(function () { + Promise.PSD.inner = true; + // Chains and rejection + new Promise(function (resolve) { + return resolve(); + }).then(function (x) { + return 3; + }).then(null, function (e) { + return "catched"; + }).then(function (x) {}).then(function () { + throw new TypeError("oops"); + }); + }).then(function () { + return QUnit.ok(false, "Promise.follow() should not resolve since an unhandled rejection should have been detected"); + }); + }).then(function () { + return QUnit.ok(false, "Promise.follow() should not resolve since an unhandled rejection should have been detected"); + }).catch(TypeError, function (err) { + QUnit.ok(true, "Got TypeError: " + err.stack); + }); + }).then(function () { + return QUnit.ok(true, "Outer Promise.follow() should resolve because inner was catched"); + }).catch(function (err) { + QUnit.ok(false, "Should have catched TypeError: " + err.stack); + }).then(function () { + QUnit.start(); + }); + //}); + }); + QUnit.asyncTest("onunhandledrejection should propagate once", 1, function () { + var Promise = Dexie.Promise; + function logErr(ev) { + QUnit.ok(true, ev.reason); + return false; + } + window.addEventListener('unhandledrejection', logErr); + var p = new Promise(function (resolve, reject) { + reject("apa"); + }).finally(function () {}).finally(function () {}); + var p2 = p.finally(function () {}); + var p3 = p.then(function () {}); + var p4 = p.then(function () {}).then(function () {}); + Promise.all([p, p2, p3, p4]).finally(function () { + setTimeout(function () { + window.removeEventListener('unhandledrejection', logErr); + QUnit.start(); + }, 1); + }); + }); + QUnit.asyncTest("onunhandledrejection should not propagate if catched after finally", 1, function () { + var Promise = Dexie.Promise; + function logErr(ev) { + QUnit.ok(false, "Should already be catched:" + ev.reason); + } + window.addEventListener('unhandledrejection', logErr); + var p = new Promise(function (resolve, reject) { + reject("apa"); + }).finally(function () {}).finally(function () {}).catch(function (e) { + QUnit.ok(true, "Catching it here: " + e); + }); + var p2 = p.finally(function () {}); + var p3 = p.then(function () {}); + var p4 = p.then(function () {}).then(function () {}); + Promise.all([p, p2, p3, p4]).finally(function () { + setTimeout(function () { + window.removeEventListener('unhandledrejection', logErr); + QUnit.start(); + }, 1); + }); + }); + QUnit.asyncTest("Issue#27(A) - Then handlers are called synchronously for already resolved promises", function () { + // Test with plain Dexie.Promise() + var expectedLog = ['1', '3', '2', 'a', 'c', 'b']; + var log = []; + var promise = createDirectlyResolvedPromise(); + log.push('1'); + promise.then(function () { + log.push('2'); + log.push('a'); + promise.then(function () { + log.push('b'); + check(); + }); + log.push('c'); + check(); + }); + log.push('3'); + check(); + function check() { + if (log.length == expectedLog.length) { + for (var i = 0; i < log.length; ++i) { + QUnit.equal(log[i], expectedLog[i], "Position " + i + " is " + log[i] + " and was expected to be " + expectedLog[i]); + } + QUnit.start(); + } + } + }); + QUnit.asyncTest("Issue#27(B) - Then handlers are called synchronously for already resolved promises", function () { + // Test with a Promise returned from the Dexie library + var expectedLog = ['1', '3', '2', 'a', 'c', 'b']; + var log = []; + var db = new Dexie("Promise-test"); + db.version(1).stores({ friends: '++id' }); + db.on('populate', function () { + db.friends.add({ name: "one" }); + db.friends.add({ name: "two" }); + db.friends.add({ name: "three" }); + }); + db.delete().then(function () { + return db.open(); + }).then(function () { + var promise = db.friends.toCollection().each(function () {}); + log.push('1'); + promise.then(function () { + log.push('2'); + log.push('a'); + promise.then(function () { + log.push('b'); + check(); + }).catch(function (e) { + QUnit.ok(false, "error: " + e); + QUnit.start(); + }); + log.push('c'); + check(); + }).catch(function (e) { + QUnit.ok(false, "error: " + e); + QUnit.start(); + }); + log.push('3'); + check(); + function check() { + if (log.length == expectedLog.length) { + for (var i = 0; i < log.length; ++i) { + QUnit.equal(log[i], expectedLog[i], "Position " + i + " is " + log[i] + " and was expected to be " + expectedLog[i]); + } + db.delete().then(QUnit.start); + } + } + }); + }); + QUnit.asyncTest("Issue #97 A transaction may be lost after calling Dexie.Promise.resolve().then(...)", function () { + Dexie.Promise.newPSD(function () { + Dexie.Promise.PSD.hello = "promise land"; + Dexie.Promise.resolve().then(function () { + QUnit.ok(!!Dexie.Promise.PSD, "We should have a Dexie.Promise.PSD"); + QUnit.equal(Dexie.Promise.PSD.hello, "promise land"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + }); + /*asyncTest("setTimeout vs setImmediate", ()=>{ + var log=[]; + setImmediate(()=>{ + log.push("setImmediate"); + if (log.length == 2) end(); + }); + setTimeout(()=>{ + log.push("setTimeout"); + if (log.length == 2) end(); + }, 40); + function end() { + equal(log[0], "setImmediate", "setImmediate first"); + equal(log[1], "setTimeout", "setTimeout second"); + start(); + } + });*/ + QUnit.asyncTest("unhandledrejection", function () { + var errors = []; + function onError(ev) { + errors.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', onError); + new Dexie.Promise(function (resolve, reject) { + reject("error"); + }); + setTimeout(function () { + QUnit.equal(errors.length, 1, "Should be one error there"); + QUnit.equal(errors[0], "error", "Should be our error there"); + window.removeEventListener('unhandledrejection', onError); + QUnit.start(); + }, 40); + }); + QUnit.asyncTest("unhandledrejection2", function () { + var errors = []; + function onError(ev) { + errors.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', onError); + new Dexie.Promise(function (resolve, reject) { + new Dexie.Promise(function (resolve2, reject2) { + reject2("error"); + }).then(resolve, function (e) { + reject(e); + //return Dexie.Promise.reject(e); + }); + }); + setTimeout(function () { + QUnit.equal(errors.length, 1, "Should be one error there"); + QUnit.equal(errors[0], "error", "Should be our error there"); + window.removeEventListener('unhandledrejection', onError); + QUnit.start(); + }, 40); + }); + QUnit.asyncTest("unhandledrejection3", function () { + var errors = []; + function onError(ev) { + errors.push(ev.reason); + ev.preventDefault(); + } + window.addEventListener('unhandledrejection', onError); + new Dexie.Promise(function (resolve, reject) { + new Dexie.Promise(function (resolve2, reject2) { + reject2("error"); + }).then(resolve, function (e) { + reject(e); + //return Dexie.Promise.reject(e); + }); + }).catch(function () {}); + setTimeout(function () { + QUnit.equal(errors.length, 0, "Should be zarro errors there"); + window.removeEventListener('unhandledrejection', onError); + QUnit.start(); + }, 40); + }); + + QUnit.module("extendability"); + QUnit.asyncTest("recursive-pause", function () { + var db = new Dexie("TestDB"); + db.version(1).stores({ + activities: "Oid,Task,Tick,Tock,Type,Flags", + tasks: "Oid,Name,Parent" + }); + var Activity = db.activities.defineClass({ + Oid: String, + Task: String, + Tick: Number, + Tock: Number, + Type: Number, + Flags: Number + }); + db.on('populate', function () { + db.tasks.add({ Oid: "T1", Name: "The root task" }); + db.tasks.add({ Oid: "T2", Name: "The child task", Parent: "T1" }); + db.activities.add({ Oid: "A1", Task: "T2", Tick: 0, Tock: 10, Type: 1 }); + db.activities.add({ Oid: "A2", Task: "T2", Tick: 100, Tock: 110, Type: 1 }); + db.activities.add({ Oid: "A3", Task: "T2", Tick: 200, Tock: 210, Type: 2 }); + }); + db.delete().then(function () { + return db.open(); + }).then(function () { + return db.transaction("rw", db.activities, db.tasks, function () { + Dexie.Promise.newPSD(function () { + Dexie.currentTransaction._lock(); + db.activities.where("Type").equals(2).modify({ Flags: 2 }).finally(function () { + Dexie.currentTransaction._unlock(); + }); + }); + db.activities.where("Flags").equals(2).count(function (count) { + QUnit.equal(count, 1, "Should have put one entry there now"); + }); + db.activities.where("Flags").equals(2).each(function (act) { + QUnit.equal(act.Type, 2, "The entry is correct"); + }); + }); + }).catch(function (e) { + QUnit.ok(false, e.stack || e); + }).finally(function () { + db.delete().then(QUnit.start); + }); + }); + test("protochain", function () { + var Promise = Dexie.Promise; + var root, branch1, branch2; + Promise.newPSD(function () { + root = Promise.PSD; + root.constructor = function () {}; + root.constructor.prototype = root; + Promise.newPSD(function () { + branch1 = Promise.PSD; + branch1.constructor = function () {}; + branch1.constructor.prototype = branch1; + }); + Promise.newPSD(function () { + branch2 = Promise.PSD; + branch2.constructor = function () {}; + branch2.constructor.prototype = branch2; + }); + }); + QUnit.ok(branch1 instanceof root.constructor, "branch1 instanceof root.constructor"); + QUnit.ok(branch2 instanceof root.constructor, "branch2 instanceof root.constructor"); + QUnit.ok(!(root instanceof branch1.constructor), "!(root instanceof branch1.constructor)"); + QUnit.ok(!(root instanceof branch2.constructor), "!(root instanceof branch2.constructor)"); + QUnit.ok(!(branch1 instanceof branch2.constructor), "!(branch1 instanceof branch2.constructor)"); + QUnit.ok(!(branch2 instanceof branch1.constructor), "!(branch2 instanceof branch1.constructor)"); + }); + test("protochain2", function () { + var derive = Dexie.derive; + function Root() {} + function Branch1() {} + function Branch2() {} + derive(Branch1).from(Root); + derive(Branch2).from(Root); + var root = new Root(); + var branch1 = new Branch1(); + var branch2 = new Branch2(); + QUnit.ok(branch1 instanceof root.constructor, "branch1 instanceof root.constructor"); + QUnit.ok(branch2 instanceof root.constructor, "branch2 instanceof root.constructor"); + QUnit.ok(!(root instanceof branch1.constructor), "!(root instanceof branch1.constructor)"); + QUnit.ok(!(root instanceof branch2.constructor), "!(root instanceof branch2.constructor)"); + QUnit.ok(!(branch1 instanceof branch2.constructor), "!(branch1 instanceof branch2.constructor)"); + QUnit.ok(!(branch2 instanceof branch1.constructor), "!(branch2 instanceof branch1.constructor)"); + }); + + var __generator$10 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + /** + * Created by David on 3/31/2016. + */ + var Promise$3 = Dexie.Promise; + var all = Promise$3.all; + var async$4 = Dexie.async; + var db$8 = new Dexie("TestDBCrudHooks"); + db$8.version(1).stores({ + table1: "id,idx", + table2: ",&idx", + table3: "++id,&idx", + table4: "++,&idx", + table5: "" + }); + var ourTables = [db$8.table1, db$8.table2, db$8.table3, db$8.table4, db$8.table5]; + var opLog = []; + var successLog = []; + var errorLog = []; + var watchSuccess = false; + var watchError = false; + var deliverKeys = []; + var deliverModifications = null; + var deliverKeys2 = []; + var deliverModifications2 = null; + var opLog2 = []; + var successLog2 = []; + var errorLog2 = []; + var transLog = []; + function unsubscribeHooks() { + ourTables.forEach(function (table) { + table.hook('creating').unsubscribe(creating2); + table.hook('creating').unsubscribe(creating1); + table.hook('reading').unsubscribe(reading1); + table.hook('reading').unsubscribe(reading2); + table.hook('updating').unsubscribe(updating1); + table.hook('updating').unsubscribe(updating2); + table.hook('deleting').unsubscribe(deleting2); + table.hook('deleting').unsubscribe(deleting1); + }); + } + function subscrubeHooks() { + ourTables.forEach(function (table) { + table.hook('creating', creating1); + table.hook('creating', creating2); + table.hook('reading', reading1); + table.hook('reading', reading2); + table.hook('updating', updating1); + table.hook('updating', updating2); + table.hook('deleting', deleting1); + table.hook('deleting', deleting2); + }); + } + var reset = async$4(function reset() { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + unsubscribeHooks(); + return [4 /*yield*/, all(ourTables.map(function (table) { + return table.clear(); + }))]; + case 1: + _a.sent(); + subscrubeHooks(); + opLog = []; + successLog = []; + errorLog = []; + watchSuccess = false; + watchError = false; + deliverKeys = []; + deliverModifications = null; + deliverKeys2 = []; + deliverModifications2 = null; + opLog2 = []; + successLog2 = []; + errorLog2 = []; + transLog = []; + return [2 /*return*/]; + } + }); + }); + /*function stack() { + if (Error.captureStackTrace) { + let obj = {}; + Error.captureStackTrace(obj, stack); + return obj.stack; + } + var e = new Error(""); + if (e.stack) return e.stack; + try{throw e}catch(ex){return ex.stack || "";} + }*/ + function nop$1() {} + function creating1(primKey, obj, transaction) { + // You may do additional database operations using given transaction object. + // You may also modify given obj + // You may set this.onsuccess = function (primKey){}. Called when autoincremented key is known. + // You may set this.onerror = callback if create operation fails. + // If returning any value other than undefined, the returned value will be used as primary key + transLog.push({ trans: transaction, current: Dexie.currentTransaction }); + var op = { + op: "create", + key: primKey, + value: Dexie.deepClone(obj) + }; + opLog.push(op); + if (watchSuccess) { + this.onsuccess = function (primKey) { + return successLog.push(primKey); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog.push(e); + }; + } + if (deliverKeys[opLog.length - 1]) return deliverKeys[opLog.length - 1]; + } + // Check that chaining several hooks works + function creating2(primKey, obj, transaction) { + var op = { + op: "create", + key: primKey, + value: Dexie.deepClone(obj) + }; + opLog2.push(op); + if (watchSuccess) { + this.onsuccess = function (primKey) { + return successLog2.push(primKey); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog2.push(e); + }; + } + if (deliverKeys2[opLog2.length - 1]) return deliverKeys2[opLog2.length - 1]; + } + function reading1(obj) { + opLog.push({ + op: "read", + obj: Dexie.deepClone(obj) + }); + return { theObject: obj }; + } + function reading2(obj) { + opLog2.push({ + op: "read", + obj: Dexie.deepClone(obj) + }); + return obj.theObject; + } + function updating1(modifications, primKey, obj, transaction) { + // You may use transaction to do additional database operations. + // You may not do any modifications on any of the given arguments. + // You may set this.onsuccess = callback when update operation completes. + // You may set this.onerror = callback if update operation fails. + // If you want to make additional modifications, return another modifications object + // containing the additional or overridden modifications to make. Any returned + // object will be merged to the given modifications object. + transLog.push({ trans: transaction, current: Dexie.currentTransaction }); + var op = { + op: "update", + key: primKey, + obj: Dexie.deepClone(obj), + mods: Dexie.shallowClone(modifications) + }; + opLog.push(op); + if (watchSuccess) { + this.onsuccess = function () { + return successLog.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog.push(e); + }; + } + if (deliverModifications) return deliverModifications; + } + // Chaining: + function updating2(modifications, primKey, obj, transaction) { + // You may use transaction to do additional database operations. + // You may not do any modifications on any of the given arguments. + // You may set this.onsuccess = callback when update operation completes. + // You may set this.onerror = callback if update operation fails. + // If you want to make additional modifications, return another modifications object + // containing the additional or overridden modifications to make. Any returned + // object will be merged to the given modifications object. + var op = { + op: "update", + key: primKey, + obj: Dexie.deepClone(obj), + mods: Dexie.shallowClone(modifications) + }; + opLog2.push(op); + if (watchSuccess) { + this.onsuccess = function () { + return successLog2.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog2.push(e); + }; + } + if (deliverModifications2) return deliverModifications2; + } + function deleting1(primKey, obj, transaction) { + // You may do additional database operations using given transaction object. + // You may set this.onsuccess = callback when delete operation completes. + // You may set this.onerror = callback if delete operation fails. + // Any modification to obj is ignored. + // Any return value is ignored. + // throwing exception will make the db operation fail. + transLog.push({ trans: transaction, current: Dexie.currentTransaction }); + var op = { + op: "delete", + key: primKey, + obj: obj + }; + opLog.push(op); + if (watchSuccess) { + this.onsuccess = function () { + return successLog.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog.push(e); + }; + } + } + // Chaining: + function deleting2(primKey, obj, transaction) { + // You may do additional database operations using given transaction object. + // You may set this.onsuccess = callback when delete operation completes. + // You may set this.onerror = callback if delete operation fails. + // Any modification to obj is ignored. + // Any return value is ignored. + // throwing exception will make the db operation fail. + var op = { + op: "delete", + key: primKey, + obj: obj + }; + opLog2.push(op); + if (watchSuccess) { + this.onsuccess = function () { + return successLog2.push(undefined); + }; + } + if (watchError) { + this.onerror = function (e) { + return errorLog2.push(e); + }; + } + } + QUnit.module("crud-hooks", { + setup: function () { + QUnit.stop(); + resetDatabase(db$8).then(function () { + return reset(); + }).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + unsubscribeHooks(); + } + }); + var expect = async$4(function (expected, modifyer) { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, reset()]; + case 1: + _a.sent(); + return [4 /*yield*/, modifyer()]; + case 2: + _a.sent(); + QUnit.equal(JSON.stringify(opLog, null, 2), JSON.stringify(expected, null, 2), "Expected oplog: " + JSON.stringify(expected)); + QUnit.ok(transLog.every(function (x) { + return x.trans && x.current === x.trans; + }), "transaction argument is valid and same as Dexie.currentTransaction"); + return [4 /*yield*/, reset()]; + case 3: + _a.sent(); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 4: + _a.sent(); + QUnit.equal(errorLog.length + errorLog2.length, 0, "No errors should have been registered"); + QUnit.equal(successLog.length, expected.filter(function (op) { + return op.op !== 'read'; + }).length, "First hook got success events"); + QUnit.equal(successLog2.length, expected.filter(function (op) { + return op.op !== 'read'; + }).length, "Second hook got success events"); + expected.forEach(function (x, i) { + if (x.op === "create" && x.key !== undefined) { + QUnit.equal(successLog[i], x.key, "Success events got the correct key"); + QUnit.equal(successLog2[i], x.key, "Success events got the correct key (2)"); + } + }); + if (!expected.some(function (x) { + return x.op === "create" && x.key === undefined; + })) return [3 /*break*/, 7]; + // Test to deliver prim key from both hooks and expect the second hook's key to win. + return [4 /*yield*/, reset()]; + case 5: + // Test to deliver prim key from both hooks and expect the second hook's key to win. + _a.sent(); + deliverKeys = expected.map(function (x, i) { + return "Hook1Key" + i; + }); + deliverKeys2 = expected.map(function (x, i) { + return "Hook2Key" + i; + }); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 6: + _a.sent(); + QUnit.equal(errorLog.length + errorLog2.length, 0, "No errors should have been registered"); + expected.forEach(function (x, i) { + if (x.op === "create" && x.key === undefined) { + QUnit.equal(opLog[i].key, expected[i].key, "First hook got expected key delivered"); + QUnit.equal(opLog2[i].key, deliverKeys[i], "Second hook got key delivered from first hook"); + QUnit.equal(successLog[i], deliverKeys2[i], "Success event got delivered key from hook2"); + QUnit.equal(successLog2[i], deliverKeys2[i], "Success event got delivered key from hook2 (2)"); + } + }); + _a.label = 7; + case 7: + if (!expected.some(function (x) { + return x.op === "update"; + })) return [3 /*break*/, 10]; + return [4 /*yield*/, reset()]; + case 8: + _a.sent(); + deliverModifications = { "someProp.someSubProp": "someValue" }; + return [4 /*yield*/, modifyer()]; + case 9: + _a.sent(); + expected.forEach(function (x, i) { + if (x.op === "update") { + QUnit.equal(JSON.stringify(opLog[i].obj), JSON.stringify(opLog2[i].obj), "Object has not yet been changed in hook2"); + QUnit.ok(Object.keys(opLog[i].mods).every(function (prop) { + return JSON.stringify(opLog[i].mods[prop]) === JSON.stringify(opLog2[i].mods[prop]); + }), "All mods that were originally sent to hook1, are also sent to hook2"); + QUnit.ok("someProp.someSubProp" in opLog2[i].mods, "oplog2 got first hook's additional modifications"); + } + }); + _a.label = 10; + case 10: + return [2 /*return*/]; + } + }); + }); + var verifyErrorFlows = async$4(function (modifyer) { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, reset()]; + case 1: + _a.sent(); + QUnit.ok(true, "Verifying ERROR flows"); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 2: + _a.sent(); + QUnit.equal(opLog.length, opLog2.length, "Number of ops same for hook1 and hook2: " + opLog.length); + QUnit.equal(successLog.length + errorLog.length, opLog.length, "Either onerror or onsuccess must have been called for every op. onerror: " + errorLog.length + ". onsuccess: " + successLog.length + ". opLog: " + JSON.stringify(opLog)); + QUnit.equal(successLog2.length + errorLog2.length, opLog2.length, "Either onerror or onsuccess must have been called for every op (hook2). onerror: " + errorLog2.length + ". onsuccess: " + successLog2.length + ". opLog: " + JSON.stringify(opLog2)); + return [2 /*return*/]; + } + }); + }); + // + // + // Tests goes here... + // + // + // + // CREATING hook tests... + // + // Ways to produce CREATEs: + // Table.add() + // Table.put() + // Table.bulkAdd() + // Table.bulkPut() + spawnedTest("creating using Table.add()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 14 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + db$8.table1.add({ id: 1, idx: 11 }); + db$8.table2.add({ idx: 12 }, 2); + db$8.table3.add({ idx: 13 }); + db$8.table4.add({ idx: 14 }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$8.table1.add({ id: 1 }).catch(nop$1)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table2.add({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$8.table2.add({}, 1).catch(nop$1)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table1.add({ id: {} }).catch(nop$1)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("creating using Table.put()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 14 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + db$8.table1.put({ id: 1, idx: 11 }); + db$8.table2.put({ idx: 12 }, 2); + db$8.table3.put({ idx: 13 }); + db$8.table4.put({ idx: 14 }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table3.put({ idx: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$8.table3.put({ idx: 1 }).catch(nop$1)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table2.put({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$8.table2.put({}, 1).catch(nop$1)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$8.table3.put({ id: {} }).catch(nop$1)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("creating using Table.bulkAdd()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 1.2, + value: { id: 1.2, idx: 11.2 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + key: 2.2, + value: { idx: 12.2 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 13.2 } + }, { + op: "create", + value: { idx: 14 } + }, { + op: "create", + value: { idx: 14.2 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + db$8.table1.bulkAdd([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + db$8.table2.bulkAdd([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + db$8.table3.bulkAdd([{ idx: 13 }, { idx: 13.2 }]); + db$8.table4.bulkAdd([{ idx: 14 }, { idx: 14.2 }]); + return [2 /*return*/]; + }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.bulkAdd([{ id: 1 }, { id: 1 }]).catch(nop$1)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$8.table1.bulkAdd([{ id: 2 }, { id: 2 }, { id: 3 }]).catch(nop$1)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$8.table2.bulkAdd([{}, {}], [1, 1]).catch(nop$1)]; + case 3: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$8.table2.bulkAdd([{}, {}, {}], [2, 2, 3]).catch(nop$1)]; + case 4: + _a.sent(); // 1. success, 2. error event. 3. success. + return [4 /*yield*/, db$8.table1.bulkAdd([{ id: {} }]).catch(nop$1)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("creating using Table.bulkPut()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 1.2, + value: { id: 1.2, idx: 11.2 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + key: 2.2, + value: { idx: 12.2 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 13.2 } + }, { + op: "create", + value: { idx: 14 } + }, { + op: "create", + value: { idx: 14.2 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.bulkPut([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table2.bulkPut([{ idx: 12 }, { idx: 12.2 }], [2, 2.2])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$8.table3.bulkPut([{ idx: 13 }, { idx: 13.2 }])]; + case 3: + _a.sent(); + return [4 /*yield*/, db$8.table4.bulkPut([{ idx: 14 }, { idx: 14.2 }])]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table3.bulkPut([{ idx: 1 }, { idx: 1 }]).catch(nop$1)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$8.table3.bulkPut([{ idx: 2 }, { idx: 2 }, { idx: 3 }]).catch(nop$1)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$8.table1.bulkPut([{ id: {} }]).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + // + // READING hooks test + // Ways to produce READs: + // Table.get() + // Collection.toArray() + // Collection.each() + // Collection.first() + // Collection.last() + // But not: + // Table.filter() / Collection.and() + spawnedTest("reading tests", function () { + var readOps, readOps2; + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { foo: "bar" } + }, { + op: "create", + key: 2, + value: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }], function () { + return db$8.transaction('rw', 'table5', function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table5.bulkAdd([{ foo: "bar" }, { fee: "bore" }], [1, 2])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table5.toArray()]; + case 2: + _a.sent(); + return [4 /*yield*/, db$8.table5.reverse().each(function (x) {})]; + case 3: + _a.sent(); + return [4 /*yield*/, db$8.table5.orderBy(':id').first()]; + case 4: + _a.sent(); + return [4 /*yield*/, db$8.table5.orderBy(':id').last()]; + case 5: + _a.sent(); + return [4 /*yield*/, db$8.table5.filter(function (x) { + return false; + }).toArray()]; + case 6: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + readOps = opLog.filter(function (o) { + return o.op === 'read'; + }), readOps2 = opLog2.filter(function (o) { + return o.op === 'read'; + }); + QUnit.ok(readOps.every(function (o, i) { + return JSON.stringify(readOps2[i].obj.theObject) === JSON.stringify(o.obj); + }), "hook2 should have got hook1's return value"); + return [2 /*return*/]; + } + }); + }); + // + // UPDATING hooks test + // Ways to produce UPDATEs: + // Table.put() + // Table.bulkPut() + // Table.update() + // Collection.modify() + spawnedTest("updating using Table.put()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + db$8.table1.put({ id: 1, address: { city: 'A' } }); // create + db$8.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table3.add({ id: 1, idx: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table3.put({ id: 2, idx: 1 }).catch(nop$1)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$8.table3.put({ id: {} }).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("updating using Table.bulkPut()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + db$8.table1.put({ id: 1, address: { city: 'A' } }); // create + db$8.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table4.add({ idx: 1 }, 1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table4.bulkPut([{ idx: 1 }], [2]).catch(nop$1)]; + case 2: + _a.sent(); // error event (DataError) + return [4 /*yield*/, db$8.table3.bulkPut([{}], [{}]).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("updating using Table.update()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.update(1, { "address.city": "B" })]; + case 2: + _a.sent(); // update + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table3.update(1, { idx: 2 }).catch(nop$1)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$8.table3.update(1, 3).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception? + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("updating using Collection.modify()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.where('id').equals(1).modify({ "address.city": "B" })]; + case 2: + _a.sent(); // update + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.table3.where('id').equals(1).modify({ idx: 2 }).catch(nop$1)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$8.table3.where('id').equals(1).modify(function () { + throw "apa"; + }).catch(nop$1)]; + case 3: + _a.sent(); // Trigger direct exception + return [2 /*return*/]; + } + }); + }).catch(nop$1); + })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + // + // DELETING hook tests + // + // Ways to produce DELETEs: + // Table.delete(key) + // Table.bulkDetele(keys) + // Table.clear() + // Collection.modify() + // Collection.delete() + spawnedTest("deleting using Table.delete(key)", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.delete(1)]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Table.bulkDelete(key)", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.bulkDelete([1])]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Table.clear()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.clear()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Table.modify()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.where('id').between(0, 2).modify(function () { + delete this.value; + })]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Collection.delete()", function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, function () { + return __generator$10(this, function (_a) { + switch (_a.label) { + case 0: + return [4 /*yield*/, db$8.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$8.table1.where('id').between(0, 2).delete()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + + var __awaiter$5 = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$11 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _this$4 = undefined; + var db$9 = new Dexie("TestDBBinary"); + db$9.version(1).stores({ + items: "id" + }); + QUnit.module("blobs", { + setup: function () { + QUnit.stop(); + resetDatabase(db$9).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + function readBlob(blob) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onloadend = function (ev) { + return resolve(ev.target.result); + }; + reader.onerror = function (ev) { + return reject(ev.target.error); + }; + reader.onabort = function (ev) { + return reject(new Error("Blob Aborted")); + }; + reader.readAsArrayBuffer(blob); + }); + } + function arraysAreEqual(a1, a2) { + var length = a1.length; + if (a2.length !== length) return false; + for (var i = 0; i < length; ++i) { + if (a1[i] !== a2[i]) return false; + } + return true; + } + promisedTest("Test blobs", function () { + return __awaiter$5(_this$4, void 0, void 0, function () { + var binaryData, blob, back, arrayBuffer, resultBinaryData; + return __generator$11(this, function (_a) { + switch (_a.label) { + case 0: + binaryData = new Uint8Array([1, 2, 3, 4]); + blob = new Blob([binaryData], { type: 'application/octet-binary' }); + return [4 /*yield*/, db$9.items.add({ id: 1, blob: blob })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.items.get(1)]; + case 2: + back = _a.sent(); + return [4 /*yield*/, readBlob(back.blob)]; + case 3: + arrayBuffer = _a.sent(); + resultBinaryData = new Uint8Array(arrayBuffer); + QUnit.ok(arraysAreEqual(resultBinaryData, binaryData), "Arrays should be equal"); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest("Test blob with creating hook applied", function () { + return __awaiter$5(_this$4, void 0, void 0, function () { + function updatingHook(modifications, primKey, obj, trans) { + QUnit.ok(modifications.blob instanceof Blob, "When hook is called, the modifications should point to a Blob object"); + } + var binaryData, blob, back, arrayBuffer, resultBinaryData; + return __generator$11(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0,, 5, 6]); + db$9.items.hook('updating', updatingHook); + binaryData = new Uint8Array([1, 2, 3, 4]); + blob = new Blob([binaryData], { type: 'application/octet-binary' }); + return [4 /*yield*/, db$9.items.add({ id: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.items.put({ id: 1, blob: blob })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$9.items.get(1)]; + case 3: + back = _a.sent(); + return [4 /*yield*/, readBlob(back.blob)]; + case 4: + arrayBuffer = _a.sent(); + resultBinaryData = new Uint8Array(arrayBuffer); + QUnit.ok(arraysAreEqual(resultBinaryData, binaryData), "Arrays should be equal"); + return [3 /*break*/, 6]; + case 5: + db$9.items.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 6: + return [2 /*return*/]; + } + }); + }); + }); + + var __awaiter$6 = undefined && undefined.__awaiter || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + var __generator$12 = undefined && undefined.__generator || function (thisArg, body) { + var _ = { label: 0, sent: function () { + if (t[0] & 1) throw t[1];return t[1]; + }, trys: [], ops: [] }, + f, + y, + t, + g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [0, t.value]; + switch (op[0]) { + case 0:case 1: + t = op;break; + case 4: + _.label++;return { value: op[1], done: false }; + case 5: + _.label++;y = op[1];op = [0];continue; + case 7: + op = _.ops.pop();_.trys.pop();continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0;continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1];break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1];t = op;break; + } + if (t && _.label < t[2]) { + _.label = t[2];_.ops.push(op);break; + } + if (t[2]) _.ops.pop(); + _.trys.pop();continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e];y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1];return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + var _this$5 = undefined; + var db$10 = new Dexie("TestDBBinaryKeys"); + db$10.version(1).stores({ + items: "id,data" + }); + db$10.on('populate', function () { + db$10.items.bulkAdd([{ id: 'Uint8Array', data: new Uint8Array([1, 2, 3]) }, { id: 'ArrayBuffer', data: new Uint8Array([4, 5, 6]).buffer }]); + }); + QUnit.module("binarykeys", { + setup: function () { + QUnit.stop(); + resetDatabase(db$10).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () {} + }); + promisedTest('Binary Primary Key (Int32Array)', function () { + return __awaiter$6(_this$5, void 0, void 0, function () { + var id, back; + return __generator$12(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1,, 4, 6]); + id = new Int32Array([4, 2]); + QUnit.equal(id[0], 4, "Sanity check 1"); + QUnit.equal(id[1], 2, "Sanity check 2"); + return [4 /*yield*/, db$10.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$10.items.where({ id: new Int32Array([4, 2]) }).first()]; + case 3: + back = _a.sent(); + QUnit.equal(back.data, "string", "Should retrieve an object by its binary primary key"); + QUnit.equal(back.id[0], 4, "Should get correct value 4"); + QUnit.equal(back.id[1], 2, "Should get correcg value 2"); + return [3 /*break*/, 6]; + case 4: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + return [4 /*yield*/, db$10.items.clear()]; + case 5: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + _a.sent(); + return [7 /*endfinally*/]; + case 6: + return [2 /*return*/]; + } + }); + }); + }); + promisedTest('Binary Primary Key (Float32Array)', function () { + return __awaiter$6(_this$5, void 0, void 0, function () { + var id, back; + return __generator$12(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1,, 4, 6]); + id = new Float32Array([4.3, 2.5]); + QUnit.equal(Math.round(id[0] * 100), 4.3 * 100, "Sanity check 1"); + QUnit.equal(Math.round(id[1] * 100), 2.5 * 100, "Sanity check 2"); + return [4 /*yield*/, db$10.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$10.items // avoiding db.items.get(key) because it triggers bug in Firefox 55. + .where({ id: new Float32Array([4.3, 2.5]) }).first()]; + case 3: + back = _a.sent(); + QUnit.equal(back.data, "string", "Should retrieve an object by its binary primary key"); + QUnit.equal(Math.round(back.id[0] * 100), 4.3 * 100, "Should get correct float value 4.3"); + QUnit.equal(Math.round(back.id[1] * 100), 2.5 * 100, "Should get correcg float value 2.5"); + return [3 /*break*/, 6]; + case 4: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + return [4 /*yield*/, db$10.items.clear()]; + case 5: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + _a.sent(); + return [7 /*endfinally*/]; + case 6: + return [2 /*return*/]; + } + }); + }); + }); + promisedTest('Binary Index', function () { + return __awaiter$6(_this$5, void 0, void 0, function () { + var _a, x; + return __generator$12(this, function (_b) { + switch (_b.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a = QUnit.equal; + return [4 /*yield*/, db$10.items.where('data').equals(new Uint8Array([1, 2, 3])).count()]; + case 1: + _a.apply(void 0, [_b.sent(), 1, "Should be able to query on binary key"]); + return [4 /*yield*/, db$10.items.where('data').anyOf([new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])]).toArray()]; + case 2: + x = _b.sent(); + QUnit.equal(x.length, 2, "Should find both keys even though the second has another binary type (IndexedDB should not distinguish them)"); + return [2 /*return*/]; + } + }); + }); + }); + promisedTest('OR-query', function () { + return __awaiter$6(_this$5, void 0, void 0, function () { + var a; + return __generator$12(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1,, 4, 6]); + return [4 /*yield*/, db$10.items.bulkAdd([{ + id: new Float32Array([6.3, 10.5]), + data: "something" + }, { + id: new Uint8Array([1, 2, 3]), + data: "somethingelse" + }])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$10.items.where('data').equals("something").or('id').equals(new Uint8Array([1, 2, 3])).toArray()]; + case 3: + a = _a.sent(); + QUnit.equal(a.length, 2, "Should get two entries"); + QUnit.ok(a.some(function (x) { + return x.data === "something"; + }), "Should get 'something' in the result"); + QUnit.ok(a.some(function (x) { + return x.data === "somethingelse"; + }), "Should get 'somethingelse' in the result"); + return [3 /*break*/, 6]; + case 4: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + return [4 /*yield*/, db$10.items.clear()]; + case 5: + // Cleanup. This is only needed because of a firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1395071 + _a.sent(); + return [7 /*endfinally*/]; + case 6: + return [2 /*return*/]; + } + }); + }); + }); + + //import "./tests-performance.js"; Not required. Should make other performance tests separately instead. +}); +//# sourceMappingURL=bundle.js.map + +//# sourceMappingURL=bundle.js.map \ No newline at end of file