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..e57e6f9b1 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js @@ -0,0 +1,991 @@ +/* ========================================================================== + * 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 +// 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..0b6147f93 --- /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() {}\r\n\r\nexport function promisableChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function() {\r\n var res = f1.apply(this, arguments);\r\n if (res && typeof res.then === 'function') {\r\n var thiz = this, args = arguments;\r\n return res.then(function() {\r\n return f2.apply(thiz, args);\r\n });\r\n }\r\n return f2.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function createUUID() {\r\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\r\n var d = Date.now();\r\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\r\n var r = (d + Math.random() * 16) % 16 | 0;\r\n d = Math.floor(d / 16);\r\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\r\n });\r\n return uuid;\r\n}\r\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\r\n return function overrideCreateTransaction(origFunc) {\r\n return function (mode, storenames, dbschema, parent) {\r\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\r\n var addChanges = false;\r\n if (mode === 'readwrite' && storenames.some(function (storeName) {\r\n return dbschema[storeName] && dbschema[storeName].observable;\r\n })) {\r\n // At least one included store is a observable store. Make sure to also include the _changes store.\r\n addChanges = true;\r\n storenames = storenames.slice(0); // Clone\r\n if (storenames.indexOf(\"_changes\") === -1)\r\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\r\n }\r\n // Call original db._createTransaction()\r\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\r\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\r\n if (addChanges) {\r\n trans._lastWrittenRevision = 0;\r\n trans.on('complete', function () {\r\n if (trans._lastWrittenRevision) {\r\n // Changes were written in this transaction.\r\n if (!parent) {\r\n // This is root-level transaction, i.e. a physical commit has happened.\r\n // Delay-trigger a wakeup call:\r\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\r\n wakeupObservers.timeoutHandle = setTimeout(function () {\r\n delete wakeupObservers.timeoutHandle;\r\n wakeupObservers(trans._lastWrittenRevision);\r\n }, 25);\r\n } else {\r\n // This is just a virtual commit of a sub transaction.\r\n // Wait with waking up observers until root transaction has committed.\r\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\r\n var rootTransaction = (function findRootTransaction(trans) {\r\n return trans.parent ? findRootTransaction(trans.parent) : trans;\r\n })(parent);\r\n rootTransaction._lastWrittenRevision = Math.max(\r\n trans._lastWrittenRevision,\r\n rootTransaction.lastWrittenRevision || 0);\r\n }\r\n }\r\n });\r\n // Derive \"source\" property from parent transaction by default\r\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\r\n }\r\n return trans;\r\n };\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initWakeupObservers(db, Observable, localStorage) {\r\n return function wakeupObservers(lastWrittenRevision) {\r\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.\r\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\r\n // Set the static property lastRevision[db.name] to the revision of the last written change.\r\n Observable.latestRevision[db.name] = lastWrittenRevision;\r\n // Wakeup ourselves, and any other db instances on this window:\r\n Dexie.ignoreTransaction(function () {\r\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\r\n });\r\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\r\n // We need a storage event to wakeup other windwos.\r\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\r\n // the purpose to wakeup db instances in other windows.\r\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.\r\n }\r\n };\r\n}\r\n","// Change Types\r\nexport const CREATE = 1;\r\nexport const UPDATE = 2;\r\nexport const DELETE = 3;\r\n","import Dexie from 'dexie';\r\n\r\nimport {CREATE} from '../change_types';\r\nimport {createUUID} from '../utils';\r\n\r\nexport default function initCreatingHook(db, table) {\r\n return function creatingHook(primKey, obj, trans) {\r\n /// \r\n var rv = undefined;\r\n if (primKey === undefined && table.schema.primKey.uuid) {\r\n primKey = rv = createUUID();\r\n if (table.schema.primKey.keyPath) {\r\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\r\n }\r\n }\r\n\r\n var change = {\r\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.\r\n table: table.name,\r\n key: primKey === undefined ? null : primKey,\r\n type: CREATE,\r\n obj: obj\r\n };\r\n\r\n var promise = db._changes.add(change).then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n return rev;\r\n });\r\n\r\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\r\n this.onsuccess = function (resultKey) {\r\n if (primKey != resultKey)\r\n promise._then(function () {\r\n change.key = resultKey;\r\n db._changes.put(change);\r\n });\r\n };\r\n\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n\r\n return rv;\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport {UPDATE} from '../change_types';\r\n\r\nexport default function initUpdatingHook(db, tableName) {\r\n return function updatingHook(mods, primKey, oldObj, trans) {\r\n /// \r\n // mods may contain property paths with undefined as value if the property\r\n // is being deleted. Since we cannot persist undefined we need to act\r\n // like those changes is setting the value to null instead.\r\n var modsWithoutUndefined = {};\r\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\r\n // Therefore we may do that kind of optimization here - to not add change entries if\r\n // there's nothing to change.\r\n var anythingChanged = false;\r\n var newObj = Dexie.deepClone(oldObj);\r\n for (var propPath in mods) {\r\n var mod = mods[propPath];\r\n if (typeof mod === 'undefined') {\r\n Dexie.delByKeyPath(newObj, propPath);\r\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\r\n anythingChanged = true;\r\n } else {\r\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\r\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\r\n Dexie.setByKeyPath(newObj, propPath, mod);\r\n modsWithoutUndefined[propPath] = mod;\r\n anythingChanged = true;\r\n }\r\n }\r\n }\r\n if (anythingChanged) {\r\n var change = {\r\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.\r\n table: tableName,\r\n key: primKey,\r\n type: UPDATE,\r\n mods: modsWithoutUndefined,\r\n oldObj: oldObj,\r\n obj: newObj\r\n };\r\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\r\n this.onsuccess = function () {\r\n promise._then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n });\r\n };\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change.\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n }\r\n };\r\n}\r\n","import {DELETE} from '../change_types';\r\n\r\nexport default function initDeletingHook(db, tableName) {\r\n return function deletingHook(primKey, obj, trans) {\r\n /// \r\n var promise = db._changes.add({\r\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.\r\n table: tableName,\r\n key: primKey,\r\n type: DELETE,\r\n oldObj: obj\r\n }).then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n return rev;\r\n })\r\n .catch((e) => {\r\n console.log(obj)\r\n console.log(e.stack)\r\n })\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change.\r\n // Using _then because if promise is already fullfilled, the standard then() would\r\n // do setTimeout() and we would loose the transaction.\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n };\r\n}\r\n","import initCreatingHook from './creating';\r\nimport initUpdatingHook from './updating';\r\nimport initDeletingHook from './deleting';\r\n\r\nexport default function initCrudMonitor(db) {\r\n//\r\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\r\n//\r\n return function crudMonitor(table) {\r\n /// \r\n if (table.hook._observing) return;\r\n table.hook._observing = true;\r\n\r\n const tableName = table.name;\r\n table.hook('creating').subscribe(initCreatingHook(db, table));\r\n\r\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\r\n\r\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initOnStorage(Observable) {\r\n return function onStorage(event) {\r\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\r\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\r\n var parts = event.key.split('/');\r\n var prop = parts[1];\r\n var dbname = parts[2];\r\n if (prop === 'latestRevision') {\r\n var rev = parseInt(event.newValue, 10);\r\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\r\n Observable.latestRevision[dbname] = rev;\r\n Dexie.ignoreTransaction(function () {\r\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\r\n });\r\n }\r\n } else if (prop.indexOf(\"deadnode:\") === 0) {\r\n var nodeID = parseInt(prop.split(':')[1], 10);\r\n if (event.newValue) {\r\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\r\n }\r\n } else if (prop === 'intercomm') {\r\n if (event.newValue) {\r\n Observable.on.intercomm.fire(dbname);\r\n }\r\n }\r\n }\r\n };\r\n}\r\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\r\n return function overrideOpen(origOpen) {\r\n return function () {\r\n //\r\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\r\n //\r\n Object.keys(db._allTables).forEach(tableName => {\r\n let table = db._allTables[tableName];\r\n if (table.schema.observable) {\r\n crudMonitor(table);\r\n }\r\n if (table.name === \"_syncNodes\") {\r\n table.mapToClass(SyncNode);\r\n }\r\n });\r\n return origOpen.apply(this, arguments);\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\r\n//\r\n// Intercommunication between nodes\r\n//\r\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\r\n\r\n var requestsWaitingForReply = {};\r\n\r\n /**\r\n * @param {string} type Type of message\r\n * @param message Message to send\r\n * @param {number} destinationNode ID of destination node\r\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.\r\n */\r\n db.observable.sendMessage = function (type, message, destinationNode, options) {\r\n /// Type of message\r\n /// Message to send\r\n /// ID of destination node\r\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.\r\n options = options || {};\r\n if (!mySyncNode.node)\r\n return options.wantReply ?\r\n Promise.reject(new Dexie.DatabaseClosedError()) :\r\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\r\n\r\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\r\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\r\n return Dexie.ignoreTransaction(()=> {\r\n var tables = [\"_intercomm\"];\r\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.\r\n var promise = db.transaction('rw', tables, () => {\r\n if (options.wantReply) {\r\n // Check that there is a receiver there to take the request.\r\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\r\n if (receiverAlive)\r\n return db._intercomm.add(msg);\r\n else // If we couldn't find a node -> send to master\r\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\r\n msg.destinationNode = masterNode.id;\r\n return db._intercomm.add(msg)\r\n });\r\n });\r\n } else {\r\n // If caller doesn't need a response, we don't have to make sure that it gets one.\r\n return db._intercomm.add(msg);\r\n }\r\n }).then(messageId => {\r\n var rv = null;\r\n if (options.wantReply) {\r\n rv = new Promise(function (resolve, reject) {\r\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\r\n });\r\n }\r\n if (localStorage) {\r\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\r\n }\r\n Observable.on.intercomm.fire(db.name);\r\n return rv;\r\n });\r\n\r\n if (!options.wantReply) {\r\n promise.catch(()=> {\r\n });\r\n return;\r\n } else {\r\n // Forward rejection to caller if it waits for reply.\r\n return promise;\r\n }\r\n });\r\n };\r\n\r\n // Send a message to all local _syncNodes\r\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\r\n if (!mySyncNode.node) return;\r\n var mySyncNodeId = mySyncNode.node.id;\r\n Dexie.ignoreTransaction(()=> {\r\n db._syncNodes.toArray(nodes => {\r\n return Promise.all(nodes\r\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\r\n .map(node => db.observable.sendMessage(type, message, node.id)));\r\n }).catch(()=> {\r\n });\r\n });\r\n };\r\n\r\n function consumeIntercommMessages() {\r\n // Check if we got messages:\r\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\r\n\r\n return Dexie.ignoreTransaction(()=> {\r\n return db.transaction('rw', '_intercomm', function() {\r\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\r\n messages.forEach(msg => consumeMessage(msg));\r\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\r\n });\r\n });\r\n });\r\n }\r\n\r\n function consumeMessage(msg) {\r\n if (msg.type === 'response') {\r\n // This is a response. Lookup pending request and fulfill its promise.\r\n var request = requestsWaitingForReply[msg.requestId.toString()];\r\n if (request) {\r\n if (msg.isFailure) {\r\n request.reject(msg.message.error);\r\n } else {\r\n request.resolve(msg.message.result);\r\n }\r\n delete requestsWaitingForReply[msg.requestId.toString()];\r\n }\r\n } else {\r\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\r\n msg.resolve = function (result) {\r\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\r\n };\r\n msg.reject = function (error) {\r\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\r\n };\r\n db.on.message.fire(msg);\r\n }\r\n }\r\n\r\n // Listener for 'intercomm' events\r\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\r\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\r\n // sendMessage is used to communicate in the same tab and to trigger a storage event\r\n function onIntercomm(dbname) {\r\n // When storage event trigger us to check\r\n if (dbname === db.name) {\r\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\r\n }\r\n }\r\n\r\n return {\r\n onIntercomm,\r\n consumeIntercommMessages\r\n };\r\n}\r\n","export default function overrideParseStoresSpec(origFunc) {\r\n return function(stores, dbSchema) {\r\n // Create the _changes and _syncNodes tables\r\n stores[\"_changes\"] = \"++rev\";\r\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\r\n stores[\"_intercomm\"] = \"++id,destinationNode\";\r\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\r\n // Call default implementation. Will populate the dbSchema structures.\r\n origFunc.call(this, stores, dbSchema);\r\n // Allow UUID primary keys using $$ prefix on primary key or indexes\r\n Object.keys(dbSchema).forEach(function(tableName) {\r\n var schema = dbSchema[tableName];\r\n if (schema.primKey.name.indexOf('$$') === 0) {\r\n schema.primKey.uuid = true;\r\n schema.primKey.name = schema.primKey.name.substr(2);\r\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\r\n }\r\n });\r\n // Now mark all observable tables\r\n Object.keys(dbSchema).forEach(function(tableName) {\r\n // Marked observable tables with \"observable\" in their TableSchema.\r\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\r\n dbSchema[tableName].observable = true;\r\n }\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function deleteOldChanges(db) {\r\n // This is a background job and should never be done within\r\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\r\n // We should not return the Promise but catch it ourselves instead.\r\n\r\n // To prohibit starving the database we want to lock transactions as short as possible\r\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\r\n // continuation every 500 ms.\r\n const CHUNK_SIZE = 100;\r\n\r\n Dexie.ignoreTransaction(()=>{\r\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\r\n return db._changes\r\n .where(\"rev\").below(oldestNode.myRevision)\r\n .limit(CHUNK_SIZE)\r\n .primaryKeys();\r\n }).then(keysToDelete => {\r\n if (keysToDelete.length === 0) return; // Done.\r\n return db._changes.bulkDelete(keysToDelete).then(()=> {\r\n // If not done garbage collecting, reschedule a continuation of it until done.\r\n if (keysToDelete.length === CHUNK_SIZE) {\r\n // Limit reached. Changes are there are more job to do. Schedule again:\r\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\r\n }\r\n });\r\n });\r\n }).catch(()=>{\r\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\r\n // No need to log this.\r\n });\r\n}\r\n","/* ========================================================================== \r\n * dexie-observable.js\r\n * ==========================================================================\r\n *\r\n * Dexie addon for observing database changes not just on local db instance\r\n * but also on other instances, tabs and windows.\r\n *\r\n * Comprises a base framework for dexie-syncable.js\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com,\r\n * Nikolas Poniros, https://github.com/nponiros\r\n *\r\n * ==========================================================================\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n * \r\n */\r\nimport Dexie from 'dexie';\r\nimport { nop, promisableChain, createUUID } from './utils';\r\n\r\nimport initOverrideCreateTransaction from './override-create-transaction';\r\nimport initWakeupObservers from './wakeup-observers';\r\nimport initCrudMonitor from './hooks/crud-monitor';\r\nimport initOnStorage from './on-storage';\r\nimport initOverrideOpen from './override-open';\r\nimport initIntercomm from './intercomm';\r\n\r\nimport overrideParseStoresSpec from './override-parse-stores-spec';\r\n\r\nimport deleteOldChanges from './delete-old-changes';\r\n\r\nvar global = self;\r\n\r\n/** class DatabaseChange\r\n *\r\n * Object contained by the _changes table.\r\n */\r\nvar DatabaseChange = Dexie.defineClass({\r\n rev: Number, // Auto-incremented primary key\r\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\r\n table: String, // Table name\r\n key: Object, // Primary key. Any type.\r\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\r\n obj: Object, // CREATE: obj contains the object created.\r\n mods: Object, // UPDATE: mods contains the modifications made to the object.\r\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\r\n});\r\n\r\n// Import some usable helper functions\r\nvar override = Dexie.override;\r\nvar Promise = Dexie.Promise;\r\nvar browserIsShuttingDown = false;\r\n\r\nexport default function Observable(db) {\r\n /// \r\n /// Extension to Dexie providing Syncronization capabilities to Dexie.\r\n /// \r\n /// \r\n\r\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.\r\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\r\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \r\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)\r\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.\r\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\r\n\r\n var localStorage = Observable.localStorageImpl;\r\n\r\n /** class SyncNode\r\n *\r\n * Object contained in the _syncNodes table.\r\n */\r\n var SyncNode = Dexie.defineClass({\r\n //id: Number,\r\n myRevision: Number,\r\n type: String, // \"local\" or \"remote\"\r\n lastHeartBeat: Number,\r\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.\r\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\r\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\r\n\r\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\r\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \r\n syncContext: null,\r\n syncOptions: Object,\r\n connected: false, // FIXTHIS: Remove! Replace with status.\r\n status: Number,\r\n appliedRemoteRevision: null,\r\n remoteBaseRevisions: [{ local: Number, remote: null }],\r\n dbUploadState: {\r\n tablesToUpload: [String],\r\n currentTable: String,\r\n currentKey: null,\r\n localBaseRevision: Number\r\n }\r\n });\r\n\r\n db.observable = {};\r\n db.observable.SyncNode = SyncNode;\r\n\r\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\r\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\r\n const crudMonitor = initCrudMonitor(db);\r\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\r\n\r\n var mySyncNode = {node: null};\r\n\r\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\r\n const onIntercomm = intercomm.onIntercomm;\r\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\r\n\r\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\r\n Object.defineProperty(db, \"_localSyncNode\", {\r\n get: function() { return mySyncNode.node; }\r\n });\r\n\r\n var pollHandle = null,\r\n heartbeatHandle = null;\r\n\r\n if (Dexie.fake) {\r\n // This code will never run.\r\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\r\n db.version(1).stores({\r\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\r\n _changes: \"++rev\",\r\n _intercomm: \"++id,destinationNode\",\r\n _uncommittedChanges: \"++id,node\"\r\n });\r\n db._syncNodes.mapToClass(SyncNode);\r\n db._changes.mapToClass(DatabaseChange);\r\n mySyncNode.node = new SyncNode({\r\n myRevision: 0,\r\n type: \"local\",\r\n lastHeartBeat: Date.now(),\r\n deleteTimeStamp: null\r\n });\r\n }\r\n\r\n //\r\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\r\n // It also adds UUID support for the primary key and sets tables as observable tables.\r\n //\r\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\r\n\r\n // changes event on db:\r\n db.on.addEventType({\r\n changes: 'asap',\r\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.\r\n message: 'asap'\r\n });\r\n\r\n //\r\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\r\n //\r\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\r\n\r\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\r\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\r\n // window with the same database name has been created already, this static property will already be set correctly.\r\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\r\n\r\n //\r\n // Override open to setup hooks for db changes and map the _syncNodes table to class\r\n //\r\n db.open = override(db.open, overrideOpen);\r\n\r\n db.close = override(db.close, function(origClose) {\r\n return function () {\r\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\r\n // Teardown our framework.\r\n if (wakeupObservers.timeoutHandle) {\r\n clearTimeout(wakeupObservers.timeoutHandle);\r\n delete wakeupObservers.timeoutHandle;\r\n }\r\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\r\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\r\n Observable.on('intercomm').unsubscribe(onIntercomm);\r\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\r\n // Inform other db instances in same window that we are dying:\r\n if (mySyncNode.node && mySyncNode.node.id) {\r\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\r\n // Inform other windows as well:\r\n if (localStorage) {\r\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.\r\n }\r\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\r\n mySyncNode.node.lastHeartBeat = 0;\r\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\r\n mySyncNode.node = null;\r\n }\r\n\r\n if (pollHandle) clearTimeout(pollHandle);\r\n pollHandle = null;\r\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\r\n heartbeatHandle = null;\r\n return origClose.apply(this, arguments);\r\n };\r\n });\r\n\r\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\r\n db.delete = override(db.delete, function(origDelete) {\r\n return function() {\r\n return origDelete.apply(this, arguments).then(function(result) {\r\n // Reset Observable.latestRevision[db.name]\r\n Observable.latestRevision[db.name] = 0;\r\n return result;\r\n });\r\n };\r\n });\r\n\r\n // When db opens, make sure to start monitor any changes before other db operations will start.\r\n db.on(\"ready\", function startObserving() {\r\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\r\n \r\n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\r\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\r\n // Therefore we know that the retrieved value will be This query will\r\n var latestRevision = (lastChange ? lastChange.rev : 0);\r\n mySyncNode.node = new SyncNode({\r\n myRevision: latestRevision,\r\n type: \"local\",\r\n lastHeartBeat: Date.now(),\r\n deleteTimeStamp: null,\r\n isMaster: 0\r\n });\r\n if (Observable.latestRevision[db.name] < latestRevision) {\r\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\r\n // There are other db instances in same window that hasnt yet been informed about a new revision\r\n Observable.latestRevision[db.name] = latestRevision;\r\n Dexie.ignoreTransaction(function() {\r\n Observable.on.latestRevisionIncremented.fire(latestRevision);\r\n });\r\n }\r\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\r\n return db.transaction('rw', '_syncNodes', () => {\r\n return db._syncNodes\r\n .where('isMaster').equals(1)\r\n .first(currentMaster => {\r\n if (!currentMaster) {\r\n // There's no master. We must be the master\r\n mySyncNode.node.isMaster = 1;\r\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\r\n // Master have been inactive for too long\r\n // Take over mastership\r\n mySyncNode.node.isMaster = 1;\r\n currentMaster.isMaster = 0;\r\n return db._syncNodes.put(currentMaster);\r\n }\r\n }).then(()=>{\r\n // Add our node to DB and start subscribing to events\r\n return db._syncNodes.add(mySyncNode.node).then(function() {\r\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\r\n Observable.on('beforeunload', onBeforeUnload);\r\n Observable.on('suicideNurseCall', onSuicide);\r\n Observable.on('intercomm', onIntercomm);\r\n // Start polling for changes and do cleanups:\r\n pollHandle = setTimeout(poll, LOCAL_POLL);\r\n // Start heartbeat\r\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\r\n });\r\n });\r\n }).then(function () {\r\n cleanup();\r\n });\r\n });\r\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\r\n\r\n var handledRevision = 0;\r\n\r\n function onLatestRevisionIncremented(dbname, latestRevision) {\r\n if (dbname === db.name) {\r\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\r\n handledRevision = latestRevision;\r\n Dexie.vip(function() {\r\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\r\n // Handle database closed error gracefully while reading changes.\r\n // Don't trigger 'unhandledrejection'.\r\n // Even though we intercept the close() method, it might be called when in the middle of\r\n // reading changes and then that flow will cancel with DatabaseClosedError.\r\n });\r\n });\r\n }\r\n }\r\n\r\n function readChanges(latestRevision, recursion, wasPartial) {\r\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\r\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\r\n // should be handled in case database is totally empty we should fail if sync is not available)\r\n if (!recursion && readChanges.ongoingOperation) {\r\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\r\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().\r\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\r\n return readChanges.ongoingOperation;\r\n }\r\n\r\n var partial = false;\r\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.\r\n if (!ourSyncNode) {\r\n return Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n var LIMIT = 1000;\r\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\r\n if (changes.length > 0) {\r\n var lastChange = changes[changes.length - 1];\r\n partial = (changes.length === LIMIT);\r\n db.on('changes').fire(changes, partial);\r\n ourSyncNode.myRevision = lastChange.rev;\r\n } else if (wasPartial) {\r\n // No more changes, BUT since we have triggered on('changes') with partial = true,\r\n // we HAVE TO trigger changes again with empty list and partial = false\r\n db.on('changes').fire([], false);\r\n }\r\n\r\n let ourNodeStillExists = false;\r\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\r\n ourNodeStillExists = true;\r\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\r\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\r\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\r\n }).then(()=>ourNodeStillExists);\r\n }).then(ourNodeStillExists =>{\r\n if (!ourNodeStillExists) {\r\n // My node has been deleted. We must have been lazy and got removed by another node.\r\n if (browserIsShuttingDown) {\r\n throw new Error(\"Browser is shutting down\");\r\n } else {\r\n db.close();\r\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\r\n if (global.location) global.location.reload(true);\r\n throw new Error(\"Out of sync\"); // Will make current promise reject\r\n }\r\n }\r\n\r\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\r\n // resolve until all changes have been read.\r\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\r\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\r\n // In either case, call readChanges() again until we're done.\r\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\r\n }\r\n\r\n }).finally(function() {\r\n delete readChanges.ongoingOperation;\r\n });\r\n\r\n if (!recursion) {\r\n readChanges.ongoingOperation = promise;\r\n }\r\n return promise;\r\n }\r\n\r\n /**\r\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\r\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\r\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\r\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\r\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\r\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\r\n * \r\n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\r\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\r\n * it would believe it was dead.\r\n */\r\n function heartbeat() {\r\n heartbeatHandle = null;\r\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\r\n if (!currentInstance) return;\r\n db.transaction('rw!', db._syncNodes, ()=>{\r\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\r\n if (!ourSyncNode) {\r\n // We do not exist anymore. Call db.close() to teardown polls etc.\r\n if (db.isOpen()) db.close();\r\n return;\r\n }\r\n ourSyncNode.lastHeartBeat = Date.now();\r\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\r\n return db._syncNodes.put(ourSyncNode);\r\n });\r\n }).catch('DatabaseClosedError', () => {\r\n // Ignore silently\r\n }).finally(() => {\r\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\r\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\r\n }\r\n });\r\n }\r\n\r\n function poll() {\r\n pollHandle = null;\r\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\r\n if (!currentInstance) return;\r\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.\r\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\r\n .catch('DatabaseClosedError', ()=>{\r\n // Handle database closed error gracefully while reading changes.\r\n // Don't trigger 'unhandledrejection'.\r\n // Even though we intercept the close() method, it might be called when in the middle of\r\n // reading changes and then that flow will cancel with DatabaseClosedError.\r\n })\r\n .finally(function() {\r\n // Poll again in given interval:\r\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\r\n pollHandle = setTimeout(poll, LOCAL_POLL);\r\n }\r\n });\r\n });\r\n }\r\n\r\n \r\n function cleanup() {\r\n var ourSyncNode = mySyncNode.node;\r\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\r\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\r\n // Cleanup dead local nodes that has no heartbeat for over a minute\r\n // Dont do the following:\r\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\r\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\r\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.\r\n var weBecameMaster = false;\r\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\r\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\r\n // Delete the node.\r\n delete this.value;\r\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\r\n if (localStorage) {\r\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\r\n }\r\n // Check if we are deleting a master node\r\n if (node.isMaster) {\r\n // The node we are deleting is master. We must take over that role.\r\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\r\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\r\n weBecameMaster = true;\r\n }\r\n // Cleanup intercomm messages destinated to the node being deleted.\r\n // Those that waits for reply should be redirected to us.\r\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\r\n if (msg.wantReply)\r\n msg.destinationNode = ourSyncNode.id;\r\n else\r\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\r\n delete this.value;\r\n });\r\n } else if (!node.deleteTimeStamp) {\r\n // Mark the node for deletion\r\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\r\n }\r\n }).then(function() {\r\n // Cleanup old revisions that no node is interested of.\r\n Observable.deleteOldChanges(db);\r\n return db.on(\"cleanup\").fire(weBecameMaster);\r\n });\r\n });\r\n }\r\n\r\n function onBeforeUnload() {\r\n // Mark our own sync node for deletion.\r\n if (!mySyncNode.node) return;\r\n browserIsShuttingDown = true;\r\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\r\n mySyncNode.node.lastHeartBeat = 0;\r\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\r\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...\r\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:\r\n if (localStorage) {\r\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.\r\n }\r\n }\r\n\r\n function onSuicide(dbname, nodeID) {\r\n if (dbname === db.name && !Observable.wereTheOneDying) {\r\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.\r\n // It's own call to put() may have been cancelled.\r\n // Note also that in IE, this event may be called twice, but that doesnt harm!\r\n Dexie.vip(function() {\r\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\r\n });\r\n }\r\n }\r\n\r\n}\r\n\r\n//\r\n// Static properties and methods\r\n// \r\n\r\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\r\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\r\nObservable.createUUID = createUUID;\r\n\r\nObservable.deleteOldChanges = deleteOldChanges;\r\n\r\nObservable._onStorage = initOnStorage(Observable);\r\n\r\nObservable._onBeforeUnload = function() {\r\n Observable.on.beforeunload.fire();\r\n};\r\n\r\ntry {\r\n Observable.localStorageImpl = global.localStorage;\r\n} catch (ex){}\r\n\r\n//\r\n// Map window events to static events in Dexie.Observable:\r\n//\r\nif (global.addEventListener) {\r\n global.addEventListener(\"storage\", Observable._onStorage);\r\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\r\n}\r\n// Register addon:\r\nDexie.Observable = Observable;\r\nDexie.addons.push(Observable);\r\n"],"names":["Promise"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GAAG,gBAAgB,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..eeea36dac --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js @@ -0,0 +1,999 @@ +/* ========================================================================== + * 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, Mon Oct 02 2017 + * + * 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 +// 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, Mon Oct 02 2017 + * + * 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..3bade075a --- /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() {}\r\n\r\nexport function promisableChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function() {\r\n var res = f1.apply(this, arguments);\r\n if (res && typeof res.then === 'function') {\r\n var thiz = this, args = arguments;\r\n return res.then(function() {\r\n return f2.apply(thiz, args);\r\n });\r\n }\r\n return f2.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function createUUID() {\r\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\r\n var d = Date.now();\r\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\r\n var r = (d + Math.random() * 16) % 16 | 0;\r\n d = Math.floor(d / 16);\r\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\r\n });\r\n return uuid;\r\n}\r\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\r\n return function overrideCreateTransaction(origFunc) {\r\n return function (mode, storenames, dbschema, parent) {\r\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\r\n var addChanges = false;\r\n if (mode === 'readwrite' && storenames.some(function (storeName) {\r\n return dbschema[storeName] && dbschema[storeName].observable;\r\n })) {\r\n // At least one included store is a observable store. Make sure to also include the _changes store.\r\n addChanges = true;\r\n storenames = storenames.slice(0); // Clone\r\n if (storenames.indexOf(\"_changes\") === -1)\r\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\r\n }\r\n // Call original db._createTransaction()\r\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\r\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\r\n if (addChanges) {\r\n trans._lastWrittenRevision = 0;\r\n trans.on('complete', function () {\r\n if (trans._lastWrittenRevision) {\r\n // Changes were written in this transaction.\r\n if (!parent) {\r\n // This is root-level transaction, i.e. a physical commit has happened.\r\n // Delay-trigger a wakeup call:\r\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\r\n wakeupObservers.timeoutHandle = setTimeout(function () {\r\n delete wakeupObservers.timeoutHandle;\r\n wakeupObservers(trans._lastWrittenRevision);\r\n }, 25);\r\n } else {\r\n // This is just a virtual commit of a sub transaction.\r\n // Wait with waking up observers until root transaction has committed.\r\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\r\n var rootTransaction = (function findRootTransaction(trans) {\r\n return trans.parent ? findRootTransaction(trans.parent) : trans;\r\n })(parent);\r\n rootTransaction._lastWrittenRevision = Math.max(\r\n trans._lastWrittenRevision,\r\n rootTransaction.lastWrittenRevision || 0);\r\n }\r\n }\r\n });\r\n // Derive \"source\" property from parent transaction by default\r\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\r\n }\r\n return trans;\r\n };\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initWakeupObservers(db, Observable, localStorage) {\r\n return function wakeupObservers(lastWrittenRevision) {\r\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.\r\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\r\n // Set the static property lastRevision[db.name] to the revision of the last written change.\r\n Observable.latestRevision[db.name] = lastWrittenRevision;\r\n // Wakeup ourselves, and any other db instances on this window:\r\n Dexie.ignoreTransaction(function () {\r\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\r\n });\r\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\r\n // We need a storage event to wakeup other windwos.\r\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\r\n // the purpose to wakeup db instances in other windows.\r\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.\r\n }\r\n };\r\n}\r\n","// Change Types\r\nexport const CREATE = 1;\r\nexport const UPDATE = 2;\r\nexport const DELETE = 3;\r\n","import Dexie from 'dexie';\r\n\r\nimport {CREATE} from '../change_types';\r\nimport {createUUID} from '../utils';\r\n\r\nexport default function initCreatingHook(db, table) {\r\n return function creatingHook(primKey, obj, trans) {\r\n /// \r\n var rv = undefined;\r\n if (primKey === undefined && table.schema.primKey.uuid) {\r\n primKey = rv = createUUID();\r\n if (table.schema.primKey.keyPath) {\r\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\r\n }\r\n }\r\n\r\n var change = {\r\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.\r\n table: table.name,\r\n key: primKey === undefined ? null : primKey,\r\n type: CREATE,\r\n obj: obj\r\n };\r\n\r\n var promise = db._changes.add(change).then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n return rev;\r\n });\r\n\r\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\r\n this.onsuccess = function (resultKey) {\r\n if (primKey != resultKey)\r\n promise._then(function () {\r\n change.key = resultKey;\r\n db._changes.put(change);\r\n });\r\n };\r\n\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n\r\n return rv;\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport {UPDATE} from '../change_types';\r\n\r\nexport default function initUpdatingHook(db, tableName) {\r\n return function updatingHook(mods, primKey, oldObj, trans) {\r\n /// \r\n // mods may contain property paths with undefined as value if the property\r\n // is being deleted. Since we cannot persist undefined we need to act\r\n // like those changes is setting the value to null instead.\r\n var modsWithoutUndefined = {};\r\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\r\n // Therefore we may do that kind of optimization here - to not add change entries if\r\n // there's nothing to change.\r\n var anythingChanged = false;\r\n var newObj = Dexie.deepClone(oldObj);\r\n for (var propPath in mods) {\r\n var mod = mods[propPath];\r\n if (typeof mod === 'undefined') {\r\n Dexie.delByKeyPath(newObj, propPath);\r\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\r\n anythingChanged = true;\r\n } else {\r\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\r\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\r\n Dexie.setByKeyPath(newObj, propPath, mod);\r\n modsWithoutUndefined[propPath] = mod;\r\n anythingChanged = true;\r\n }\r\n }\r\n }\r\n if (anythingChanged) {\r\n var change = {\r\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.\r\n table: tableName,\r\n key: primKey,\r\n type: UPDATE,\r\n mods: modsWithoutUndefined,\r\n oldObj: oldObj,\r\n obj: newObj\r\n };\r\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\r\n this.onsuccess = function () {\r\n promise._then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n });\r\n };\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change.\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n }\r\n };\r\n}\r\n","import {DELETE} from '../change_types';\r\n\r\nexport default function initDeletingHook(db, tableName) {\r\n return function deletingHook(primKey, obj, trans) {\r\n /// \r\n var promise = db._changes.add({\r\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.\r\n table: tableName,\r\n key: primKey,\r\n type: DELETE,\r\n oldObj: obj\r\n }).then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n return rev;\r\n })\r\n .catch((e) => {\r\n console.log(obj)\r\n console.log(e.stack)\r\n })\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change.\r\n // Using _then because if promise is already fullfilled, the standard then() would\r\n // do setTimeout() and we would loose the transaction.\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n };\r\n}\r\n","import initCreatingHook from './creating';\r\nimport initUpdatingHook from './updating';\r\nimport initDeletingHook from './deleting';\r\n\r\nexport default function initCrudMonitor(db) {\r\n//\r\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\r\n//\r\n return function crudMonitor(table) {\r\n /// \r\n if (table.hook._observing) return;\r\n table.hook._observing = true;\r\n\r\n const tableName = table.name;\r\n table.hook('creating').subscribe(initCreatingHook(db, table));\r\n\r\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\r\n\r\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initOnStorage(Observable) {\r\n return function onStorage(event) {\r\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\r\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\r\n var parts = event.key.split('/');\r\n var prop = parts[1];\r\n var dbname = parts[2];\r\n if (prop === 'latestRevision') {\r\n var rev = parseInt(event.newValue, 10);\r\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\r\n Observable.latestRevision[dbname] = rev;\r\n Dexie.ignoreTransaction(function () {\r\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\r\n });\r\n }\r\n } else if (prop.indexOf(\"deadnode:\") === 0) {\r\n var nodeID = parseInt(prop.split(':')[1], 10);\r\n if (event.newValue) {\r\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\r\n }\r\n } else if (prop === 'intercomm') {\r\n if (event.newValue) {\r\n Observable.on.intercomm.fire(dbname);\r\n }\r\n }\r\n }\r\n };\r\n}\r\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\r\n return function overrideOpen(origOpen) {\r\n return function () {\r\n //\r\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\r\n //\r\n Object.keys(db._allTables).forEach(tableName => {\r\n let table = db._allTables[tableName];\r\n if (table.schema.observable) {\r\n crudMonitor(table);\r\n }\r\n if (table.name === \"_syncNodes\") {\r\n table.mapToClass(SyncNode);\r\n }\r\n });\r\n return origOpen.apply(this, arguments);\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\r\n//\r\n// Intercommunication between nodes\r\n//\r\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\r\n\r\n var requestsWaitingForReply = {};\r\n\r\n /**\r\n * @param {string} type Type of message\r\n * @param message Message to send\r\n * @param {number} destinationNode ID of destination node\r\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.\r\n */\r\n db.observable.sendMessage = function (type, message, destinationNode, options) {\r\n /// Type of message\r\n /// Message to send\r\n /// ID of destination node\r\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.\r\n options = options || {};\r\n if (!mySyncNode.node)\r\n return options.wantReply ?\r\n Promise.reject(new Dexie.DatabaseClosedError()) :\r\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\r\n\r\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\r\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\r\n return Dexie.ignoreTransaction(()=> {\r\n var tables = [\"_intercomm\"];\r\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.\r\n var promise = db.transaction('rw', tables, () => {\r\n if (options.wantReply) {\r\n // Check that there is a receiver there to take the request.\r\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\r\n if (receiverAlive)\r\n return db._intercomm.add(msg);\r\n else // If we couldn't find a node -> send to master\r\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\r\n msg.destinationNode = masterNode.id;\r\n return db._intercomm.add(msg)\r\n });\r\n });\r\n } else {\r\n // If caller doesn't need a response, we don't have to make sure that it gets one.\r\n return db._intercomm.add(msg);\r\n }\r\n }).then(messageId => {\r\n var rv = null;\r\n if (options.wantReply) {\r\n rv = new Promise(function (resolve, reject) {\r\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\r\n });\r\n }\r\n if (localStorage) {\r\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\r\n }\r\n Observable.on.intercomm.fire(db.name);\r\n return rv;\r\n });\r\n\r\n if (!options.wantReply) {\r\n promise.catch(()=> {\r\n });\r\n return;\r\n } else {\r\n // Forward rejection to caller if it waits for reply.\r\n return promise;\r\n }\r\n });\r\n };\r\n\r\n // Send a message to all local _syncNodes\r\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\r\n if (!mySyncNode.node) return;\r\n var mySyncNodeId = mySyncNode.node.id;\r\n Dexie.ignoreTransaction(()=> {\r\n db._syncNodes.toArray(nodes => {\r\n return Promise.all(nodes\r\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\r\n .map(node => db.observable.sendMessage(type, message, node.id)));\r\n }).catch(()=> {\r\n });\r\n });\r\n };\r\n\r\n function consumeIntercommMessages() {\r\n // Check if we got messages:\r\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\r\n\r\n return Dexie.ignoreTransaction(()=> {\r\n return db.transaction('rw', '_intercomm', function() {\r\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\r\n messages.forEach(msg => consumeMessage(msg));\r\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\r\n });\r\n });\r\n });\r\n }\r\n\r\n function consumeMessage(msg) {\r\n if (msg.type === 'response') {\r\n // This is a response. Lookup pending request and fulfill its promise.\r\n var request = requestsWaitingForReply[msg.requestId.toString()];\r\n if (request) {\r\n if (msg.isFailure) {\r\n request.reject(msg.message.error);\r\n } else {\r\n request.resolve(msg.message.result);\r\n }\r\n delete requestsWaitingForReply[msg.requestId.toString()];\r\n }\r\n } else {\r\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\r\n msg.resolve = function (result) {\r\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\r\n };\r\n msg.reject = function (error) {\r\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\r\n };\r\n db.on.message.fire(msg);\r\n }\r\n }\r\n\r\n // Listener for 'intercomm' events\r\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\r\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\r\n // sendMessage is used to communicate in the same tab and to trigger a storage event\r\n function onIntercomm(dbname) {\r\n // When storage event trigger us to check\r\n if (dbname === db.name) {\r\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\r\n }\r\n }\r\n\r\n return {\r\n onIntercomm,\r\n consumeIntercommMessages\r\n };\r\n}\r\n","export default function overrideParseStoresSpec(origFunc) {\r\n return function(stores, dbSchema) {\r\n // Create the _changes and _syncNodes tables\r\n stores[\"_changes\"] = \"++rev\";\r\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\r\n stores[\"_intercomm\"] = \"++id,destinationNode\";\r\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\r\n // Call default implementation. Will populate the dbSchema structures.\r\n origFunc.call(this, stores, dbSchema);\r\n // Allow UUID primary keys using $$ prefix on primary key or indexes\r\n Object.keys(dbSchema).forEach(function(tableName) {\r\n var schema = dbSchema[tableName];\r\n if (schema.primKey.name.indexOf('$$') === 0) {\r\n schema.primKey.uuid = true;\r\n schema.primKey.name = schema.primKey.name.substr(2);\r\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\r\n }\r\n });\r\n // Now mark all observable tables\r\n Object.keys(dbSchema).forEach(function(tableName) {\r\n // Marked observable tables with \"observable\" in their TableSchema.\r\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\r\n dbSchema[tableName].observable = true;\r\n }\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function deleteOldChanges(db) {\r\n // This is a background job and should never be done within\r\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\r\n // We should not return the Promise but catch it ourselves instead.\r\n\r\n // To prohibit starving the database we want to lock transactions as short as possible\r\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\r\n // continuation every 500 ms.\r\n const CHUNK_SIZE = 100;\r\n\r\n Dexie.ignoreTransaction(()=>{\r\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\r\n return db._changes\r\n .where(\"rev\").below(oldestNode.myRevision)\r\n .limit(CHUNK_SIZE)\r\n .primaryKeys();\r\n }).then(keysToDelete => {\r\n if (keysToDelete.length === 0) return; // Done.\r\n return db._changes.bulkDelete(keysToDelete).then(()=> {\r\n // If not done garbage collecting, reschedule a continuation of it until done.\r\n if (keysToDelete.length === CHUNK_SIZE) {\r\n // Limit reached. Changes are there are more job to do. Schedule again:\r\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\r\n }\r\n });\r\n });\r\n }).catch(()=>{\r\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\r\n // No need to log this.\r\n });\r\n}\r\n","/* ========================================================================== \r\n * dexie-observable.js\r\n * ==========================================================================\r\n *\r\n * Dexie addon for observing database changes not just on local db instance\r\n * but also on other instances, tabs and windows.\r\n *\r\n * Comprises a base framework for dexie-syncable.js\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com,\r\n * Nikolas Poniros, https://github.com/nponiros\r\n *\r\n * ==========================================================================\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n * \r\n */\r\nimport Dexie from 'dexie';\r\nimport { nop, promisableChain, createUUID } from './utils';\r\n\r\nimport initOverrideCreateTransaction from './override-create-transaction';\r\nimport initWakeupObservers from './wakeup-observers';\r\nimport initCrudMonitor from './hooks/crud-monitor';\r\nimport initOnStorage from './on-storage';\r\nimport initOverrideOpen from './override-open';\r\nimport initIntercomm from './intercomm';\r\n\r\nimport overrideParseStoresSpec from './override-parse-stores-spec';\r\n\r\nimport deleteOldChanges from './delete-old-changes';\r\n\r\nvar global = self;\r\n\r\n/** class DatabaseChange\r\n *\r\n * Object contained by the _changes table.\r\n */\r\nvar DatabaseChange = Dexie.defineClass({\r\n rev: Number, // Auto-incremented primary key\r\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\r\n table: String, // Table name\r\n key: Object, // Primary key. Any type.\r\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\r\n obj: Object, // CREATE: obj contains the object created.\r\n mods: Object, // UPDATE: mods contains the modifications made to the object.\r\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\r\n});\r\n\r\n// Import some usable helper functions\r\nvar override = Dexie.override;\r\nvar Promise = Dexie.Promise;\r\nvar browserIsShuttingDown = false;\r\n\r\nexport default function Observable(db) {\r\n /// \r\n /// Extension to Dexie providing Syncronization capabilities to Dexie.\r\n /// \r\n /// \r\n\r\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.\r\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\r\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \r\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)\r\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.\r\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\r\n\r\n var localStorage = Observable.localStorageImpl;\r\n\r\n /** class SyncNode\r\n *\r\n * Object contained in the _syncNodes table.\r\n */\r\n var SyncNode = Dexie.defineClass({\r\n //id: Number,\r\n myRevision: Number,\r\n type: String, // \"local\" or \"remote\"\r\n lastHeartBeat: Number,\r\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.\r\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\r\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\r\n\r\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\r\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \r\n syncContext: null,\r\n syncOptions: Object,\r\n connected: false, // FIXTHIS: Remove! Replace with status.\r\n status: Number,\r\n appliedRemoteRevision: null,\r\n remoteBaseRevisions: [{ local: Number, remote: null }],\r\n dbUploadState: {\r\n tablesToUpload: [String],\r\n currentTable: String,\r\n currentKey: null,\r\n localBaseRevision: Number\r\n }\r\n });\r\n\r\n db.observable = {};\r\n db.observable.SyncNode = SyncNode;\r\n\r\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\r\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\r\n const crudMonitor = initCrudMonitor(db);\r\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\r\n\r\n var mySyncNode = {node: null};\r\n\r\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\r\n const onIntercomm = intercomm.onIntercomm;\r\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\r\n\r\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\r\n Object.defineProperty(db, \"_localSyncNode\", {\r\n get: function() { return mySyncNode.node; }\r\n });\r\n\r\n var pollHandle = null,\r\n heartbeatHandle = null;\r\n\r\n if (Dexie.fake) {\r\n // This code will never run.\r\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\r\n db.version(1).stores({\r\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\r\n _changes: \"++rev\",\r\n _intercomm: \"++id,destinationNode\",\r\n _uncommittedChanges: \"++id,node\"\r\n });\r\n db._syncNodes.mapToClass(SyncNode);\r\n db._changes.mapToClass(DatabaseChange);\r\n mySyncNode.node = new SyncNode({\r\n myRevision: 0,\r\n type: \"local\",\r\n lastHeartBeat: Date.now(),\r\n deleteTimeStamp: null\r\n });\r\n }\r\n\r\n //\r\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\r\n // It also adds UUID support for the primary key and sets tables as observable tables.\r\n //\r\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\r\n\r\n // changes event on db:\r\n db.on.addEventType({\r\n changes: 'asap',\r\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.\r\n message: 'asap'\r\n });\r\n\r\n //\r\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\r\n //\r\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\r\n\r\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\r\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\r\n // window with the same database name has been created already, this static property will already be set correctly.\r\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\r\n\r\n //\r\n // Override open to setup hooks for db changes and map the _syncNodes table to class\r\n //\r\n db.open = override(db.open, overrideOpen);\r\n\r\n db.close = override(db.close, function(origClose) {\r\n return function () {\r\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\r\n // Teardown our framework.\r\n if (wakeupObservers.timeoutHandle) {\r\n clearTimeout(wakeupObservers.timeoutHandle);\r\n delete wakeupObservers.timeoutHandle;\r\n }\r\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\r\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\r\n Observable.on('intercomm').unsubscribe(onIntercomm);\r\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\r\n // Inform other db instances in same window that we are dying:\r\n if (mySyncNode.node && mySyncNode.node.id) {\r\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\r\n // Inform other windows as well:\r\n if (localStorage) {\r\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.\r\n }\r\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\r\n mySyncNode.node.lastHeartBeat = 0;\r\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\r\n mySyncNode.node = null;\r\n }\r\n\r\n if (pollHandle) clearTimeout(pollHandle);\r\n pollHandle = null;\r\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\r\n heartbeatHandle = null;\r\n return origClose.apply(this, arguments);\r\n };\r\n });\r\n\r\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\r\n db.delete = override(db.delete, function(origDelete) {\r\n return function() {\r\n return origDelete.apply(this, arguments).then(function(result) {\r\n // Reset Observable.latestRevision[db.name]\r\n Observable.latestRevision[db.name] = 0;\r\n return result;\r\n });\r\n };\r\n });\r\n\r\n // When db opens, make sure to start monitor any changes before other db operations will start.\r\n db.on(\"ready\", function startObserving() {\r\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\r\n \r\n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\r\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\r\n // Therefore we know that the retrieved value will be This query will\r\n var latestRevision = (lastChange ? lastChange.rev : 0);\r\n mySyncNode.node = new SyncNode({\r\n myRevision: latestRevision,\r\n type: \"local\",\r\n lastHeartBeat: Date.now(),\r\n deleteTimeStamp: null,\r\n isMaster: 0\r\n });\r\n if (Observable.latestRevision[db.name] < latestRevision) {\r\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\r\n // There are other db instances in same window that hasnt yet been informed about a new revision\r\n Observable.latestRevision[db.name] = latestRevision;\r\n Dexie.ignoreTransaction(function() {\r\n Observable.on.latestRevisionIncremented.fire(latestRevision);\r\n });\r\n }\r\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\r\n return db.transaction('rw', '_syncNodes', () => {\r\n return db._syncNodes\r\n .where('isMaster').equals(1)\r\n .first(currentMaster => {\r\n if (!currentMaster) {\r\n // There's no master. We must be the master\r\n mySyncNode.node.isMaster = 1;\r\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\r\n // Master have been inactive for too long\r\n // Take over mastership\r\n mySyncNode.node.isMaster = 1;\r\n currentMaster.isMaster = 0;\r\n return db._syncNodes.put(currentMaster);\r\n }\r\n }).then(()=>{\r\n // Add our node to DB and start subscribing to events\r\n return db._syncNodes.add(mySyncNode.node).then(function() {\r\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\r\n Observable.on('beforeunload', onBeforeUnload);\r\n Observable.on('suicideNurseCall', onSuicide);\r\n Observable.on('intercomm', onIntercomm);\r\n // Start polling for changes and do cleanups:\r\n pollHandle = setTimeout(poll, LOCAL_POLL);\r\n // Start heartbeat\r\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\r\n });\r\n });\r\n }).then(function () {\r\n cleanup();\r\n });\r\n });\r\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\r\n\r\n var handledRevision = 0;\r\n\r\n function onLatestRevisionIncremented(dbname, latestRevision) {\r\n if (dbname === db.name) {\r\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\r\n handledRevision = latestRevision;\r\n Dexie.vip(function() {\r\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\r\n // Handle database closed error gracefully while reading changes.\r\n // Don't trigger 'unhandledrejection'.\r\n // Even though we intercept the close() method, it might be called when in the middle of\r\n // reading changes and then that flow will cancel with DatabaseClosedError.\r\n });\r\n });\r\n }\r\n }\r\n\r\n function readChanges(latestRevision, recursion, wasPartial) {\r\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\r\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\r\n // should be handled in case database is totally empty we should fail if sync is not available)\r\n if (!recursion && readChanges.ongoingOperation) {\r\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\r\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().\r\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\r\n return readChanges.ongoingOperation;\r\n }\r\n\r\n var partial = false;\r\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.\r\n if (!ourSyncNode) {\r\n return Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n var LIMIT = 1000;\r\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\r\n if (changes.length > 0) {\r\n var lastChange = changes[changes.length - 1];\r\n partial = (changes.length === LIMIT);\r\n db.on('changes').fire(changes, partial);\r\n ourSyncNode.myRevision = lastChange.rev;\r\n } else if (wasPartial) {\r\n // No more changes, BUT since we have triggered on('changes') with partial = true,\r\n // we HAVE TO trigger changes again with empty list and partial = false\r\n db.on('changes').fire([], false);\r\n }\r\n\r\n let ourNodeStillExists = false;\r\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\r\n ourNodeStillExists = true;\r\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\r\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\r\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\r\n }).then(()=>ourNodeStillExists);\r\n }).then(ourNodeStillExists =>{\r\n if (!ourNodeStillExists) {\r\n // My node has been deleted. We must have been lazy and got removed by another node.\r\n if (browserIsShuttingDown) {\r\n throw new Error(\"Browser is shutting down\");\r\n } else {\r\n db.close();\r\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\r\n if (global.location) global.location.reload(true);\r\n throw new Error(\"Out of sync\"); // Will make current promise reject\r\n }\r\n }\r\n\r\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\r\n // resolve until all changes have been read.\r\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\r\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\r\n // In either case, call readChanges() again until we're done.\r\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\r\n }\r\n\r\n }).finally(function() {\r\n delete readChanges.ongoingOperation;\r\n });\r\n\r\n if (!recursion) {\r\n readChanges.ongoingOperation = promise;\r\n }\r\n return promise;\r\n }\r\n\r\n /**\r\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\r\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\r\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\r\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\r\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\r\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\r\n * \r\n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\r\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\r\n * it would believe it was dead.\r\n */\r\n function heartbeat() {\r\n heartbeatHandle = null;\r\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\r\n if (!currentInstance) return;\r\n db.transaction('rw!', db._syncNodes, ()=>{\r\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\r\n if (!ourSyncNode) {\r\n // We do not exist anymore. Call db.close() to teardown polls etc.\r\n if (db.isOpen()) db.close();\r\n return;\r\n }\r\n ourSyncNode.lastHeartBeat = Date.now();\r\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\r\n return db._syncNodes.put(ourSyncNode);\r\n });\r\n }).catch('DatabaseClosedError', () => {\r\n // Ignore silently\r\n }).finally(() => {\r\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\r\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\r\n }\r\n });\r\n }\r\n\r\n function poll() {\r\n pollHandle = null;\r\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\r\n if (!currentInstance) return;\r\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.\r\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\r\n .catch('DatabaseClosedError', ()=>{\r\n // Handle database closed error gracefully while reading changes.\r\n // Don't trigger 'unhandledrejection'.\r\n // Even though we intercept the close() method, it might be called when in the middle of\r\n // reading changes and then that flow will cancel with DatabaseClosedError.\r\n })\r\n .finally(function() {\r\n // Poll again in given interval:\r\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\r\n pollHandle = setTimeout(poll, LOCAL_POLL);\r\n }\r\n });\r\n });\r\n }\r\n\r\n \r\n function cleanup() {\r\n var ourSyncNode = mySyncNode.node;\r\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\r\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\r\n // Cleanup dead local nodes that has no heartbeat for over a minute\r\n // Dont do the following:\r\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\r\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\r\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.\r\n var weBecameMaster = false;\r\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\r\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\r\n // Delete the node.\r\n delete this.value;\r\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\r\n if (localStorage) {\r\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\r\n }\r\n // Check if we are deleting a master node\r\n if (node.isMaster) {\r\n // The node we are deleting is master. We must take over that role.\r\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\r\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\r\n weBecameMaster = true;\r\n }\r\n // Cleanup intercomm messages destinated to the node being deleted.\r\n // Those that waits for reply should be redirected to us.\r\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\r\n if (msg.wantReply)\r\n msg.destinationNode = ourSyncNode.id;\r\n else\r\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\r\n delete this.value;\r\n });\r\n } else if (!node.deleteTimeStamp) {\r\n // Mark the node for deletion\r\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\r\n }\r\n }).then(function() {\r\n // Cleanup old revisions that no node is interested of.\r\n Observable.deleteOldChanges(db);\r\n return db.on(\"cleanup\").fire(weBecameMaster);\r\n });\r\n });\r\n }\r\n\r\n function onBeforeUnload() {\r\n // Mark our own sync node for deletion.\r\n if (!mySyncNode.node) return;\r\n browserIsShuttingDown = true;\r\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\r\n mySyncNode.node.lastHeartBeat = 0;\r\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\r\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...\r\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:\r\n if (localStorage) {\r\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.\r\n }\r\n }\r\n\r\n function onSuicide(dbname, nodeID) {\r\n if (dbname === db.name && !Observable.wereTheOneDying) {\r\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.\r\n // It's own call to put() may have been cancelled.\r\n // Note also that in IE, this event may be called twice, but that doesnt harm!\r\n Dexie.vip(function() {\r\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\r\n });\r\n }\r\n }\r\n\r\n}\r\n\r\n//\r\n// Static properties and methods\r\n// \r\n\r\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\r\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\r\nObservable.createUUID = createUUID;\r\n\r\nObservable.deleteOldChanges = deleteOldChanges;\r\n\r\nObservable._onStorage = initOnStorage(Observable);\r\n\r\nObservable._onBeforeUnload = function() {\r\n Observable.on.beforeunload.fire();\r\n};\r\n\r\ntry {\r\n Observable.localStorageImpl = global.localStorage;\r\n} catch (ex){}\r\n\r\n//\r\n// Map window events to static events in Dexie.Observable:\r\n//\r\nif (global.addEventListener) {\r\n global.addEventListener(\"storage\", Observable._onStorage);\r\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\r\n}\r\n// Register addon:\r\nDexie.Observable = Observable;\r\nDexie.addons.push(Observable);\r\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,OAA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/dist/dexie-observable.min.js new file mode 100644 index 000000000..e9304bf2e --- /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(),n="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)});return n}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 u=t.call(this,o,i,r,a);return s&&(u._lastWrittenRevision=0,u.on("complete",function(){if(u._lastWrittenRevision)if(a){var e=function t(e){return e.parent?t(e.parent):e}(a);e._lastWrittenRevision=Math.max(u._lastWrittenRevision,e.lastWrittenRevision||0)}else n.timeoutHandle&&clearTimeout(n.timeoutHandle),n.timeoutHandle=setTimeout(function(){delete n.timeoutHandle,n(u._lastWrittenRevision)},25)}),u.parent&&u.parent.source&&(u.source=u.parent.source)),u}}}function r(n,t,o){return function(i){t.latestRevision[n.name]n.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)}}}function d(e,n,t){return function(o){return function(){return Object.keys(e._allTables).forEach(function(o){var i=e._allTables[o];i.schema.observable&&t(i),"_syncNodes"===i.name&&i.mapToClass(n)}),o.apply(this,arguments)}}}function f(n,t,o,i,r){function a(){return i.node?e.ignoreTransaction(function(){return n.transaction("rw","_intercomm",function(){return n._intercomm.where({destinationNode:i.node.id}).toArray(function(e){return e.forEach(function(e){return s(e)}),n._intercomm.where("id").anyOf(e.map(function(e){return e.id}))["delete"]()})})}):g.reject(new e.DatabaseClosedError)}function s(e){if("response"===e.type){var t=c[e.requestId.toString()];t&&(e.isFailure?t.reject(e.message.error):t.resolve(e.message.result),delete c[e.requestId.toString()])}else e.resolve=function(t){n.observable.sendMessage("response",{result:t},e.sender,{requestId:e.id})},e.reject=function(t){n.observable.sendMessage("response",{error:t.toString()},e.sender,{isFailure:!0,requestId:e.id})},n.on.message.fire(e)}function u(e){e===n.name&&a()["catch"]("DatabaseClosedError",function(){})}var c={};return n.observable.sendMessage=function(o,a,s,u){if(u=u||{},!i.node)return u.wantReply?g.reject(new e.DatabaseClosedError):g.resolve();var l={message:a,destinationNode:s,sender:i.node.id,type:o};return e.extend(l,u),e.ignoreTransaction(function(){var e=["_intercomm"];u.wantReply&&e.push("_syncNodes");var o=n.transaction("rw",e,function(){return u.wantReply?n._syncNodes.where("id").equals(s).count(function(e){return e?n._intercomm.add(l):n._syncNodes.where("isMaster").above(0).first(function(e){return l.destinationNode=e.id,n._intercomm.add(l)})}):n._intercomm.add(l)}).then(function(e){var o=null;return u.wantReply&&(o=new g(function(n,t){c[e.toString()]={resolve:n,reject:t}})),r&&r.setItem("Dexie.Observable/intercomm/"+n.name,e.toString()),t.on.intercomm.fire(n.name),o});return u.wantReply?o:void o["catch"](function(){})})},n.observable.broadcastMessage=function(t,o,r){if(i.node){var a=i.node.id;e.ignoreTransaction(function(){n._syncNodes.toArray(function(e){return g.all(e.filter(function(e){return"local"===e.type&&(r||e.id!==a)}).map(function(e){return n.observable.sendMessage(t,o,e.id)}))})["catch"](function(){})})}},{onIntercomm:u,consumeIntercommMessages:a}}function m(e){return function(n,t){n._changes="++rev",n._syncNodes="++id,myRevision,lastHeartBeat,&url,isMaster,type,status",n._intercomm="++id,destinationNode",n._uncommittedChanges="++id,node",e.call(this,n,t),Object.keys(t).forEach(function(e){var n=t[e];0===n.primKey.name.indexOf("$$")&&(n.primKey.uuid=!0,n.primKey.name=n.primKey.name.substr(2),n.primKey.keyPath=n.primKey.keyPath.substr(2))}),Object.keys(t).forEach(function(e){0!==e.indexOf("_")&&0!==e.indexOf("$")&&(t[e].observable=!0)})}}function v(n){var t=100;e.ignoreTransaction(function(){return n._syncNodes.orderBy("myRevision").first(function(e){return n._changes.where("rev").below(e.myRevision).limit(t).primaryKeys()}).then(function(e){return 0!==e.length?n._changes.bulkDelete(e).then(function(){e.length===t&&setTimeout(function(){return n.isOpen()&&v(n)},500)}):void 0})})["catch"](function(){})}function y(o){function a(n,t){if(n===o.name){if(W>=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 w.reject(new e.DatabaseClosedError);var u=1e3,c=o._changes.where("rev").above(a.myRevision).limit(u).toArray(function(e){if(e.length>0){var n=e[e.length-1];r=e.length===u,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 N?new Error("Browser is shutting down"):(o.close(),console.error("Out of sync"),_.location&&_.location.reload(!0),new Error("Out of sync"));return r||y.latestRevision[o.name]>a.myRevision?s(y.latestRevision[o.name],(t||0)+1,r):void 0})["finally"](function(){delete s.ongoingOperation});return t||(s.ongoingOperation=c),c}function u(){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(u,S))})}function l(){K=null;var n=B.node&&B.node.id;n&&e.vip(function(){s(y.latestRevision[o.name]).then(v).then(H)["catch"]("DatabaseClosedError",function(){})["finally"](function(){B.node&&B.node.id===n&&o.isOpen()&&(K=setTimeout(l,O))})})}function v(){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.deleteTimeStamp\r\n var rv = undefined;\r\n if (primKey === undefined && table.schema.primKey.uuid) {\r\n primKey = rv = createUUID();\r\n if (table.schema.primKey.keyPath) {\r\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\r\n }\r\n }\r\n\r\n var change = {\r\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.\r\n table: table.name,\r\n key: primKey === undefined ? null : primKey,\r\n type: CREATE,\r\n obj: obj\r\n };\r\n\r\n var promise = db._changes.add(change).then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n return rev;\r\n });\r\n\r\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\r\n this.onsuccess = function (resultKey) {\r\n if (primKey != resultKey)\r\n promise._then(function () {\r\n change.key = resultKey;\r\n db._changes.put(change);\r\n });\r\n };\r\n\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n\r\n return rv;\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport {UPDATE} from '../change_types';\r\n\r\nexport default function initUpdatingHook(db, tableName) {\r\n return function updatingHook(mods, primKey, oldObj, trans) {\r\n /// \r\n // mods may contain property paths with undefined as value if the property\r\n // is being deleted. Since we cannot persist undefined we need to act\r\n // like those changes is setting the value to null instead.\r\n var modsWithoutUndefined = {};\r\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\r\n // Therefore we may do that kind of optimization here - to not add change entries if\r\n // there's nothing to change.\r\n var anythingChanged = false;\r\n var newObj = Dexie.deepClone(oldObj);\r\n for (var propPath in mods) {\r\n var mod = mods[propPath];\r\n if (typeof mod === 'undefined') {\r\n Dexie.delByKeyPath(newObj, propPath);\r\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\r\n anythingChanged = true;\r\n } else {\r\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\r\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\r\n Dexie.setByKeyPath(newObj, propPath, mod);\r\n modsWithoutUndefined[propPath] = mod;\r\n anythingChanged = true;\r\n }\r\n }\r\n }\r\n if (anythingChanged) {\r\n var change = {\r\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.\r\n table: tableName,\r\n key: primKey,\r\n type: UPDATE,\r\n mods: modsWithoutUndefined,\r\n oldObj: oldObj,\r\n obj: newObj\r\n };\r\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\r\n this.onsuccess = function () {\r\n promise._then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n });\r\n };\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change.\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n }\r\n };\r\n}\r\n","import {DELETE} from '../change_types';\r\n\r\nexport default function initDeletingHook(db, tableName) {\r\n return function deletingHook(primKey, obj, trans) {\r\n /// \r\n var promise = db._changes.add({\r\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.\r\n table: tableName,\r\n key: primKey,\r\n type: DELETE,\r\n oldObj: obj\r\n }).then(function (rev) {\r\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\r\n return rev;\r\n })\r\n .catch((e) => {\r\n console.log(obj)\r\n console.log(e.stack)\r\n })\r\n this.onerror = function () {\r\n // If the main operation fails, make sure to regret the change.\r\n // Using _then because if promise is already fullfilled, the standard then() would\r\n // do setTimeout() and we would loose the transaction.\r\n promise._then(function (rev) {\r\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\r\n db._changes.delete(rev);\r\n });\r\n };\r\n };\r\n}\r\n","import initCreatingHook from './creating';\r\nimport initUpdatingHook from './updating';\r\nimport initDeletingHook from './deleting';\r\n\r\nexport default function initCrudMonitor(db) {\r\n//\r\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\r\n//\r\n return function crudMonitor(table) {\r\n /// \r\n if (table.hook._observing) return;\r\n table.hook._observing = true;\r\n\r\n const tableName = table.name;\r\n table.hook('creating').subscribe(initCreatingHook(db, table));\r\n\r\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\r\n\r\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initOnStorage(Observable) {\r\n return function onStorage(event) {\r\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\r\n if (event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\r\n var parts = event.key.split('/');\r\n var prop = parts[1];\r\n var dbname = parts[2];\r\n if (prop === 'latestRevision') {\r\n var rev = parseInt(event.newValue, 10);\r\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\r\n Observable.latestRevision[dbname] = rev;\r\n Dexie.ignoreTransaction(function () {\r\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\r\n });\r\n }\r\n } else if (prop.indexOf(\"deadnode:\") === 0) {\r\n var nodeID = parseInt(prop.split(':')[1], 10);\r\n if (event.newValue) {\r\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\r\n }\r\n } else if (prop === 'intercomm') {\r\n if (event.newValue) {\r\n Observable.on.intercomm.fire(dbname);\r\n }\r\n }\r\n }\r\n };\r\n}\r\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\r\n return function overrideOpen(origOpen) {\r\n return function () {\r\n //\r\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\r\n //\r\n Object.keys(db._allTables).forEach(tableName => {\r\n let table = db._allTables[tableName];\r\n if (table.schema.observable) {\r\n crudMonitor(table);\r\n }\r\n if (table.name === \"_syncNodes\") {\r\n table.mapToClass(SyncNode);\r\n }\r\n });\r\n return origOpen.apply(this, arguments);\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\r\n//\r\n// Intercommunication between nodes\r\n//\r\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\r\n\r\n var requestsWaitingForReply = {};\r\n\r\n /**\r\n * @param {string} type Type of message\r\n * @param message Message to send\r\n * @param {number} destinationNode ID of destination node\r\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.\r\n */\r\n db.observable.sendMessage = function (type, message, destinationNode, options) {\r\n /// Type of message\r\n /// Message to send\r\n /// ID of destination node\r\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.\r\n options = options || {};\r\n if (!mySyncNode.node)\r\n return options.wantReply ?\r\n Promise.reject(new Dexie.DatabaseClosedError()) :\r\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\r\n\r\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\r\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\r\n return Dexie.ignoreTransaction(()=> {\r\n var tables = [\"_intercomm\"];\r\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.\r\n var promise = db.transaction('rw', tables, () => {\r\n if (options.wantReply) {\r\n // Check that there is a receiver there to take the request.\r\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\r\n if (receiverAlive)\r\n return db._intercomm.add(msg);\r\n else // If we couldn't find a node -> send to master\r\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\r\n msg.destinationNode = masterNode.id;\r\n return db._intercomm.add(msg)\r\n });\r\n });\r\n } else {\r\n // If caller doesn't need a response, we don't have to make sure that it gets one.\r\n return db._intercomm.add(msg);\r\n }\r\n }).then(messageId => {\r\n var rv = null;\r\n if (options.wantReply) {\r\n rv = new Promise(function (resolve, reject) {\r\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\r\n });\r\n }\r\n if (localStorage) {\r\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\r\n }\r\n Observable.on.intercomm.fire(db.name);\r\n return rv;\r\n });\r\n\r\n if (!options.wantReply) {\r\n promise.catch(()=> {\r\n });\r\n return;\r\n } else {\r\n // Forward rejection to caller if it waits for reply.\r\n return promise;\r\n }\r\n });\r\n };\r\n\r\n // Send a message to all local _syncNodes\r\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\r\n if (!mySyncNode.node) return;\r\n var mySyncNodeId = mySyncNode.node.id;\r\n Dexie.ignoreTransaction(()=> {\r\n db._syncNodes.toArray(nodes => {\r\n return Promise.all(nodes\r\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\r\n .map(node => db.observable.sendMessage(type, message, node.id)));\r\n }).catch(()=> {\r\n });\r\n });\r\n };\r\n\r\n function consumeIntercommMessages() {\r\n // Check if we got messages:\r\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\r\n\r\n return Dexie.ignoreTransaction(()=> {\r\n return db.transaction('rw', '_intercomm', function() {\r\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\r\n messages.forEach(msg => consumeMessage(msg));\r\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\r\n });\r\n });\r\n });\r\n }\r\n\r\n function consumeMessage(msg) {\r\n if (msg.type === 'response') {\r\n // This is a response. Lookup pending request and fulfill its promise.\r\n var request = requestsWaitingForReply[msg.requestId.toString()];\r\n if (request) {\r\n if (msg.isFailure) {\r\n request.reject(msg.message.error);\r\n } else {\r\n request.resolve(msg.message.result);\r\n }\r\n delete requestsWaitingForReply[msg.requestId.toString()];\r\n }\r\n } else {\r\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\r\n msg.resolve = function (result) {\r\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\r\n };\r\n msg.reject = function (error) {\r\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\r\n };\r\n db.on.message.fire(msg);\r\n }\r\n }\r\n\r\n // Listener for 'intercomm' events\r\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\r\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\r\n // sendMessage is used to communicate in the same tab and to trigger a storage event\r\n function onIntercomm(dbname) {\r\n // When storage event trigger us to check\r\n if (dbname === db.name) {\r\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\r\n }\r\n }\r\n\r\n return {\r\n onIntercomm,\r\n consumeIntercommMessages\r\n };\r\n}\r\n","export default function overrideParseStoresSpec(origFunc) {\r\n return function(stores, dbSchema) {\r\n // Create the _changes and _syncNodes tables\r\n stores[\"_changes\"] = \"++rev\";\r\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\r\n stores[\"_intercomm\"] = \"++id,destinationNode\";\r\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\r\n // Call default implementation. Will populate the dbSchema structures.\r\n origFunc.call(this, stores, dbSchema);\r\n // Allow UUID primary keys using $$ prefix on primary key or indexes\r\n Object.keys(dbSchema).forEach(function(tableName) {\r\n var schema = dbSchema[tableName];\r\n if (schema.primKey.name.indexOf('$$') === 0) {\r\n schema.primKey.uuid = true;\r\n schema.primKey.name = schema.primKey.name.substr(2);\r\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\r\n }\r\n });\r\n // Now mark all observable tables\r\n Object.keys(dbSchema).forEach(function(tableName) {\r\n // Marked observable tables with \"observable\" in their TableSchema.\r\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\r\n dbSchema[tableName].observable = true;\r\n }\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function deleteOldChanges(db) {\r\n // This is a background job and should never be done within\r\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\r\n // We should not return the Promise but catch it ourselves instead.\r\n\r\n // To prohibit starving the database we want to lock transactions as short as possible\r\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\r\n // continuation every 500 ms.\r\n const CHUNK_SIZE = 100;\r\n\r\n Dexie.ignoreTransaction(()=>{\r\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\r\n return db._changes\r\n .where(\"rev\").below(oldestNode.myRevision)\r\n .limit(CHUNK_SIZE)\r\n .primaryKeys();\r\n }).then(keysToDelete => {\r\n if (keysToDelete.length === 0) return; // Done.\r\n return db._changes.bulkDelete(keysToDelete).then(()=> {\r\n // If not done garbage collecting, reschedule a continuation of it until done.\r\n if (keysToDelete.length === CHUNK_SIZE) {\r\n // Limit reached. Changes are there are more job to do. Schedule again:\r\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\r\n }\r\n });\r\n });\r\n }).catch(()=>{\r\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\r\n // No need to log this.\r\n });\r\n}\r\n","/* ========================================================================== \r\n * dexie-observable.js\r\n * ==========================================================================\r\n *\r\n * Dexie addon for observing database changes not just on local db instance\r\n * but also on other instances, tabs and windows.\r\n *\r\n * Comprises a base framework for dexie-syncable.js\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com,\r\n * Nikolas Poniros, https://github.com/nponiros\r\n *\r\n * ==========================================================================\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n * \r\n */\r\nimport Dexie from 'dexie';\r\nimport { nop, promisableChain, createUUID } from './utils';\r\n\r\nimport initOverrideCreateTransaction from './override-create-transaction';\r\nimport initWakeupObservers from './wakeup-observers';\r\nimport initCrudMonitor from './hooks/crud-monitor';\r\nimport initOnStorage from './on-storage';\r\nimport initOverrideOpen from './override-open';\r\nimport initIntercomm from './intercomm';\r\n\r\nimport overrideParseStoresSpec from './override-parse-stores-spec';\r\n\r\nimport deleteOldChanges from './delete-old-changes';\r\n\r\nvar global = self;\r\n\r\n/** class DatabaseChange\r\n *\r\n * Object contained by the _changes table.\r\n */\r\nvar DatabaseChange = Dexie.defineClass({\r\n rev: Number, // Auto-incremented primary key\r\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\r\n table: String, // Table name\r\n key: Object, // Primary key. Any type.\r\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\r\n obj: Object, // CREATE: obj contains the object created.\r\n mods: Object, // UPDATE: mods contains the modifications made to the object.\r\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\r\n});\r\n\r\n// Import some usable helper functions\r\nvar override = Dexie.override;\r\nvar Promise = Dexie.Promise;\r\nvar browserIsShuttingDown = false;\r\n\r\nexport default function Observable(db) {\r\n /// \r\n /// Extension to Dexie providing Syncronization capabilities to Dexie.\r\n /// \r\n /// \r\n\r\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.\r\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\r\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \r\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)\r\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.\r\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\r\n\r\n var localStorage = Observable.localStorageImpl;\r\n\r\n /** class SyncNode\r\n *\r\n * Object contained in the _syncNodes table.\r\n */\r\n var SyncNode = Dexie.defineClass({\r\n //id: Number,\r\n myRevision: Number,\r\n type: String, // \"local\" or \"remote\"\r\n lastHeartBeat: Number,\r\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.\r\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\r\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\r\n\r\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\r\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \r\n syncContext: null,\r\n syncOptions: Object,\r\n connected: false, // FIXTHIS: Remove! Replace with status.\r\n status: Number,\r\n appliedRemoteRevision: null,\r\n remoteBaseRevisions: [{ local: Number, remote: null }],\r\n dbUploadState: {\r\n tablesToUpload: [String],\r\n currentTable: String,\r\n currentKey: null,\r\n localBaseRevision: Number\r\n }\r\n });\r\n\r\n db.observable = {};\r\n db.observable.SyncNode = SyncNode;\r\n\r\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\r\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\r\n const crudMonitor = initCrudMonitor(db);\r\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\r\n\r\n var mySyncNode = {node: null};\r\n\r\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\r\n const onIntercomm = intercomm.onIntercomm;\r\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\r\n\r\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\r\n Object.defineProperty(db, \"_localSyncNode\", {\r\n get: function() { return mySyncNode.node; }\r\n });\r\n\r\n var pollHandle = null,\r\n heartbeatHandle = null;\r\n\r\n if (Dexie.fake) {\r\n // This code will never run.\r\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\r\n db.version(1).stores({\r\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\r\n _changes: \"++rev\",\r\n _intercomm: \"++id,destinationNode\",\r\n _uncommittedChanges: \"++id,node\"\r\n });\r\n db._syncNodes.mapToClass(SyncNode);\r\n db._changes.mapToClass(DatabaseChange);\r\n mySyncNode.node = new SyncNode({\r\n myRevision: 0,\r\n type: \"local\",\r\n lastHeartBeat: Date.now(),\r\n deleteTimeStamp: null\r\n });\r\n }\r\n\r\n //\r\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\r\n // It also adds UUID support for the primary key and sets tables as observable tables.\r\n //\r\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\r\n\r\n // changes event on db:\r\n db.on.addEventType({\r\n changes: 'asap',\r\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.\r\n message: 'asap'\r\n });\r\n\r\n //\r\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\r\n //\r\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\r\n\r\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\r\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\r\n // window with the same database name has been created already, this static property will already be set correctly.\r\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\r\n\r\n //\r\n // Override open to setup hooks for db changes and map the _syncNodes table to class\r\n //\r\n db.open = override(db.open, overrideOpen);\r\n\r\n db.close = override(db.close, function(origClose) {\r\n return function () {\r\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\r\n // Teardown our framework.\r\n if (wakeupObservers.timeoutHandle) {\r\n clearTimeout(wakeupObservers.timeoutHandle);\r\n delete wakeupObservers.timeoutHandle;\r\n }\r\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\r\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\r\n Observable.on('intercomm').unsubscribe(onIntercomm);\r\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\r\n // Inform other db instances in same window that we are dying:\r\n if (mySyncNode.node && mySyncNode.node.id) {\r\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\r\n // Inform other windows as well:\r\n if (localStorage) {\r\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.\r\n }\r\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\r\n mySyncNode.node.lastHeartBeat = 0;\r\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\r\n mySyncNode.node = null;\r\n }\r\n\r\n if (pollHandle) clearTimeout(pollHandle);\r\n pollHandle = null;\r\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\r\n heartbeatHandle = null;\r\n return origClose.apply(this, arguments);\r\n };\r\n });\r\n\r\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\r\n db.delete = override(db.delete, function(origDelete) {\r\n return function() {\r\n return origDelete.apply(this, arguments).then(function(result) {\r\n // Reset Observable.latestRevision[db.name]\r\n Observable.latestRevision[db.name] = 0;\r\n return result;\r\n });\r\n };\r\n });\r\n\r\n // When db opens, make sure to start monitor any changes before other db operations will start.\r\n db.on(\"ready\", function startObserving() {\r\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\r\n \r\n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\r\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\r\n // Therefore we know that the retrieved value will be This query will\r\n var latestRevision = (lastChange ? lastChange.rev : 0);\r\n mySyncNode.node = new SyncNode({\r\n myRevision: latestRevision,\r\n type: \"local\",\r\n lastHeartBeat: Date.now(),\r\n deleteTimeStamp: null,\r\n isMaster: 0\r\n });\r\n if (Observable.latestRevision[db.name] < latestRevision) {\r\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\r\n // There are other db instances in same window that hasnt yet been informed about a new revision\r\n Observable.latestRevision[db.name] = latestRevision;\r\n Dexie.ignoreTransaction(function() {\r\n Observable.on.latestRevisionIncremented.fire(latestRevision);\r\n });\r\n }\r\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\r\n return db.transaction('rw', '_syncNodes', () => {\r\n return db._syncNodes\r\n .where('isMaster').equals(1)\r\n .first(currentMaster => {\r\n if (!currentMaster) {\r\n // There's no master. We must be the master\r\n mySyncNode.node.isMaster = 1;\r\n } else if (currentMaster.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\r\n // Master have been inactive for too long\r\n // Take over mastership\r\n mySyncNode.node.isMaster = 1;\r\n currentMaster.isMaster = 0;\r\n return db._syncNodes.put(currentMaster);\r\n }\r\n }).then(()=>{\r\n // Add our node to DB and start subscribing to events\r\n return db._syncNodes.add(mySyncNode.node).then(function() {\r\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\r\n Observable.on('beforeunload', onBeforeUnload);\r\n Observable.on('suicideNurseCall', onSuicide);\r\n Observable.on('intercomm', onIntercomm);\r\n // Start polling for changes and do cleanups:\r\n pollHandle = setTimeout(poll, LOCAL_POLL);\r\n // Start heartbeat\r\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\r\n });\r\n });\r\n }).then(function () {\r\n cleanup();\r\n });\r\n });\r\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\r\n\r\n var handledRevision = 0;\r\n\r\n function onLatestRevisionIncremented(dbname, latestRevision) {\r\n if (dbname === db.name) {\r\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\r\n handledRevision = latestRevision;\r\n Dexie.vip(function() {\r\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\r\n // Handle database closed error gracefully while reading changes.\r\n // Don't trigger 'unhandledrejection'.\r\n // Even though we intercept the close() method, it might be called when in the middle of\r\n // reading changes and then that flow will cancel with DatabaseClosedError.\r\n });\r\n });\r\n }\r\n }\r\n\r\n function readChanges(latestRevision, recursion, wasPartial) {\r\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\r\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\r\n // should be handled in case database is totally empty we should fail if sync is not available)\r\n if (!recursion && readChanges.ongoingOperation) {\r\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\r\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().\r\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\r\n return readChanges.ongoingOperation;\r\n }\r\n\r\n var partial = false;\r\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.\r\n if (!ourSyncNode) {\r\n return Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n var LIMIT = 1000;\r\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\r\n if (changes.length > 0) {\r\n var lastChange = changes[changes.length - 1];\r\n partial = (changes.length === LIMIT);\r\n db.on('changes').fire(changes, partial);\r\n ourSyncNode.myRevision = lastChange.rev;\r\n } else if (wasPartial) {\r\n // No more changes, BUT since we have triggered on('changes') with partial = true,\r\n // we HAVE TO trigger changes again with empty list and partial = false\r\n db.on('changes').fire([], false);\r\n }\r\n\r\n let ourNodeStillExists = false;\r\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\r\n ourNodeStillExists = true;\r\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\r\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\r\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\r\n }).then(()=>ourNodeStillExists);\r\n }).then(ourNodeStillExists =>{\r\n if (!ourNodeStillExists) {\r\n // My node has been deleted. We must have been lazy and got removed by another node.\r\n if (browserIsShuttingDown) {\r\n throw new Error(\"Browser is shutting down\");\r\n } else {\r\n db.close();\r\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\r\n if (global.location) global.location.reload(true);\r\n throw new Error(\"Out of sync\"); // Will make current promise reject\r\n }\r\n }\r\n\r\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\r\n // resolve until all changes have been read.\r\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\r\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\r\n // In either case, call readChanges() again until we're done.\r\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\r\n }\r\n\r\n }).finally(function() {\r\n delete readChanges.ongoingOperation;\r\n });\r\n\r\n if (!recursion) {\r\n readChanges.ongoingOperation = promise;\r\n }\r\n return promise;\r\n }\r\n\r\n /**\r\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\r\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\r\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\r\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\r\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\r\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\r\n * \r\n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\r\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\r\n * it would believe it was dead.\r\n */\r\n function heartbeat() {\r\n heartbeatHandle = null;\r\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\r\n if (!currentInstance) return;\r\n db.transaction('rw!', db._syncNodes, ()=>{\r\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\r\n if (!ourSyncNode) {\r\n // We do not exist anymore. Call db.close() to teardown polls etc.\r\n if (db.isOpen()) db.close();\r\n return;\r\n }\r\n ourSyncNode.lastHeartBeat = Date.now();\r\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\r\n return db._syncNodes.put(ourSyncNode);\r\n });\r\n }).catch('DatabaseClosedError', () => {\r\n // Ignore silently\r\n }).finally(() => {\r\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\r\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\r\n }\r\n });\r\n }\r\n\r\n function poll() {\r\n pollHandle = null;\r\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\r\n if (!currentInstance) return;\r\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.\r\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\r\n .catch('DatabaseClosedError', ()=>{\r\n // Handle database closed error gracefully while reading changes.\r\n // Don't trigger 'unhandledrejection'.\r\n // Even though we intercept the close() method, it might be called when in the middle of\r\n // reading changes and then that flow will cancel with DatabaseClosedError.\r\n })\r\n .finally(function() {\r\n // Poll again in given interval:\r\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\r\n pollHandle = setTimeout(poll, LOCAL_POLL);\r\n }\r\n });\r\n });\r\n }\r\n\r\n \r\n function cleanup() {\r\n var ourSyncNode = mySyncNode.node;\r\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\r\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\r\n // Cleanup dead local nodes that has no heartbeat for over a minute\r\n // Dont do the following:\r\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\r\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\r\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.\r\n var weBecameMaster = false;\r\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\r\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\r\n // Delete the node.\r\n delete this.value;\r\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\r\n if (localStorage) {\r\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\r\n }\r\n // Check if we are deleting a master node\r\n if (node.isMaster) {\r\n // The node we are deleting is master. We must take over that role.\r\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\r\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\r\n weBecameMaster = true;\r\n }\r\n // Cleanup intercomm messages destinated to the node being deleted.\r\n // Those that waits for reply should be redirected to us.\r\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\r\n if (msg.wantReply)\r\n msg.destinationNode = ourSyncNode.id;\r\n else\r\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\r\n delete this.value;\r\n });\r\n } else if (!node.deleteTimeStamp) {\r\n // Mark the node for deletion\r\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\r\n }\r\n }).then(function() {\r\n // Cleanup old revisions that no node is interested of.\r\n Observable.deleteOldChanges(db);\r\n return db.on(\"cleanup\").fire(weBecameMaster);\r\n });\r\n });\r\n }\r\n\r\n function onBeforeUnload() {\r\n // Mark our own sync node for deletion.\r\n if (!mySyncNode.node) return;\r\n browserIsShuttingDown = true;\r\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\r\n mySyncNode.node.lastHeartBeat = 0;\r\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\r\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...\r\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:\r\n if (localStorage) {\r\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.\r\n }\r\n }\r\n\r\n function onSuicide(dbname, nodeID) {\r\n if (dbname === db.name && !Observable.wereTheOneDying) {\r\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.\r\n // It's own call to put() may have been cancelled.\r\n // Note also that in IE, this event may be called twice, but that doesnt harm!\r\n Dexie.vip(function() {\r\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\r\n });\r\n }\r\n }\r\n\r\n}\r\n\r\n//\r\n// Static properties and methods\r\n// \r\n\r\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\r\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\r\nObservable.createUUID = createUUID;\r\n\r\nObservable.deleteOldChanges = deleteOldChanges;\r\n\r\nObservable._onStorage = initOnStorage(Observable);\r\n\r\nObservable._onBeforeUnload = function() {\r\n Observable.on.beforeunload.fire();\r\n};\r\n\r\ntry {\r\n Observable.localStorageImpl = global.localStorage;\r\n} catch (ex){}\r\n\r\n//\r\n// Map window events to static events in Dexie.Observable:\r\n//\r\nif (global.addEventListener) {\r\n global.addEventListener(\"storage\", Observable._onStorage);\r\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\r\n}\r\n// Register addon:\r\nDexie.Observable = Observable;\r\nDexie.addons.push(Observable);\r\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..c082e62b0 --- /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 (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 +// 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'); + } + } + 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..50db3d54d --- /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';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initSyncableConnect(db, connect) {\r\n return function syncableConnect(protocolInstance, protocolName, url, options) {\r\n if (db.isOpen()) {\r\n // Database is open\r\n if (!db._localSyncNode)\r\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\r\n\r\n if (db._localSyncNode.isMaster) {\r\n // We are master node\r\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\r\n } else {\r\n // We are not master node\r\n // Request master node to do the connect:\r\n return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\r\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.\r\n return db.observable.sendMessage('connect', {\r\n protocolName: protocolName,\r\n url: url,\r\n options: options\r\n }, masterNode.id, {wantReply: true});\r\n });\r\n }\r\n } else if (db.hasBeenClosed()) {\r\n // Database has been closed.\r\n return Promise.reject(new Dexie.DatabaseClosedError());\r\n } else if (db.hasFailed()) {\r\n // Database has failed to open\r\n return Promise.reject(new Dexie.InvalidStateError(\r\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\r\n } else {\r\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\r\n // Wait for it to open, then connect.\r\n var promise = new Promise(function (resolve, reject) {\r\n db.on(\"ready\", () => {\r\n // First, check if this is the very first time we connect to given URL.\r\n // Need to know, because if it is, we should stall the promise returned to\r\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\r\n return db._syncNodes.get({url}, node => {\r\n // Ok, now we know whether we should await the connect promise or not.\r\n // No matter, we should now connect (will maybe create the SyncNode instance\r\n // representing the given URL)\r\n let connectPromise = db.syncable.connect(protocolName, url, options);\r\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\r\n // Ok, so let's see if we should suspend DB queries until connected or not:\r\n if (node && node.appliedRemoteRevision) {\r\n // The very first initial sync has been done so we need not wait\r\n // for the connect promise to complete. It can continue in background.\r\n // Returning here will resume db.on('ready') and resume all queries that\r\n // the application has put to the database.\r\n return;\r\n }\r\n // This was the very first time we connect to the remote server,\r\n // we must make sure that the initial sync request succeeeds before resuming\r\n // database queries that the application code puts onto the database.\r\n // If OFFLINE or other error, don't allow the application to proceed.\r\n // We are assuming that an initial sync is essential for the application to\r\n // function correctly.\r\n return connectPromise;\r\n });\r\n });\r\n // Force open() to happen. Otherwise connect() may stall forever.\r\n db.open().catch(ex => {\r\n // If open fails, db.on('ready') may not have been called and we must\r\n // reject promise with InvalidStateError\r\n reject(new Dexie.InvalidStateError(\r\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\r\n ex\r\n ));\r\n });\r\n });\r\n return promise;\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initPersistedContext(node) {\r\n //\r\n // PersistedContext : IPersistedContext\r\n //\r\n return class PersistedContext {\r\n constructor(nodeID, otherProps) {\r\n this.nodeID = nodeID;\r\n if (otherProps) Dexie.extend(this, otherProps);\r\n }\r\n\r\n save() {\r\n // Store this instance in the syncContext property of the node it belongs to.\r\n return Dexie.vip(() => {\r\n return node.save();\r\n });\r\n }\r\n }\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport initPersistedContext from './PersistedContext';\r\n\r\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\r\n return function getOrCreateSyncNode(options) {\r\n return db.transaction('rw', db._syncNodes, db._changes, function () {\r\n if (!url) throw new Error(\"Url cannot be empty\");\r\n\r\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\r\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\r\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\r\n // maps to class\r\n if (node) {\r\n const PersistedContext = initPersistedContext(node);\r\n // Node already there. Make syncContext become an instance of PersistedContext:\r\n node.syncContext = new PersistedContext(node.id, node.syncContext);\r\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\r\n node.syncOptions = options; // Options could have been changed\r\n db._syncNodes.put(node);\r\n } else {\r\n // Create new node and sync everything\r\n node = new db.observable.SyncNode();\r\n node.myRevision = -1;\r\n node.appliedRemoteRevision = null;\r\n node.remoteBaseRevisions = [];\r\n node.type = \"remote\";\r\n node.syncProtocol = protocolName;\r\n node.url = url;\r\n node.syncOptions = options;\r\n node.lastHeartBeat = Date.now();\r\n node.dbUploadState = null;\r\n const PersistedContext = initPersistedContext(node);\r\n Dexie.Promise.resolve(function () {\r\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\r\n if (options.initialUpload === false)\r\n return db._changes.toCollection().lastKey(function (currentRevision) {\r\n node.myRevision = currentRevision;\r\n });\r\n }()).then(function () {\r\n db._syncNodes.add(node).then(function (nodeID) {\r\n node.syncContext = new PersistedContext(nodeID); // Update syncContext in db with correct nodeId.\r\n db._syncNodes.put(node);\r\n });\r\n });\r\n }\r\n\r\n return node; // returning node will make the db.transaction()-promise resolve with this value.\r\n });\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initEnqueue(db) {\r\n return function enqueue(context, fn, instanceID) {\r\n function _enqueue() {\r\n if (!context.ongoingOperation) {\r\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\r\n return Dexie.vip(function () {\r\n return fn();\r\n });\r\n }).finally(()=> {\r\n delete context.ongoingOperation;\r\n });\r\n } else {\r\n context.ongoingOperation = context.ongoingOperation.then(function () {\r\n return enqueue(context, fn, instanceID);\r\n });\r\n }\r\n return context.ongoingOperation;\r\n }\r\n\r\n if (!instanceID) {\r\n // Caller wants to enqueue it until database becomes open.\r\n if (db.isOpen()) {\r\n return _enqueue();\r\n } else {\r\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\r\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)\r\n return _enqueue();\r\n } else {\r\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n };\r\n}\r\n","export default function initSaveToUncommittedChanges(db, node) {\r\n return function saveToUncommittedChanges(changes, remoteRevision) {\r\n return db.transaction('rw!', db._uncommittedChanges, () => {\r\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\r\n let changeWithNodeId = {\r\n node: node.id,\r\n type: change.type,\r\n table: change.table,\r\n key: change.key\r\n };\r\n if (change.obj) changeWithNodeId.obj = change.obj;\r\n if (change.mods) changeWithNodeId.mods = change.mods;\r\n return changeWithNodeId;\r\n }));\r\n }).then(() => {\r\n node.appliedRemoteRevision = remoteRevision;\r\n return node.save();\r\n });\r\n };\r\n}\r\n","// Change Types\r\nexport const CREATE = 1;\r\nexport const UPDATE = 2;\r\nexport const DELETE = 3;\r\n","import Dexie from 'dexie';\r\n\r\nexport default function bulkUpdate(table, changes) {\r\n let keys = changes.map(c => c.key);\r\n let map = {};\r\n // Retrieve current object of each change to update and map each\r\n // found object's primary key to the existing object:\r\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\r\n map[cursor.primaryKey+''] = obj;\r\n }).then(()=>{\r\n // Filter away changes whose key wasn't found in the local database\r\n // (we can't update them if we do not know the existing values)\r\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\r\n // Apply modifications onto each existing object (in memory)\r\n // and generate array of resulting objects to put using bulkPut():\r\n let objsToPut = updatesThatApply.map (c => {\r\n let curr = map[c.key+''];\r\n Object.keys(c.mods).forEach(keyPath => {\r\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\r\n });\r\n return curr;\r\n });\r\n return table.bulkPut(objsToPut);\r\n });\r\n}\r\n","import Dexie from 'dexie';\r\nimport { CREATE, DELETE, UPDATE } from './change_types';\r\nimport bulkUpdate from './bulk-update';\r\n\r\nexport default function initApplyChanges(db) {\r\n return function applyChanges(changes) {\r\n let collectedChanges = {};\r\n changes.forEach((change) => {\r\n if (!collectedChanges.hasOwnProperty(change.table)) {\r\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\r\n }\r\n collectedChanges[change.table][change.type].push(change);\r\n });\r\n let table_names = Object.keys(collectedChanges);\r\n let tables = table_names.map((table) => db.table(table));\r\n\r\n return db.transaction(\"rw\", tables, () => {\r\n table_names.forEach((table_name) => {\r\n const table = db.table(table_name);\r\n const specifyKeys = !table.schema.primKey.keyPath;\r\n const createChangesToApply = collectedChanges[table_name][CREATE];\r\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\r\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\r\n if (createChangesToApply.length > 0)\r\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\r\n createChangesToApply.map(c => c.key) : undefined);\r\n if (updateChangesToApply.length > 0)\r\n bulkUpdate(table, updateChangesToApply);\r\n if (deleteChangesToApply.length > 0)\r\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\r\n });\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\nimport initApplyChanges from './apply-changes';\r\n\r\nexport default function initFinallyCommitAllChanges(db, node) {\r\n const applyChanges = initApplyChanges(db);\r\n\r\n return function finallyCommitAllChanges(changes, remoteRevision) {\r\n // 1. Open a write transaction on all tables in DB\r\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\r\n table.name === '_uncommittedChanges' ||\r\n table.schema.observable);\r\n\r\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\r\n var trans = Dexie.currentTransaction;\r\n var localRevisionBeforeChanges = 0;\r\n return db._changes.orderBy('rev').last(function (lastChange) {\r\n // Store what revision we were at before committing the changes\r\n localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0;\r\n }).then(() => {\r\n // Specify the source. Important for the change consumer to ignore changes originated from self!\r\n trans.source = node.id;\r\n // 2. Apply uncommitted changes and delete each uncommitted change\r\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\r\n }).then(function (uncommittedChanges) {\r\n return applyChanges(uncommittedChanges);\r\n }).then(function () {\r\n return db._uncommittedChanges.where('node').equals(node.id).delete();\r\n }).then(function () {\r\n // 3. Apply last chunk of changes\r\n return applyChanges(changes);\r\n }).then(function () {\r\n // Get what revision we are at now:\r\n return db._changes.orderBy('rev').last();\r\n }).then(function (lastChange) {\r\n var currentLocalRevision = (lastChange && lastChange.rev) || 0;\r\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\r\n node.appliedRemoteRevision = remoteRevision;\r\n node.remoteBaseRevisions.push({remote: remoteRevision, local: currentLocalRevision});\r\n if (node.myRevision === localRevisionBeforeChanges) {\r\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\r\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\r\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\r\n node.myRevision = currentLocalRevision;\r\n }\r\n // Garbage collect remoteBaseRevisions not in use anymore:\r\n if (node.remoteBaseRevisions.length > 1) {\r\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\r\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\r\n node.remoteBaseRevisions.splice(0, i);\r\n break;\r\n }\r\n }\r\n }\r\n // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\r\n node.save().catch(err=> {\r\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\r\n });\r\n });\r\n });\r\n };\r\n}\r\n","export default function getBaseRevisionAndMaxClientRevision(node) {\r\n /// \r\n if (node.remoteBaseRevisions.length === 0)\r\n return {\r\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\r\n maxClientRevision: Infinity,\r\n remoteBaseRevision: null\r\n };\r\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\r\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\r\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\r\n return {\r\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\r\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\r\n };\r\n }\r\n }\r\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.\r\n return {\r\n maxClientRevision: node.remoteBaseRevisions[0].local,\r\n remoteBaseRevision: null\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function combineCreateAndUpdate(prevChange, nextChange) {\r\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\r\n Object.keys(nextChange.mods).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\r\n });\r\n return clonedChange;\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function combineUpdateAndUpdate(prevChange, nextChange) {\r\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\r\n Object.keys(nextChange.mods).forEach(function (keyPath) {\r\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\r\n var hadParentPath = false;\r\n Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\r\n Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\r\n hadParentPath = true;\r\n });\r\n if (!hadParentPath) {\r\n // Add or replace this keyPath and its new value\r\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\r\n }\r\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\r\n // we must mimic what would happen if applying the two changes after each other:\r\n Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\r\n delete clonedChange.mods[subPath];\r\n });\r\n });\r\n return clonedChange;\r\n}\r\n","import { CREATE, UPDATE, DELETE } from './change_types';\r\nimport combineCreateAndUpdate from './combine-create-and-update.js';\r\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\r\n\r\nexport default function mergeChange(prevChange, nextChange) {\r\n switch (prevChange.type) {\r\n case CREATE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // Another CREATE replaces previous CREATE.\r\n case UPDATE:\r\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\r\n case DELETE:\r\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!\r\n }\r\n break;\r\n case UPDATE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // Another CREATE replaces previous update.\r\n case UPDATE:\r\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\r\n case DELETE:\r\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\r\n }\r\n break;\r\n case DELETE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // A resurection occurred. Only create change is of interest.\r\n case UPDATE:\r\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\r\n case DELETE:\r\n return prevChange; // Still a delete change. Leave as is.\r\n }\r\n break;\r\n }\r\n}\r\n","import {CREATE, UPDATE} from '../change_types';\r\nimport mergeChange from '../merge-change';\r\n\r\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\r\n return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\r\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.\r\n var changeSet = {};\r\n var numChanges = 0;\r\n var partial = false;\r\n var ignoreSource = node.id;\r\n var nextRevision = revision;\r\n return db.transaction('r', db._changes, function () {\r\n var query = db._changes.where('rev').between(revision, maxRevision, false, true);\r\n return query.until(() => {\r\n if (numChanges === maxChanges) {\r\n partial = true;\r\n return true;\r\n }\r\n }).each(function (change) {\r\n // Note the revision in nextRevision:\r\n nextRevision = change.rev;\r\n // change.source is set based on currentTransaction.source\r\n if (change.source === ignoreSource) return;\r\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info:\r\n var changeToSend = {\r\n type: change.type,\r\n table: change.table,\r\n key: change.key\r\n };\r\n if (change.type === CREATE)\r\n changeToSend.obj = change.obj;\r\n else if (change.type === UPDATE)\r\n changeToSend.mods = change.mods;\r\n\r\n var id = change.table + \":\" + change.key;\r\n var prevChange = changeSet[id];\r\n if (!prevChange) {\r\n // This is the first change on this key. Add it unless it comes from the source that we are working against\r\n changeSet[id] = changeToSend;\r\n ++numChanges;\r\n } else {\r\n // Merge the oldchange with the new change\r\n var nextChange = changeToSend;\r\n var mergedChange = mergeChange(prevChange, nextChange);\r\n changeSet[id] = mergedChange;\r\n }\r\n });\r\n }).then(function () {\r\n var changes = Object.keys(changeSet).map(function (key) {\r\n return changeSet[key];\r\n });\r\n hasMoreToGive.hasMoreToGive = partial;\r\n return cb(changes, partial, {myRevision: nextRevision});\r\n });\r\n };\r\n}\r\n","import {CREATE} from '../change_types';\r\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\r\n\r\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\r\n return function getTableObjectsAsChanges(state, changes, collection) {\r\n /// \r\n /// \r\n /// \r\n var limitReached = false;\r\n return collection.until(function () {\r\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\r\n limitReached = true;\r\n return true;\r\n }\r\n }).each(function (item, cursor) {\r\n changes.push({\r\n type: CREATE,\r\n table: state.currentTable,\r\n key: cursor.key,\r\n obj: cursor.value\r\n });\r\n state.currentKey = cursor.key;\r\n }).then(function () {\r\n if (limitReached) {\r\n // Limit reached. Send partial result.\r\n hasMoreToGive.hasMoreToGive = true;\r\n return cb(changes, null, true, {dbUploadState: state});\r\n } else {\r\n // Done iterating this table. Check if there are more tables to go through:\r\n if (state.tablesToUpload.length === 0) {\r\n // Done iterating all tables\r\n // Now append changes occurred during our dbUpload:\r\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\r\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\r\n changes = changes.concat(additionalChanges);\r\n nodeModificationsOnAck.dbUploadState = null;\r\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\r\n });\r\n } else {\r\n // Not done iterating all tables. Continue on next table:\r\n state.currentTable = state.tablesToUpload.shift();\r\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\r\n }\r\n }\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\r\nimport initGetChangesSinceRevision from './get-changes-since-revision';\r\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\r\n\r\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\r\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\r\n\r\n return function getLocalChangesForNode(node, cb) {\r\n /// \r\n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\r\n /// for that node.\r\n /// \r\n /// \r\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.\r\n\r\n const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\r\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\r\n\r\n // Only a \"remote\" SyncNode created by Dexie.Syncable\r\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\r\n if (node.myRevision >= 0) {\r\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.\r\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\r\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\r\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\r\n });\r\n } else {\r\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.\r\n // Check if we're in the middle of already doing that:\r\n if (node.dbUploadState === null) {\r\n // Initialize dbUploadState\r\n var tablesToUpload = db.tables.filter(function (table) {\r\n return table.schema.observable;\r\n }).map(function (table) {\r\n return table.name;\r\n });\r\n if (tablesToUpload.length === 0) return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all.\r\n var dbUploadState = {\r\n tablesToUpload: tablesToUpload,\r\n currentTable: tablesToUpload.shift(),\r\n currentKey: null\r\n };\r\n return db._changes.orderBy('rev').last(function (lastChange) {\r\n dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0;\r\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\r\n return getTableObjectsAsChanges(dbUploadState, [], collection);\r\n });\r\n } else if (node.dbUploadState.currentKey) {\r\n const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\r\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\r\n } else {\r\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\r\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\r\n }\r\n }\r\n };\r\n}\r\n","export const Statuses = {\r\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\r\n OFFLINE: 0, // The sync provider hasn't yet become online, or it has been disconnected.\r\n CONNECTING: 1, // Trying to connect to server\r\n ONLINE: 2, // Connected to server and currently in sync with server\r\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.\r\n ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect.\r\n};\r\n\r\nexport const StatusTexts = {\r\n \"-1\": \"ERROR\",\r\n \"0\": \"OFFLINE\",\r\n \"1\": \"CONNECTING\",\r\n \"2\": \"ONLINE\",\r\n \"3\": \"SYNCING\",\r\n \"4\": \"ERROR_WILL_RETRY\"\r\n};\r\n","import Dexie from 'dexie';\r\n\r\nimport initEnqueue from './enqueue';\r\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\r\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\r\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\r\nimport {Statuses} from './statuses';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\r\n const enqueue = initEnqueue(db);\r\n var hasMoreToGive = {hasMoreToGive: true};\r\n\r\n function stillAlive() {\r\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\r\n // because the new instance should be considered a fresh instance and will have another local node.\r\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\r\n }\r\n\r\n return function connectProtocol(node, activePeer) {\r\n /// \r\n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\r\n\r\n const url = activePeer.url;\r\n\r\n function changeStatusTo(newStatus) {\r\n if (node.status !== newStatus) {\r\n node.status = newStatus;\r\n node.save().then(()=> {\r\n db.syncable.on.statusChanged.fire(newStatus, url);\r\n // Also broadcast message to other nodes about the status\r\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\r\n }).catch('DatabaseClosedError', ()=> {\r\n });\r\n }\r\n }\r\n\r\n activePeer.on('disconnect', function (newStatus) {\r\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\r\n });\r\n\r\n var connectedContinuation;\r\n changeStatusTo(Statuses.CONNECTING);\r\n return doSync();\r\n\r\n function doSync() {\r\n // Use enqueue() to ensure only a single promise execution at a time.\r\n return enqueue(doSync, function () {\r\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\r\n return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider);\r\n }, dbAliveID);\r\n }\r\n\r\n function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\r\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\r\n var finalSyncPromise = new Promise(function (resolve, reject) {\r\n rejectConnectPromise.p = function (err) {\r\n reject(err);\r\n };\r\n Dexie.asap(function () {\r\n try {\r\n protocolInstance.sync(\r\n node.syncContext,\r\n url,\r\n options,\r\n remoteBaseRevision,\r\n node.appliedRemoteRevision,\r\n changes,\r\n partial,\r\n applyRemoteChanges,\r\n onChangesAccepted,\r\n function (continuation) {\r\n resolve(continuation);\r\n },\r\n onError);\r\n } catch (ex) {\r\n onError(ex, Infinity);\r\n }\r\n\r\n function onError(error, again) {\r\n reject(error);\r\n if (stillAlive()) {\r\n if (!isNaN(again) && again < Infinity) {\r\n setTimeout(function () {\r\n if (stillAlive()) {\r\n changeStatusTo(Statuses.SYNCING);\r\n doSync().catch('DatabaseClosedError', abortTheProvider);\r\n }\r\n }, again);\r\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\r\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\r\n connectedContinuation = null;\r\n } else {\r\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\r\n }\r\n }\r\n }\r\n });\r\n });\r\n\r\n return finalSyncPromise.then(function () {\r\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\r\n return undefined;\r\n }).finally(()=> {\r\n // In case error happens after connect, don't try reject the connect promise anymore.\r\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\r\n // is active and this happens. It would fire unhandledrejection but that we do not want.\r\n rejectConnectPromise.p = null;\r\n });\r\n\r\n function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\r\n // otherwise it will execute when finalSyncPromise resolves.\r\n finalSyncPromise.then(continueSendingChanges);\r\n return node.save();\r\n }\r\n }\r\n\r\n function abortTheProvider(error) {\r\n activePeer.disconnect(Statuses.ERROR, error);\r\n }\r\n\r\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\r\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n return getLocalChangesForNode(node, autoAck);\r\n } else {\r\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\r\n }\r\n });\r\n }\r\n\r\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\r\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\r\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\r\n\r\n return enqueue(applyRemoteChanges, function () {\r\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\r\n // FIXTHIS: Check what to do if clear() is true!\r\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\r\n .catch(function (error) {\r\n abortTheProvider(error);\r\n return Promise.reject(error);\r\n });\r\n }, dbAliveID);\r\n }\r\n\r\n //\r\n //\r\n // Continuation Patterns Follows\r\n //\r\n //\r\n\r\n function continueSendingChanges(continuation) {\r\n if (!stillAlive()) { // Database was closed.\r\n if (continuation.disconnect)\r\n continuation.disconnect();\r\n return;\r\n }\r\n\r\n connectedContinuation = continuation;\r\n activePeer.on('disconnect', function () {\r\n if (connectedContinuation) {\r\n if (connectedContinuation.react) {\r\n try {\r\n // react pattern must provide a disconnect function.\r\n connectedContinuation.disconnect();\r\n } catch (e) {\r\n }\r\n }\r\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\r\n }\r\n });\r\n\r\n if (continuation.react) {\r\n continueUsingReactPattern(continuation);\r\n } else {\r\n continueUsingPollPattern(continuation);\r\n }\r\n }\r\n\r\n // React Pattern (eager)\r\n function continueUsingReactPattern(continuation) {\r\n var changesWaiting, // Boolean\r\n isWaitingForServer; // Boolean\r\n\r\n\r\n function onChanges() {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n if (isWaitingForServer)\r\n changesWaiting = true;\r\n else {\r\n reactToChanges();\r\n }\r\n }\r\n }\r\n\r\n db.on('changes', onChanges);\r\n\r\n activePeer.on('disconnect', function () {\r\n db.on.changes.unsubscribe(onChanges);\r\n });\r\n\r\n function reactToChanges() {\r\n if (!connectedContinuation) return;\r\n changesWaiting = false;\r\n isWaitingForServer = true;\r\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n if (!connectedContinuation) return;\r\n if (changes.length > 0) {\r\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n // More changes may be waiting:\r\n reactToChanges();\r\n });\r\n } else {\r\n isWaitingForServer = false;\r\n if (changesWaiting) {\r\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\r\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\r\n reactToChanges();\r\n } else {\r\n changeStatusTo(Statuses.ONLINE);\r\n }\r\n }\r\n }).catch(ex => {\r\n console.error(`Got ${ex.message} caught by reactToChanges`);\r\n abortTheProvider(ex);\r\n });\r\n }\r\n\r\n reactToChanges();\r\n }\r\n\r\n // Poll Pattern\r\n function continueUsingPollPattern() {\r\n\r\n function syncAgain() {\r\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n\r\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\r\n\r\n function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n }\r\n\r\n function onSuccess(continuation) {\r\n if (!connectedContinuation) {\r\n // Got disconnected before succeeding. Quit.\r\n return;\r\n }\r\n connectedContinuation = continuation;\r\n if (partial) {\r\n // We only sent partial changes. Need to do another round asap.\r\n syncAgain();\r\n } else {\r\n // We've sent all changes now (in sync!)\r\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\r\n // Provider wants to keep polling. Set Status to ONLINE.\r\n changeStatusTo(Statuses.ONLINE);\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, continuation.again);\r\n } else {\r\n // Provider seems finished polling. Since we are never going to poll again,\r\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\r\n activePeer.disconnect(Statuses.OFFLINE);\r\n }\r\n }\r\n }\r\n\r\n function onError(error, again) {\r\n if (!isNaN(again) && again < Infinity) {\r\n if (connectedContinuation) {\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, again);\r\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\r\n } // else status is already changed since we got disconnected.\r\n } else {\r\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\r\n }\r\n }\r\n }).catch(abortTheProvider);\r\n }\r\n\r\n if (hasMoreToGive.hasMoreToGive) {\r\n syncAgain();\r\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\r\n changeStatusTo(Statuses.ONLINE);\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, connectedContinuation.again);\r\n } else {\r\n // Provider seems finished polling. Since we are never going to poll again,\r\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\r\n activePeer.disconnect(Statuses.OFFLINE);\r\n }\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\r\nimport initConnectProtocol from './connect-protocol';\r\nimport {Statuses} from './statuses';\r\n\r\nexport default function initConnectFn(db, activePeers) {\r\n return function connect(protocolInstance, protocolName, url, options, dbAliveID) {\r\n /// \r\n var existingPeer = activePeers.filter(function (peer) {\r\n return peer.url === url;\r\n });\r\n if (existingPeer.length > 0) {\r\n const activePeer = existingPeer[0];\r\n const diffObject = {};\r\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\r\n // Options have been changed\r\n // We need to disconnect and reconnect\r\n if (Object.keys(diffObject).length !== 0) {\r\n return db.syncable.disconnect(url)\r\n .then(() => {\r\n return execConnect();\r\n })\r\n } else {\r\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\r\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.\r\n return existingPeer[0].connectPromise;\r\n }\r\n }\r\n\r\n function execConnect() {\r\n // Use an object otherwise we wouldn't be able to get the reject promise from\r\n // connectProtocol\r\n var rejectConnectPromise = {p: null};\r\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\r\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\r\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\r\n return connectProtocol(node, activePeer);\r\n });\r\n\r\n var disconnected = false;\r\n var activePeer = {\r\n url: url,\r\n status: Statuses.OFFLINE,\r\n connectPromise: connectPromise,\r\n syncOptions: options,\r\n on: Dexie.Events(null, \"disconnect\"),\r\n disconnect: function (newStatus, error) {\r\n var pos = activePeers.indexOf(activePeer);\r\n if (pos >= 0) activePeers.splice(pos, 1);\r\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\r\n if (!disconnected) {\r\n activePeer.on.disconnect.fire(newStatus, error);\r\n }\r\n disconnected = true;\r\n }\r\n };\r\n activePeers.push(activePeer);\r\n\r\n return connectPromise;\r\n }\r\n\r\n return execConnect();\r\n };\r\n}\r\n","/* ========================================================================== \r\n * dexie-syncable.js\r\n * ==========================================================================\r\n *\r\n * Dexie addon for syncing indexedDB with remote endpoints.\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com,\r\n * Nikolas Poniros, https://github.com/nponiros\r\n *\r\n * ==========================================================================\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n * \r\n */\r\n\r\nimport Dexie from \"dexie\";\r\n// Depend on 'dexie-observable'\r\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\r\n// That way, our plugin works in all UMD cases.\r\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\r\nimport \"dexie-observable\";\r\n\r\nimport initSyncableConnect from './syncable-connect';\r\nimport initConnectFn from './connect-fn';\r\nimport {Statuses, StatusTexts} from './statuses';\r\n\r\nvar override = Dexie.override,\r\n Promise = Dexie.Promise,\r\n Observable = Dexie.Observable;\r\n\r\nexport default function Syncable (db) {\r\n /// \r\n\r\n var activePeers = [];\r\n\r\n const connectFn = initConnectFn(db, activePeers);\r\n const syncableConnect = initSyncableConnect(db, connectFn);\r\n\r\n db.on('message', function(msg) {\r\n // Message from other local node arrives...\r\n Dexie.vip(function() {\r\n if (msg.type === 'connect') {\r\n // We are master node and another non-master node wants us to do the connect.\r\n db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\r\n } else if (msg.type === 'disconnect') {\r\n db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject);\r\n } else if (msg.type === 'syncStatusChanged') {\r\n // We are client and a master node informs us about syncStatus change.\r\n // Lookup the connectedProvider and call its event\r\n db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url);\r\n }\r\n });\r\n });\r\n\r\n db.on('cleanup', function(weBecameMaster) {\r\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\r\n if (weBecameMaster) {\r\n // We took over the master role in Observable's cleanup method.\r\n // We should connect to remote servers now.\r\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\r\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\r\n // connection has been closed. The new master would then be expected to reconnect.\r\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\r\n // an old closed one. \r\n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\r\n return db._syncNodes.where({type: 'remote'})\r\n .filter(node => node.status !== Statuses.OFFLINE)\r\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \r\n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\r\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\r\n })\r\n )));\r\n })).catch('DatabaseClosedError', ()=>{});\r\n }\r\n });\r\n\r\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\r\n // when the database opens. It will not wait for the connection to complete, just initiate the\r\n // connection so that it will continue syncing as long as the database is open.\r\n\r\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\r\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\r\n db.on('ready', function onReady() {\r\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\r\n if (db._localSyncNode && db._localSyncNode.isMaster) {\r\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\r\n // This \"ready\" subscriber will never be the one performing the initial sync request, because\r\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\r\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\r\n // called after this one. There, in that subscriber, the initial sync request will take place\r\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\r\n // next time this database is opened.\r\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\r\n // once in the past for each \"connectedRemoteNode\" we find in query below.\r\n\r\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\r\n db._syncNodes\r\n .where('type').equals('remote')\r\n .and(node => node.status !== Statuses.OFFLINE)\r\n .toArray(connectedRemoteNodes => {\r\n // There are connected remote nodes that we must manage (or take over to manage)\r\n connectedRemoteNodes.forEach(\r\n node => db.syncable.connect(\r\n node.syncProtocol,\r\n node.url,\r\n node.syncOptions) \r\n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\r\n );\r\n }).catch('DatabaseClosedError', ()=>{});\r\n }\r\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\r\n\r\n db.syncable = {};\r\n\r\n db.syncable.getStatus = function(url, cb) {\r\n if (db.isOpen()) {\r\n return Dexie.vip(function() {\r\n return db._syncNodes.where('url').equals(url).first(function(node) {\r\n return node ? node.status : Statuses.OFFLINE;\r\n });\r\n }).then(cb);\r\n } else {\r\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\r\n }\r\n };\r\n\r\n db.syncable.getOptions = function(url, cb) {\r\n return db.transaction('r?', db._syncNodes, () => {\r\n return db._syncNodes.where('url').equals(url).first(function(node) {\r\n return node.syncOptions;\r\n }).then(cb);\r\n });\r\n };\r\n\r\n db.syncable.list = function() {\r\n return db.transaction('r?', db._syncNodes, ()=>{\r\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\r\n return a.map(function(node) { return node.url; });\r\n });\r\n });\r\n };\r\n\r\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\r\n\r\n db.syncable.disconnect = function(url) {\r\n return Dexie.ignoreTransaction(()=>{\r\n return Promise.resolve().then(()=>{\r\n if (db._localSyncNode && db._localSyncNode.isMaster) {\r\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\r\n return peer.disconnect(Statuses.OFFLINE);\r\n }));\r\n } else {\r\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\r\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\r\n });\r\n }\r\n }).then(()=>{\r\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\r\n node.status = Statuses.OFFLINE;\r\n });\r\n });\r\n });\r\n };\r\n\r\n db.syncable.connect = function(protocolName, url, options) {\r\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.\r\n var protocolInstance = Syncable.registeredProtocols[protocolName];\r\n if (protocolInstance) {\r\n return syncableConnect(protocolInstance, protocolName, url, options);\r\n } else {\r\n return Promise.reject(\r\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\r\n );\r\n }\r\n };\r\n\r\n db.syncable.delete = function(url) {\r\n return db.syncable.disconnect(url).then(()=>{\r\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\r\n // Find the node(s)\r\n // Several can be found, as detected by @martindiphoorn,\r\n // let's delete them and cleanup _uncommittedChanges and _changes \r\n // accordingly.\r\n let nodeIDsToDelete;\r\n return db._syncNodes\r\n .where(\"url\").equals(url)\r\n .toArray(nodes => nodes.map(node => node.id))\r\n .then(nodeIDs => {\r\n nodeIDsToDelete = nodeIDs;\r\n // Delete the syncNode that represents the remote endpoint.\r\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\r\n })\r\n .then (() =>\r\n // In case there were uncommittedChanges belonging to this, delete them as well\r\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\r\n }).then(()=> {\r\n // Spawn background job to delete old changes, now that a node has been deleted,\r\n // there might be changes in _changes table that is not needed to keep anymore.\r\n // This is done in its own transaction, or possible several transaction to prohibit\r\n // starvation\r\n Observable.deleteOldChanges(db);\r\n });\r\n });\r\n };\r\n\r\n db.syncable.unsyncedChanges = function(url) {\r\n return db._syncNodes.where(\"url\").equals(url).first(function(node) {\r\n return db._changes.where('rev').above(node.myRevision).toArray();\r\n });\r\n };\r\n\r\n db.close = override(db.close, function(origClose) {\r\n return function() {\r\n activePeers.forEach(function(peer) {\r\n peer.disconnect();\r\n });\r\n return origClose.apply(this, arguments);\r\n };\r\n });\r\n\r\n Object.defineProperty(\r\n db.observable.SyncNode.prototype,\r\n 'save', {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value() {\r\n return db.transaction('rw?', db._syncNodes, () => {\r\n return db._syncNodes.put(this);\r\n });\r\n }\r\n });\r\n}\r\n\r\nSyncable.Statuses = Statuses;\r\n\r\nSyncable.StatusTexts = StatusTexts;\r\n\r\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\r\n\r\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\r\n /// \r\n /// Register a synchronization protocol that can synchronize databases with remote servers.\r\n /// \r\n /// Provider name\r\n /// Implementation of ISyncProtocol\r\n const partialsThreshold = protocolInstance.partialsThreshold;\r\n if (typeof partialsThreshold === 'number') {\r\n // Don't allow NaN or negative threshold\r\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\r\n throw new Error('The given number for the threshold is not supported');\r\n }\r\n // If the threshold is 0 we will not send any client changes but will get server changes\r\n } else {\r\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\r\n protocolInstance.partialsThreshold = Infinity;\r\n }\r\n Syncable.registeredProtocols[name] = protocolInstance;\r\n};\r\n\r\n// Register addon in Dexie:\r\nDexie.Syncable = Syncable;\r\nDexie.addons.push(Syncable);\r\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,SAAO,GAAG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M;;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.js b/addons/Dexie.Syncable/dist/dexie-syncable.js new file mode 100644 index 000000000..c7f2fab2d --- /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, Mon Oct 02 2017 + * + * 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 (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 +// 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, Mon Oct 02 2017 + * + * 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'); + } + } + 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..683c0b273 --- /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';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initSyncableConnect(db, connect) {\r\n return function syncableConnect(protocolInstance, protocolName, url, options) {\r\n if (db.isOpen()) {\r\n // Database is open\r\n if (!db._localSyncNode)\r\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\r\n\r\n if (db._localSyncNode.isMaster) {\r\n // We are master node\r\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\r\n } else {\r\n // We are not master node\r\n // Request master node to do the connect:\r\n return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\r\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.\r\n return db.observable.sendMessage('connect', {\r\n protocolName: protocolName,\r\n url: url,\r\n options: options\r\n }, masterNode.id, {wantReply: true});\r\n });\r\n }\r\n } else if (db.hasBeenClosed()) {\r\n // Database has been closed.\r\n return Promise.reject(new Dexie.DatabaseClosedError());\r\n } else if (db.hasFailed()) {\r\n // Database has failed to open\r\n return Promise.reject(new Dexie.InvalidStateError(\r\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\r\n } else {\r\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\r\n // Wait for it to open, then connect.\r\n var promise = new Promise(function (resolve, reject) {\r\n db.on(\"ready\", () => {\r\n // First, check if this is the very first time we connect to given URL.\r\n // Need to know, because if it is, we should stall the promise returned to\r\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\r\n return db._syncNodes.get({url}, node => {\r\n // Ok, now we know whether we should await the connect promise or not.\r\n // No matter, we should now connect (will maybe create the SyncNode instance\r\n // representing the given URL)\r\n let connectPromise = db.syncable.connect(protocolName, url, options);\r\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\r\n // Ok, so let's see if we should suspend DB queries until connected or not:\r\n if (node && node.appliedRemoteRevision) {\r\n // The very first initial sync has been done so we need not wait\r\n // for the connect promise to complete. It can continue in background.\r\n // Returning here will resume db.on('ready') and resume all queries that\r\n // the application has put to the database.\r\n return;\r\n }\r\n // This was the very first time we connect to the remote server,\r\n // we must make sure that the initial sync request succeeeds before resuming\r\n // database queries that the application code puts onto the database.\r\n // If OFFLINE or other error, don't allow the application to proceed.\r\n // We are assuming that an initial sync is essential for the application to\r\n // function correctly.\r\n return connectPromise;\r\n });\r\n });\r\n // Force open() to happen. Otherwise connect() may stall forever.\r\n db.open().catch(ex => {\r\n // If open fails, db.on('ready') may not have been called and we must\r\n // reject promise with InvalidStateError\r\n reject(new Dexie.InvalidStateError(\r\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\r\n ex\r\n ));\r\n });\r\n });\r\n return promise;\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initPersistedContext(node) {\r\n //\r\n // PersistedContext : IPersistedContext\r\n //\r\n return class PersistedContext {\r\n constructor(nodeID, otherProps) {\r\n this.nodeID = nodeID;\r\n if (otherProps) Dexie.extend(this, otherProps);\r\n }\r\n\r\n save() {\r\n // Store this instance in the syncContext property of the node it belongs to.\r\n return Dexie.vip(() => {\r\n return node.save();\r\n });\r\n }\r\n }\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport initPersistedContext from './PersistedContext';\r\n\r\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\r\n return function getOrCreateSyncNode(options) {\r\n return db.transaction('rw', db._syncNodes, db._changes, function () {\r\n if (!url) throw new Error(\"Url cannot be empty\");\r\n\r\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\r\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\r\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\r\n // maps to class\r\n if (node) {\r\n const PersistedContext = initPersistedContext(node);\r\n // Node already there. Make syncContext become an instance of PersistedContext:\r\n node.syncContext = new PersistedContext(node.id, node.syncContext);\r\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\r\n node.syncOptions = options; // Options could have been changed\r\n db._syncNodes.put(node);\r\n } else {\r\n // Create new node and sync everything\r\n node = new db.observable.SyncNode();\r\n node.myRevision = -1;\r\n node.appliedRemoteRevision = null;\r\n node.remoteBaseRevisions = [];\r\n node.type = \"remote\";\r\n node.syncProtocol = protocolName;\r\n node.url = url;\r\n node.syncOptions = options;\r\n node.lastHeartBeat = Date.now();\r\n node.dbUploadState = null;\r\n const PersistedContext = initPersistedContext(node);\r\n Dexie.Promise.resolve(function () {\r\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\r\n if (options.initialUpload === false)\r\n return db._changes.toCollection().lastKey(function (currentRevision) {\r\n node.myRevision = currentRevision;\r\n });\r\n }()).then(function () {\r\n db._syncNodes.add(node).then(function (nodeID) {\r\n node.syncContext = new PersistedContext(nodeID); // Update syncContext in db with correct nodeId.\r\n db._syncNodes.put(node);\r\n });\r\n });\r\n }\r\n\r\n return node; // returning node will make the db.transaction()-promise resolve with this value.\r\n });\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initEnqueue(db) {\r\n return function enqueue(context, fn, instanceID) {\r\n function _enqueue() {\r\n if (!context.ongoingOperation) {\r\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\r\n return Dexie.vip(function () {\r\n return fn();\r\n });\r\n }).finally(()=> {\r\n delete context.ongoingOperation;\r\n });\r\n } else {\r\n context.ongoingOperation = context.ongoingOperation.then(function () {\r\n return enqueue(context, fn, instanceID);\r\n });\r\n }\r\n return context.ongoingOperation;\r\n }\r\n\r\n if (!instanceID) {\r\n // Caller wants to enqueue it until database becomes open.\r\n if (db.isOpen()) {\r\n return _enqueue();\r\n } else {\r\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\r\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)\r\n return _enqueue();\r\n } else {\r\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n };\r\n}\r\n","export default function initSaveToUncommittedChanges(db, node) {\r\n return function saveToUncommittedChanges(changes, remoteRevision) {\r\n return db.transaction('rw!', db._uncommittedChanges, () => {\r\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\r\n let changeWithNodeId = {\r\n node: node.id,\r\n type: change.type,\r\n table: change.table,\r\n key: change.key\r\n };\r\n if (change.obj) changeWithNodeId.obj = change.obj;\r\n if (change.mods) changeWithNodeId.mods = change.mods;\r\n return changeWithNodeId;\r\n }));\r\n }).then(() => {\r\n node.appliedRemoteRevision = remoteRevision;\r\n return node.save();\r\n });\r\n };\r\n}\r\n","// Change Types\r\nexport const CREATE = 1;\r\nexport const UPDATE = 2;\r\nexport const DELETE = 3;\r\n","import Dexie from 'dexie';\r\n\r\nexport default function bulkUpdate(table, changes) {\r\n let keys = changes.map(c => c.key);\r\n let map = {};\r\n // Retrieve current object of each change to update and map each\r\n // found object's primary key to the existing object:\r\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\r\n map[cursor.primaryKey+''] = obj;\r\n }).then(()=>{\r\n // Filter away changes whose key wasn't found in the local database\r\n // (we can't update them if we do not know the existing values)\r\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\r\n // Apply modifications onto each existing object (in memory)\r\n // and generate array of resulting objects to put using bulkPut():\r\n let objsToPut = updatesThatApply.map (c => {\r\n let curr = map[c.key+''];\r\n Object.keys(c.mods).forEach(keyPath => {\r\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\r\n });\r\n return curr;\r\n });\r\n return table.bulkPut(objsToPut);\r\n });\r\n}\r\n","import Dexie from 'dexie';\r\nimport { CREATE, DELETE, UPDATE } from './change_types';\r\nimport bulkUpdate from './bulk-update';\r\n\r\nexport default function initApplyChanges(db) {\r\n return function applyChanges(changes) {\r\n let collectedChanges = {};\r\n changes.forEach((change) => {\r\n if (!collectedChanges.hasOwnProperty(change.table)) {\r\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\r\n }\r\n collectedChanges[change.table][change.type].push(change);\r\n });\r\n let table_names = Object.keys(collectedChanges);\r\n let tables = table_names.map((table) => db.table(table));\r\n\r\n return db.transaction(\"rw\", tables, () => {\r\n table_names.forEach((table_name) => {\r\n const table = db.table(table_name);\r\n const specifyKeys = !table.schema.primKey.keyPath;\r\n const createChangesToApply = collectedChanges[table_name][CREATE];\r\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\r\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\r\n if (createChangesToApply.length > 0)\r\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\r\n createChangesToApply.map(c => c.key) : undefined);\r\n if (updateChangesToApply.length > 0)\r\n bulkUpdate(table, updateChangesToApply);\r\n if (deleteChangesToApply.length > 0)\r\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\r\n });\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\nimport initApplyChanges from './apply-changes';\r\n\r\nexport default function initFinallyCommitAllChanges(db, node) {\r\n const applyChanges = initApplyChanges(db);\r\n\r\n return function finallyCommitAllChanges(changes, remoteRevision) {\r\n // 1. Open a write transaction on all tables in DB\r\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\r\n table.name === '_uncommittedChanges' ||\r\n table.schema.observable);\r\n\r\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\r\n var trans = Dexie.currentTransaction;\r\n var localRevisionBeforeChanges = 0;\r\n return db._changes.orderBy('rev').last(function (lastChange) {\r\n // Store what revision we were at before committing the changes\r\n localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0;\r\n }).then(() => {\r\n // Specify the source. Important for the change consumer to ignore changes originated from self!\r\n trans.source = node.id;\r\n // 2. Apply uncommitted changes and delete each uncommitted change\r\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\r\n }).then(function (uncommittedChanges) {\r\n return applyChanges(uncommittedChanges);\r\n }).then(function () {\r\n return db._uncommittedChanges.where('node').equals(node.id).delete();\r\n }).then(function () {\r\n // 3. Apply last chunk of changes\r\n return applyChanges(changes);\r\n }).then(function () {\r\n // Get what revision we are at now:\r\n return db._changes.orderBy('rev').last();\r\n }).then(function (lastChange) {\r\n var currentLocalRevision = (lastChange && lastChange.rev) || 0;\r\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\r\n node.appliedRemoteRevision = remoteRevision;\r\n node.remoteBaseRevisions.push({remote: remoteRevision, local: currentLocalRevision});\r\n if (node.myRevision === localRevisionBeforeChanges) {\r\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\r\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\r\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\r\n node.myRevision = currentLocalRevision;\r\n }\r\n // Garbage collect remoteBaseRevisions not in use anymore:\r\n if (node.remoteBaseRevisions.length > 1) {\r\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\r\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\r\n node.remoteBaseRevisions.splice(0, i);\r\n break;\r\n }\r\n }\r\n }\r\n // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\r\n node.save().catch(err=> {\r\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\r\n });\r\n });\r\n });\r\n };\r\n}\r\n","export default function getBaseRevisionAndMaxClientRevision(node) {\r\n /// \r\n if (node.remoteBaseRevisions.length === 0)\r\n return {\r\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\r\n maxClientRevision: Infinity,\r\n remoteBaseRevision: null\r\n };\r\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\r\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\r\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\r\n return {\r\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\r\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\r\n };\r\n }\r\n }\r\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.\r\n return {\r\n maxClientRevision: node.remoteBaseRevisions[0].local,\r\n remoteBaseRevision: null\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function combineCreateAndUpdate(prevChange, nextChange) {\r\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\r\n Object.keys(nextChange.mods).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\r\n });\r\n return clonedChange;\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function combineUpdateAndUpdate(prevChange, nextChange) {\r\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\r\n Object.keys(nextChange.mods).forEach(function (keyPath) {\r\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\r\n var hadParentPath = false;\r\n Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\r\n Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\r\n hadParentPath = true;\r\n });\r\n if (!hadParentPath) {\r\n // Add or replace this keyPath and its new value\r\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\r\n }\r\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\r\n // we must mimic what would happen if applying the two changes after each other:\r\n Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\r\n delete clonedChange.mods[subPath];\r\n });\r\n });\r\n return clonedChange;\r\n}\r\n","import { CREATE, UPDATE, DELETE } from './change_types';\r\nimport combineCreateAndUpdate from './combine-create-and-update.js';\r\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\r\n\r\nexport default function mergeChange(prevChange, nextChange) {\r\n switch (prevChange.type) {\r\n case CREATE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // Another CREATE replaces previous CREATE.\r\n case UPDATE:\r\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\r\n case DELETE:\r\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!\r\n }\r\n break;\r\n case UPDATE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // Another CREATE replaces previous update.\r\n case UPDATE:\r\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\r\n case DELETE:\r\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\r\n }\r\n break;\r\n case DELETE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // A resurection occurred. Only create change is of interest.\r\n case UPDATE:\r\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\r\n case DELETE:\r\n return prevChange; // Still a delete change. Leave as is.\r\n }\r\n break;\r\n }\r\n}\r\n","import {CREATE, UPDATE} from '../change_types';\r\nimport mergeChange from '../merge-change';\r\n\r\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\r\n return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\r\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.\r\n var changeSet = {};\r\n var numChanges = 0;\r\n var partial = false;\r\n var ignoreSource = node.id;\r\n var nextRevision = revision;\r\n return db.transaction('r', db._changes, function () {\r\n var query = db._changes.where('rev').between(revision, maxRevision, false, true);\r\n return query.until(() => {\r\n if (numChanges === maxChanges) {\r\n partial = true;\r\n return true;\r\n }\r\n }).each(function (change) {\r\n // Note the revision in nextRevision:\r\n nextRevision = change.rev;\r\n // change.source is set based on currentTransaction.source\r\n if (change.source === ignoreSource) return;\r\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info:\r\n var changeToSend = {\r\n type: change.type,\r\n table: change.table,\r\n key: change.key\r\n };\r\n if (change.type === CREATE)\r\n changeToSend.obj = change.obj;\r\n else if (change.type === UPDATE)\r\n changeToSend.mods = change.mods;\r\n\r\n var id = change.table + \":\" + change.key;\r\n var prevChange = changeSet[id];\r\n if (!prevChange) {\r\n // This is the first change on this key. Add it unless it comes from the source that we are working against\r\n changeSet[id] = changeToSend;\r\n ++numChanges;\r\n } else {\r\n // Merge the oldchange with the new change\r\n var nextChange = changeToSend;\r\n var mergedChange = mergeChange(prevChange, nextChange);\r\n changeSet[id] = mergedChange;\r\n }\r\n });\r\n }).then(function () {\r\n var changes = Object.keys(changeSet).map(function (key) {\r\n return changeSet[key];\r\n });\r\n hasMoreToGive.hasMoreToGive = partial;\r\n return cb(changes, partial, {myRevision: nextRevision});\r\n });\r\n };\r\n}\r\n","import {CREATE} from '../change_types';\r\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\r\n\r\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\r\n return function getTableObjectsAsChanges(state, changes, collection) {\r\n /// \r\n /// \r\n /// \r\n var limitReached = false;\r\n return collection.until(function () {\r\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\r\n limitReached = true;\r\n return true;\r\n }\r\n }).each(function (item, cursor) {\r\n changes.push({\r\n type: CREATE,\r\n table: state.currentTable,\r\n key: cursor.key,\r\n obj: cursor.value\r\n });\r\n state.currentKey = cursor.key;\r\n }).then(function () {\r\n if (limitReached) {\r\n // Limit reached. Send partial result.\r\n hasMoreToGive.hasMoreToGive = true;\r\n return cb(changes, null, true, {dbUploadState: state});\r\n } else {\r\n // Done iterating this table. Check if there are more tables to go through:\r\n if (state.tablesToUpload.length === 0) {\r\n // Done iterating all tables\r\n // Now append changes occurred during our dbUpload:\r\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\r\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\r\n changes = changes.concat(additionalChanges);\r\n nodeModificationsOnAck.dbUploadState = null;\r\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\r\n });\r\n } else {\r\n // Not done iterating all tables. Continue on next table:\r\n state.currentTable = state.tablesToUpload.shift();\r\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\r\n }\r\n }\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\r\nimport initGetChangesSinceRevision from './get-changes-since-revision';\r\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\r\n\r\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\r\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\r\n\r\n return function getLocalChangesForNode(node, cb) {\r\n /// \r\n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\r\n /// for that node.\r\n /// \r\n /// \r\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.\r\n\r\n const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\r\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\r\n\r\n // Only a \"remote\" SyncNode created by Dexie.Syncable\r\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\r\n if (node.myRevision >= 0) {\r\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.\r\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\r\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\r\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\r\n });\r\n } else {\r\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.\r\n // Check if we're in the middle of already doing that:\r\n if (node.dbUploadState === null) {\r\n // Initialize dbUploadState\r\n var tablesToUpload = db.tables.filter(function (table) {\r\n return table.schema.observable;\r\n }).map(function (table) {\r\n return table.name;\r\n });\r\n if (tablesToUpload.length === 0) return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all.\r\n var dbUploadState = {\r\n tablesToUpload: tablesToUpload,\r\n currentTable: tablesToUpload.shift(),\r\n currentKey: null\r\n };\r\n return db._changes.orderBy('rev').last(function (lastChange) {\r\n dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0;\r\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\r\n return getTableObjectsAsChanges(dbUploadState, [], collection);\r\n });\r\n } else if (node.dbUploadState.currentKey) {\r\n const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\r\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\r\n } else {\r\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\r\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\r\n }\r\n }\r\n };\r\n}\r\n","export const Statuses = {\r\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\r\n OFFLINE: 0, // The sync provider hasn't yet become online, or it has been disconnected.\r\n CONNECTING: 1, // Trying to connect to server\r\n ONLINE: 2, // Connected to server and currently in sync with server\r\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.\r\n ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect.\r\n};\r\n\r\nexport const StatusTexts = {\r\n \"-1\": \"ERROR\",\r\n \"0\": \"OFFLINE\",\r\n \"1\": \"CONNECTING\",\r\n \"2\": \"ONLINE\",\r\n \"3\": \"SYNCING\",\r\n \"4\": \"ERROR_WILL_RETRY\"\r\n};\r\n","import Dexie from 'dexie';\r\n\r\nimport initEnqueue from './enqueue';\r\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\r\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\r\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\r\nimport {Statuses} from './statuses';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\r\n const enqueue = initEnqueue(db);\r\n var hasMoreToGive = {hasMoreToGive: true};\r\n\r\n function stillAlive() {\r\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\r\n // because the new instance should be considered a fresh instance and will have another local node.\r\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\r\n }\r\n\r\n return function connectProtocol(node, activePeer) {\r\n /// \r\n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\r\n\r\n const url = activePeer.url;\r\n\r\n function changeStatusTo(newStatus) {\r\n if (node.status !== newStatus) {\r\n node.status = newStatus;\r\n node.save().then(()=> {\r\n db.syncable.on.statusChanged.fire(newStatus, url);\r\n // Also broadcast message to other nodes about the status\r\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\r\n }).catch('DatabaseClosedError', ()=> {\r\n });\r\n }\r\n }\r\n\r\n activePeer.on('disconnect', function (newStatus) {\r\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\r\n });\r\n\r\n var connectedContinuation;\r\n changeStatusTo(Statuses.CONNECTING);\r\n return doSync();\r\n\r\n function doSync() {\r\n // Use enqueue() to ensure only a single promise execution at a time.\r\n return enqueue(doSync, function () {\r\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\r\n return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider);\r\n }, dbAliveID);\r\n }\r\n\r\n function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\r\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\r\n var finalSyncPromise = new Promise(function (resolve, reject) {\r\n rejectConnectPromise.p = function (err) {\r\n reject(err);\r\n };\r\n Dexie.asap(function () {\r\n try {\r\n protocolInstance.sync(\r\n node.syncContext,\r\n url,\r\n options,\r\n remoteBaseRevision,\r\n node.appliedRemoteRevision,\r\n changes,\r\n partial,\r\n applyRemoteChanges,\r\n onChangesAccepted,\r\n function (continuation) {\r\n resolve(continuation);\r\n },\r\n onError);\r\n } catch (ex) {\r\n onError(ex, Infinity);\r\n }\r\n\r\n function onError(error, again) {\r\n reject(error);\r\n if (stillAlive()) {\r\n if (!isNaN(again) && again < Infinity) {\r\n setTimeout(function () {\r\n if (stillAlive()) {\r\n changeStatusTo(Statuses.SYNCING);\r\n doSync().catch('DatabaseClosedError', abortTheProvider);\r\n }\r\n }, again);\r\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\r\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\r\n connectedContinuation = null;\r\n } else {\r\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\r\n }\r\n }\r\n }\r\n });\r\n });\r\n\r\n return finalSyncPromise.then(function () {\r\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\r\n return undefined;\r\n }).finally(()=> {\r\n // In case error happens after connect, don't try reject the connect promise anymore.\r\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\r\n // is active and this happens. It would fire unhandledrejection but that we do not want.\r\n rejectConnectPromise.p = null;\r\n });\r\n\r\n function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\r\n // otherwise it will execute when finalSyncPromise resolves.\r\n finalSyncPromise.then(continueSendingChanges);\r\n return node.save();\r\n }\r\n }\r\n\r\n function abortTheProvider(error) {\r\n activePeer.disconnect(Statuses.ERROR, error);\r\n }\r\n\r\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\r\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n return getLocalChangesForNode(node, autoAck);\r\n } else {\r\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\r\n }\r\n });\r\n }\r\n\r\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\r\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\r\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\r\n\r\n return enqueue(applyRemoteChanges, function () {\r\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\r\n // FIXTHIS: Check what to do if clear() is true!\r\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\r\n .catch(function (error) {\r\n abortTheProvider(error);\r\n return Promise.reject(error);\r\n });\r\n }, dbAliveID);\r\n }\r\n\r\n //\r\n //\r\n // Continuation Patterns Follows\r\n //\r\n //\r\n\r\n function continueSendingChanges(continuation) {\r\n if (!stillAlive()) { // Database was closed.\r\n if (continuation.disconnect)\r\n continuation.disconnect();\r\n return;\r\n }\r\n\r\n connectedContinuation = continuation;\r\n activePeer.on('disconnect', function () {\r\n if (connectedContinuation) {\r\n if (connectedContinuation.react) {\r\n try {\r\n // react pattern must provide a disconnect function.\r\n connectedContinuation.disconnect();\r\n } catch (e) {\r\n }\r\n }\r\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\r\n }\r\n });\r\n\r\n if (continuation.react) {\r\n continueUsingReactPattern(continuation);\r\n } else {\r\n continueUsingPollPattern(continuation);\r\n }\r\n }\r\n\r\n // React Pattern (eager)\r\n function continueUsingReactPattern(continuation) {\r\n var changesWaiting, // Boolean\r\n isWaitingForServer; // Boolean\r\n\r\n\r\n function onChanges() {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n if (isWaitingForServer)\r\n changesWaiting = true;\r\n else {\r\n reactToChanges();\r\n }\r\n }\r\n }\r\n\r\n db.on('changes', onChanges);\r\n\r\n activePeer.on('disconnect', function () {\r\n db.on.changes.unsubscribe(onChanges);\r\n });\r\n\r\n function reactToChanges() {\r\n if (!connectedContinuation) return;\r\n changesWaiting = false;\r\n isWaitingForServer = true;\r\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n if (!connectedContinuation) return;\r\n if (changes.length > 0) {\r\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n // More changes may be waiting:\r\n reactToChanges();\r\n });\r\n } else {\r\n isWaitingForServer = false;\r\n if (changesWaiting) {\r\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\r\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\r\n reactToChanges();\r\n } else {\r\n changeStatusTo(Statuses.ONLINE);\r\n }\r\n }\r\n }).catch(ex => {\r\n console.error(`Got ${ex.message} caught by reactToChanges`);\r\n abortTheProvider(ex);\r\n });\r\n }\r\n\r\n reactToChanges();\r\n }\r\n\r\n // Poll Pattern\r\n function continueUsingPollPattern() {\r\n\r\n function syncAgain() {\r\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n\r\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\r\n\r\n function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n }\r\n\r\n function onSuccess(continuation) {\r\n if (!connectedContinuation) {\r\n // Got disconnected before succeeding. Quit.\r\n return;\r\n }\r\n connectedContinuation = continuation;\r\n if (partial) {\r\n // We only sent partial changes. Need to do another round asap.\r\n syncAgain();\r\n } else {\r\n // We've sent all changes now (in sync!)\r\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\r\n // Provider wants to keep polling. Set Status to ONLINE.\r\n changeStatusTo(Statuses.ONLINE);\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, continuation.again);\r\n } else {\r\n // Provider seems finished polling. Since we are never going to poll again,\r\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\r\n activePeer.disconnect(Statuses.OFFLINE);\r\n }\r\n }\r\n }\r\n\r\n function onError(error, again) {\r\n if (!isNaN(again) && again < Infinity) {\r\n if (connectedContinuation) {\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, again);\r\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\r\n } // else status is already changed since we got disconnected.\r\n } else {\r\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\r\n }\r\n }\r\n }).catch(abortTheProvider);\r\n }\r\n\r\n if (hasMoreToGive.hasMoreToGive) {\r\n syncAgain();\r\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\r\n changeStatusTo(Statuses.ONLINE);\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, connectedContinuation.again);\r\n } else {\r\n // Provider seems finished polling. Since we are never going to poll again,\r\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\r\n activePeer.disconnect(Statuses.OFFLINE);\r\n }\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\r\nimport initConnectProtocol from './connect-protocol';\r\nimport {Statuses} from './statuses';\r\n\r\nexport default function initConnectFn(db, activePeers) {\r\n return function connect(protocolInstance, protocolName, url, options, dbAliveID) {\r\n /// \r\n var existingPeer = activePeers.filter(function (peer) {\r\n return peer.url === url;\r\n });\r\n if (existingPeer.length > 0) {\r\n const activePeer = existingPeer[0];\r\n const diffObject = {};\r\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\r\n // Options have been changed\r\n // We need to disconnect and reconnect\r\n if (Object.keys(diffObject).length !== 0) {\r\n return db.syncable.disconnect(url)\r\n .then(() => {\r\n return execConnect();\r\n })\r\n } else {\r\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\r\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.\r\n return existingPeer[0].connectPromise;\r\n }\r\n }\r\n\r\n function execConnect() {\r\n // Use an object otherwise we wouldn't be able to get the reject promise from\r\n // connectProtocol\r\n var rejectConnectPromise = {p: null};\r\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\r\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\r\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\r\n return connectProtocol(node, activePeer);\r\n });\r\n\r\n var disconnected = false;\r\n var activePeer = {\r\n url: url,\r\n status: Statuses.OFFLINE,\r\n connectPromise: connectPromise,\r\n syncOptions: options,\r\n on: Dexie.Events(null, \"disconnect\"),\r\n disconnect: function (newStatus, error) {\r\n var pos = activePeers.indexOf(activePeer);\r\n if (pos >= 0) activePeers.splice(pos, 1);\r\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\r\n if (!disconnected) {\r\n activePeer.on.disconnect.fire(newStatus, error);\r\n }\r\n disconnected = true;\r\n }\r\n };\r\n activePeers.push(activePeer);\r\n\r\n return connectPromise;\r\n }\r\n\r\n return execConnect();\r\n };\r\n}\r\n","/* ========================================================================== \r\n * dexie-syncable.js\r\n * ==========================================================================\r\n *\r\n * Dexie addon for syncing indexedDB with remote endpoints.\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com,\r\n * Nikolas Poniros, https://github.com/nponiros\r\n *\r\n * ==========================================================================\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n * \r\n */\r\n\r\nimport Dexie from \"dexie\";\r\n// Depend on 'dexie-observable'\r\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\r\n// That way, our plugin works in all UMD cases.\r\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\r\nimport \"dexie-observable\";\r\n\r\nimport initSyncableConnect from './syncable-connect';\r\nimport initConnectFn from './connect-fn';\r\nimport {Statuses, StatusTexts} from './statuses';\r\n\r\nvar override = Dexie.override,\r\n Promise = Dexie.Promise,\r\n Observable = Dexie.Observable;\r\n\r\nexport default function Syncable (db) {\r\n /// \r\n\r\n var activePeers = [];\r\n\r\n const connectFn = initConnectFn(db, activePeers);\r\n const syncableConnect = initSyncableConnect(db, connectFn);\r\n\r\n db.on('message', function(msg) {\r\n // Message from other local node arrives...\r\n Dexie.vip(function() {\r\n if (msg.type === 'connect') {\r\n // We are master node and another non-master node wants us to do the connect.\r\n db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\r\n } else if (msg.type === 'disconnect') {\r\n db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject);\r\n } else if (msg.type === 'syncStatusChanged') {\r\n // We are client and a master node informs us about syncStatus change.\r\n // Lookup the connectedProvider and call its event\r\n db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url);\r\n }\r\n });\r\n });\r\n\r\n db.on('cleanup', function(weBecameMaster) {\r\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\r\n if (weBecameMaster) {\r\n // We took over the master role in Observable's cleanup method.\r\n // We should connect to remote servers now.\r\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\r\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\r\n // connection has been closed. The new master would then be expected to reconnect.\r\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\r\n // an old closed one. \r\n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\r\n return db._syncNodes.where({type: 'remote'})\r\n .filter(node => node.status !== Statuses.OFFLINE)\r\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \r\n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\r\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\r\n })\r\n )));\r\n })).catch('DatabaseClosedError', ()=>{});\r\n }\r\n });\r\n\r\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\r\n // when the database opens. It will not wait for the connection to complete, just initiate the\r\n // connection so that it will continue syncing as long as the database is open.\r\n\r\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\r\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\r\n db.on('ready', function onReady() {\r\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\r\n if (db._localSyncNode && db._localSyncNode.isMaster) {\r\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\r\n // This \"ready\" subscriber will never be the one performing the initial sync request, because\r\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\r\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\r\n // called after this one. There, in that subscriber, the initial sync request will take place\r\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\r\n // next time this database is opened.\r\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\r\n // once in the past for each \"connectedRemoteNode\" we find in query below.\r\n\r\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\r\n db._syncNodes\r\n .where('type').equals('remote')\r\n .and(node => node.status !== Statuses.OFFLINE)\r\n .toArray(connectedRemoteNodes => {\r\n // There are connected remote nodes that we must manage (or take over to manage)\r\n connectedRemoteNodes.forEach(\r\n node => db.syncable.connect(\r\n node.syncProtocol,\r\n node.url,\r\n node.syncOptions) \r\n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\r\n );\r\n }).catch('DatabaseClosedError', ()=>{});\r\n }\r\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\r\n\r\n db.syncable = {};\r\n\r\n db.syncable.getStatus = function(url, cb) {\r\n if (db.isOpen()) {\r\n return Dexie.vip(function() {\r\n return db._syncNodes.where('url').equals(url).first(function(node) {\r\n return node ? node.status : Statuses.OFFLINE;\r\n });\r\n }).then(cb);\r\n } else {\r\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\r\n }\r\n };\r\n\r\n db.syncable.getOptions = function(url, cb) {\r\n return db.transaction('r?', db._syncNodes, () => {\r\n return db._syncNodes.where('url').equals(url).first(function(node) {\r\n return node.syncOptions;\r\n }).then(cb);\r\n });\r\n };\r\n\r\n db.syncable.list = function() {\r\n return db.transaction('r?', db._syncNodes, ()=>{\r\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\r\n return a.map(function(node) { return node.url; });\r\n });\r\n });\r\n };\r\n\r\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\r\n\r\n db.syncable.disconnect = function(url) {\r\n return Dexie.ignoreTransaction(()=>{\r\n return Promise.resolve().then(()=>{\r\n if (db._localSyncNode && db._localSyncNode.isMaster) {\r\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\r\n return peer.disconnect(Statuses.OFFLINE);\r\n }));\r\n } else {\r\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\r\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\r\n });\r\n }\r\n }).then(()=>{\r\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\r\n node.status = Statuses.OFFLINE;\r\n });\r\n });\r\n });\r\n };\r\n\r\n db.syncable.connect = function(protocolName, url, options) {\r\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.\r\n var protocolInstance = Syncable.registeredProtocols[protocolName];\r\n if (protocolInstance) {\r\n return syncableConnect(protocolInstance, protocolName, url, options);\r\n } else {\r\n return Promise.reject(\r\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\r\n );\r\n }\r\n };\r\n\r\n db.syncable.delete = function(url) {\r\n return db.syncable.disconnect(url).then(()=>{\r\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\r\n // Find the node(s)\r\n // Several can be found, as detected by @martindiphoorn,\r\n // let's delete them and cleanup _uncommittedChanges and _changes \r\n // accordingly.\r\n let nodeIDsToDelete;\r\n return db._syncNodes\r\n .where(\"url\").equals(url)\r\n .toArray(nodes => nodes.map(node => node.id))\r\n .then(nodeIDs => {\r\n nodeIDsToDelete = nodeIDs;\r\n // Delete the syncNode that represents the remote endpoint.\r\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\r\n })\r\n .then (() =>\r\n // In case there were uncommittedChanges belonging to this, delete them as well\r\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\r\n }).then(()=> {\r\n // Spawn background job to delete old changes, now that a node has been deleted,\r\n // there might be changes in _changes table that is not needed to keep anymore.\r\n // This is done in its own transaction, or possible several transaction to prohibit\r\n // starvation\r\n Observable.deleteOldChanges(db);\r\n });\r\n });\r\n };\r\n\r\n db.syncable.unsyncedChanges = function(url) {\r\n return db._syncNodes.where(\"url\").equals(url).first(function(node) {\r\n return db._changes.where('rev').above(node.myRevision).toArray();\r\n });\r\n };\r\n\r\n db.close = override(db.close, function(origClose) {\r\n return function() {\r\n activePeers.forEach(function(peer) {\r\n peer.disconnect();\r\n });\r\n return origClose.apply(this, arguments);\r\n };\r\n });\r\n\r\n Object.defineProperty(\r\n db.observable.SyncNode.prototype,\r\n 'save', {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value() {\r\n return db.transaction('rw?', db._syncNodes, () => {\r\n return db._syncNodes.put(this);\r\n });\r\n }\r\n });\r\n}\r\n\r\nSyncable.Statuses = Statuses;\r\n\r\nSyncable.StatusTexts = StatusTexts;\r\n\r\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\r\n\r\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\r\n /// \r\n /// Register a synchronization protocol that can synchronize databases with remote servers.\r\n /// \r\n /// Provider name\r\n /// Implementation of ISyncProtocol\r\n const partialsThreshold = protocolInstance.partialsThreshold;\r\n if (typeof partialsThreshold === 'number') {\r\n // Don't allow NaN or negative threshold\r\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\r\n throw new Error('The given number for the threshold is not supported');\r\n }\r\n // If the threshold is 0 we will not send any client changes but will get server changes\r\n } else {\r\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\r\n protocolInstance.partialsThreshold = Infinity;\r\n }\r\n Syncable.registeredProtocols[name] = protocolInstance;\r\n};\r\n\r\n// Register addon in Dexie:\r\nDexie.Syncable = Syncable;\r\nDexie.addons.push(Syncable);\r\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAMA,SAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AAE9B,6BAA4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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..ce60551fb --- /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})})}if(n.hasBeenClosed())return N.reject(new e.DatabaseClosedError);if(n.hasFailed())return N.reject(new e.InvalidStateError("Dexie.Syncable: Cannot connect. Database has failed to open"));var a=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);return a.then(t,r),e&&e.appliedRemoteRevision?void 0:a})}),n.open()["catch"](function(n){r(new e.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open",n))})});return a}}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(){return i.initialUpload===!1?n._changes.toCollection().lastKey(function(e){c.myRevision=e}):void 0}()).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)}):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:return e;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(){var n=e._changes.where("rev").between(r,i,!1,!0);return n.until(function(){return s===o?(u=!0,!0):void 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(){return s.length===t?(f=!0,!0):void 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 p(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)&&1/0>n?(setTimeout(function(){u()&&(y(E.SYNCING),h()["catch"]("DatabaseClosedError",m))},n),y(E.ERROR_WILL_RETRY,e),S&&S.disconnect&&S.disconnect(),S=null):m(e))}try{t.sync(o.syncContext,_,c,r,o.appliedRemoteRevision,n,i,N,l,function(e){s(e)},e)}catch(a){e(a,1/0)}})});return f.then(function(){return void 0})["finally"](function(){a.p=null})}function m(e){d.disconnect(E.ERROR,e)}function p(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 m(e),C.reject(e)}):C.reject(new e.DatabaseClosedError)},r)}function g(e){return u()?(S=e,d.on("disconnect",function(){if(S){if(S.react)try{S.disconnect()}catch(e){}S=null}}),void(e.react?R(e):O(e))):void(e.disconnect&&e.disconnect())}function R(t){function r(){S&&(y(E.SYNCING),a?c=!0:i())}function i(){S&&(c=!1,a=!0,p(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"),m(e)}))}var c,a;n.on("changes",r),d.on("disconnect",function(){n.on.changes.unsubscribe(r)}),i()}function O(){function n(){p(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)&&1/0>t?S&&(setTimeout(function(){S&&(y(E.SYNCING),n())},t),y(E.ERROR_WILL_RETRY)):m(e)}t.sync(o.syncContext,_,c,i,o.appliedRemoteRevision,r,a,N,u,l,f)})["catch"](m)}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 m(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 p(t){var r=[],o=m(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(p.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=p.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 p.Statuses=E,p.StatusTexts=w,p.registeredProtocols={},p.registerSyncProtocol=function(e,n){var t=n.partialsThreshold;if("number"==typeof t){if(isNaN(t)||0>t)throw new Error("The given number for the threshold is not supported")}else n.partialsThreshold=1/0;p.registeredProtocols[e]=n},e.Syncable=p,e.addons.push(p),p}); +//# 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..29bca7c32 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.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"],"names":["Promise","initSyncableConnect","db","connect","protocolInstance","protocolName","url","options","isOpen","_localSyncNode","Error","isMaster","id","table","where","above","first","masterNode","observable","sendMessage","wantReply","hasBeenClosed","reject","Dexie","DatabaseClosedError","hasFailed","InvalidStateError","promise","resolve","on","_syncNodes","get","node","connectPromise","syncable","then","appliedRemoteRevision","open","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","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","currentLocalRevision","remote","local","i","splice","err","console","warn","stack","maxClientRevision","remoteBaseRevision","prevChange","nextChange","clonedChange","deepClone","hadParentPath","parentPath","indexOf","substr","subPath","combineCreateAndUpdate","combineUpdateAndUpdate","hasMoreToGive","revision","maxChanges","maxRevision","cb","changeSet","numChanges","partial","ignoreSource","nextRevision","query","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,SAAAC,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/Bd,aAAcA,EACdC,IAAKA,EACLC,QAASA,GACRU,EAAWL,IAAKQ,WAAW,MAG7B,GAAIlB,EAAGmB,gBAEZ,MAAOrB,GAAQsB,OAAO,GAAIC,GAAMC,oBAC3B,IAAItB,EAAGuB,YAEZ,MAAOzB,GAAQsB,OAAO,GAAIC,GAAMG,kBAC5B,+DAIJ,IAAIC,GAAU,GAAI3B,GAAQ,SAAU4B,EAASN,GAC3CpB,EAAG2B,GAAG,QAAS,WAIb,MAAO3B,GAAG4B,WAAWC,KAAKzB,IAAGA,GAAG,SAAA0B,GAI9B,GAAIC,GAAiB/B,EAAGgC,SAAS/B,QAAQE,EAAcC,EAAKC,EAG5D,OAFA0B,GAAeE,KAAKP,EAASN,GAEzBU,GAAQA,EAAKI,sBAAjB,OAaOH,MAIX/B,EAAGmC,OAAHnC,SAAgB,SAAAoC,GAGdhB,EAAO,GAAIC,GAAMG,kBACb,4DACAY,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;;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","sourcesContent":["import Dexie from 'dexie';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initSyncableConnect(db, connect) {\r\n return function syncableConnect(protocolInstance, protocolName, url, options) {\r\n if (db.isOpen()) {\r\n // Database is open\r\n if (!db._localSyncNode)\r\n throw new Error(\"Precondition failed: local sync node is missing. Make sure Dexie.Observable is active!\");\r\n\r\n if (db._localSyncNode.isMaster) {\r\n // We are master node\r\n return connect(protocolInstance, protocolName, url, options, db._localSyncNode.id);\r\n } else {\r\n // We are not master node\r\n // Request master node to do the connect:\r\n return db.table('_syncNodes').where('isMaster').above(0).first(function (masterNode) {\r\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.\r\n return db.observable.sendMessage('connect', {\r\n protocolName: protocolName,\r\n url: url,\r\n options: options\r\n }, masterNode.id, {wantReply: true});\r\n });\r\n }\r\n } else if (db.hasBeenClosed()) {\r\n // Database has been closed.\r\n return Promise.reject(new Dexie.DatabaseClosedError());\r\n } else if (db.hasFailed()) {\r\n // Database has failed to open\r\n return Promise.reject(new Dexie.InvalidStateError(\r\n \"Dexie.Syncable: Cannot connect. Database has failed to open\"));\r\n } else {\r\n // Database not yet open. It may be on its way to open, or open() hasn't yet been called.\r\n // Wait for it to open, then connect.\r\n var promise = new Promise(function (resolve, reject) {\r\n db.on(\"ready\", () => {\r\n // First, check if this is the very first time we connect to given URL.\r\n // Need to know, because if it is, we should stall the promise returned to\r\n // db.on('ready') to not be fulfilled until the initial sync has succeeded.\r\n return db._syncNodes.get({url}, node => {\r\n // Ok, now we know whether we should await the connect promise or not.\r\n // No matter, we should now connect (will maybe create the SyncNode instance\r\n // representing the given URL)\r\n let connectPromise = db.syncable.connect(protocolName, url, options);\r\n connectPromise.then(resolve, reject);// Resolve the returned promise when connected.\r\n // Ok, so let's see if we should suspend DB queries until connected or not:\r\n if (node && node.appliedRemoteRevision) {\r\n // The very first initial sync has been done so we need not wait\r\n // for the connect promise to complete. It can continue in background.\r\n // Returning here will resume db.on('ready') and resume all queries that\r\n // the application has put to the database.\r\n return;\r\n }\r\n // This was the very first time we connect to the remote server,\r\n // we must make sure that the initial sync request succeeeds before resuming\r\n // database queries that the application code puts onto the database.\r\n // If OFFLINE or other error, don't allow the application to proceed.\r\n // We are assuming that an initial sync is essential for the application to\r\n // function correctly.\r\n return connectPromise;\r\n });\r\n });\r\n // Force open() to happen. Otherwise connect() may stall forever.\r\n db.open().catch(ex => {\r\n // If open fails, db.on('ready') may not have been called and we must\r\n // reject promise with InvalidStateError\r\n reject(new Dexie.InvalidStateError(\r\n `Dexie.Syncable: Couldn't connect. Database failed to open`,\r\n ex\r\n ));\r\n });\r\n });\r\n return promise;\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initPersistedContext(node) {\r\n //\r\n // PersistedContext : IPersistedContext\r\n //\r\n return class PersistedContext {\r\n constructor(nodeID, otherProps) {\r\n this.nodeID = nodeID;\r\n if (otherProps) Dexie.extend(this, otherProps);\r\n }\r\n\r\n save() {\r\n // Store this instance in the syncContext property of the node it belongs to.\r\n return Dexie.vip(() => {\r\n return node.save();\r\n });\r\n }\r\n }\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport initPersistedContext from './PersistedContext';\r\n\r\nexport default function initGetOrCreateSyncNode(db, protocolName, url) {\r\n return function getOrCreateSyncNode(options) {\r\n return db.transaction('rw', db._syncNodes, db._changes, function () {\r\n if (!url) throw new Error(\"Url cannot be empty\");\r\n\r\n // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise.\r\n return db._syncNodes.where(\"url\").equalsIgnoreCase(url).first(function (node) {\r\n // If we found a node it will be instanceof SyncNode as Dexie.Observable\r\n // maps to class\r\n if (node) {\r\n const PersistedContext = initPersistedContext(node);\r\n // Node already there. Make syncContext become an instance of PersistedContext:\r\n node.syncContext = new PersistedContext(node.id, node.syncContext);\r\n node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen...\r\n node.syncOptions = options; // Options could have been changed\r\n db._syncNodes.put(node);\r\n } else {\r\n // Create new node and sync everything\r\n node = new db.observable.SyncNode();\r\n node.myRevision = -1;\r\n node.appliedRemoteRevision = null;\r\n node.remoteBaseRevisions = [];\r\n node.type = \"remote\";\r\n node.syncProtocol = protocolName;\r\n node.url = url;\r\n node.syncOptions = options;\r\n node.lastHeartBeat = Date.now();\r\n node.dbUploadState = null;\r\n const PersistedContext = initPersistedContext(node);\r\n Dexie.Promise.resolve(function () {\r\n // If options.initialUpload is explicitely false, set myRevision to currentRevision.\r\n if (options.initialUpload === false)\r\n return db._changes.toCollection().lastKey(function (currentRevision) {\r\n node.myRevision = currentRevision;\r\n });\r\n }()).then(function () {\r\n db._syncNodes.add(node).then(function (nodeID) {\r\n node.syncContext = new PersistedContext(nodeID); // Update syncContext in db with correct nodeId.\r\n db._syncNodes.put(node);\r\n });\r\n });\r\n }\r\n\r\n return node; // returning node will make the db.transaction()-promise resolve with this value.\r\n });\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function initEnqueue(db) {\r\n return function enqueue(context, fn, instanceID) {\r\n function _enqueue() {\r\n if (!context.ongoingOperation) {\r\n context.ongoingOperation = Dexie.ignoreTransaction(function () {\r\n return Dexie.vip(function () {\r\n return fn();\r\n });\r\n }).finally(()=> {\r\n delete context.ongoingOperation;\r\n });\r\n } else {\r\n context.ongoingOperation = context.ongoingOperation.then(function () {\r\n return enqueue(context, fn, instanceID);\r\n });\r\n }\r\n return context.ongoingOperation;\r\n }\r\n\r\n if (!instanceID) {\r\n // Caller wants to enqueue it until database becomes open.\r\n if (db.isOpen()) {\r\n return _enqueue();\r\n } else {\r\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n } else if (db._localSyncNode && instanceID === db._localSyncNode.id) {\r\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)\r\n return _enqueue();\r\n } else {\r\n return Dexie.Promise.reject(new Dexie.DatabaseClosedError());\r\n }\r\n };\r\n}\r\n","export default function initSaveToUncommittedChanges(db, node) {\r\n return function saveToUncommittedChanges(changes, remoteRevision) {\r\n return db.transaction('rw!', db._uncommittedChanges, () => {\r\n return db._uncommittedChanges.bulkAdd(changes.map(change => {\r\n let changeWithNodeId = {\r\n node: node.id,\r\n type: change.type,\r\n table: change.table,\r\n key: change.key\r\n };\r\n if (change.obj) changeWithNodeId.obj = change.obj;\r\n if (change.mods) changeWithNodeId.mods = change.mods;\r\n return changeWithNodeId;\r\n }));\r\n }).then(() => {\r\n node.appliedRemoteRevision = remoteRevision;\r\n return node.save();\r\n });\r\n };\r\n}\r\n","// Change Types\r\nexport const CREATE = 1;\r\nexport const UPDATE = 2;\r\nexport const DELETE = 3;\r\n","import Dexie from 'dexie';\r\n\r\nexport default function bulkUpdate(table, changes) {\r\n let keys = changes.map(c => c.key);\r\n let map = {};\r\n // Retrieve current object of each change to update and map each\r\n // found object's primary key to the existing object:\r\n return table.where(':id').anyOf(keys).raw().each((obj, cursor) => {\r\n map[cursor.primaryKey+''] = obj;\r\n }).then(()=>{\r\n // Filter away changes whose key wasn't found in the local database\r\n // (we can't update them if we do not know the existing values)\r\n let updatesThatApply = changes.filter(c => map.hasOwnProperty(c.key+''));\r\n // Apply modifications onto each existing object (in memory)\r\n // and generate array of resulting objects to put using bulkPut():\r\n let objsToPut = updatesThatApply.map (c => {\r\n let curr = map[c.key+''];\r\n Object.keys(c.mods).forEach(keyPath => {\r\n Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]);\r\n });\r\n return curr;\r\n });\r\n return table.bulkPut(objsToPut);\r\n });\r\n}\r\n","import Dexie from 'dexie';\r\nimport { CREATE, DELETE, UPDATE } from './change_types';\r\nimport bulkUpdate from './bulk-update';\r\n\r\nexport default function initApplyChanges(db) {\r\n return function applyChanges(changes) {\r\n let collectedChanges = {};\r\n changes.forEach((change) => {\r\n if (!collectedChanges.hasOwnProperty(change.table)) {\r\n collectedChanges[change.table] = { [CREATE]: [], [DELETE]: [], [UPDATE]: [] };\r\n }\r\n collectedChanges[change.table][change.type].push(change);\r\n });\r\n let table_names = Object.keys(collectedChanges);\r\n let tables = table_names.map((table) => db.table(table));\r\n\r\n return db.transaction(\"rw\", tables, () => {\r\n table_names.forEach((table_name) => {\r\n const table = db.table(table_name);\r\n const specifyKeys = !table.schema.primKey.keyPath;\r\n const createChangesToApply = collectedChanges[table_name][CREATE];\r\n const deleteChangesToApply = collectedChanges[table_name][DELETE];\r\n const updateChangesToApply = collectedChanges[table_name][UPDATE];\r\n if (createChangesToApply.length > 0)\r\n table.bulkPut(createChangesToApply.map(c => c.obj), specifyKeys ?\r\n createChangesToApply.map(c => c.key) : undefined);\r\n if (updateChangesToApply.length > 0)\r\n bulkUpdate(table, updateChangesToApply);\r\n if (deleteChangesToApply.length > 0)\r\n table.bulkDelete(deleteChangesToApply.map(c => c.key));\r\n });\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\nimport initApplyChanges from './apply-changes';\r\n\r\nexport default function initFinallyCommitAllChanges(db, node) {\r\n const applyChanges = initApplyChanges(db);\r\n\r\n return function finallyCommitAllChanges(changes, remoteRevision) {\r\n // 1. Open a write transaction on all tables in DB\r\n const tablesToIncludeInTrans = db.tables.filter(table => table.name === '_changes' ||\r\n table.name === '_uncommittedChanges' ||\r\n table.schema.observable);\r\n\r\n return db.transaction('rw!', tablesToIncludeInTrans, () => {\r\n var trans = Dexie.currentTransaction;\r\n var localRevisionBeforeChanges = 0;\r\n return db._changes.orderBy('rev').last(function (lastChange) {\r\n // Store what revision we were at before committing the changes\r\n localRevisionBeforeChanges = (lastChange && lastChange.rev) || 0;\r\n }).then(() => {\r\n // Specify the source. Important for the change consumer to ignore changes originated from self!\r\n trans.source = node.id;\r\n // 2. Apply uncommitted changes and delete each uncommitted change\r\n return db._uncommittedChanges.where('node').equals(node.id).toArray();\r\n }).then(function (uncommittedChanges) {\r\n return applyChanges(uncommittedChanges);\r\n }).then(function () {\r\n return db._uncommittedChanges.where('node').equals(node.id).delete();\r\n }).then(function () {\r\n // 3. Apply last chunk of changes\r\n return applyChanges(changes);\r\n }).then(function () {\r\n // Get what revision we are at now:\r\n return db._changes.orderBy('rev').last();\r\n }).then(function (lastChange) {\r\n var currentLocalRevision = (lastChange && lastChange.rev) || 0;\r\n // 4. Update node states (appliedRemoteRevision, remoteBaseRevisions and eventually myRevision)\r\n node.appliedRemoteRevision = remoteRevision;\r\n node.remoteBaseRevisions.push({remote: remoteRevision, local: currentLocalRevision});\r\n if (node.myRevision === localRevisionBeforeChanges) {\r\n // If server was up-to-date before we added new changes from the server, update myRevision to last change\r\n // because server is still up-to-date! This is also important in order to prohibit getLocalChangesForNode() from\r\n // ever sending an empty change list to server, which would otherwise be done every second time it would send changes.\r\n node.myRevision = currentLocalRevision;\r\n }\r\n // Garbage collect remoteBaseRevisions not in use anymore:\r\n if (node.remoteBaseRevisions.length > 1) {\r\n for (var i = node.remoteBaseRevisions.length - 1; i > 0; --i) {\r\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\r\n node.remoteBaseRevisions.splice(0, i);\r\n break;\r\n }\r\n }\r\n }\r\n // We are not including _syncNodes in transaction, so this save() call will execute in its own transaction.\r\n node.save().catch(err=> {\r\n console.warn(\"Dexie.Syncable: Unable to save SyncNode after applying remote changes: \" + (err.stack || err));\r\n });\r\n });\r\n });\r\n };\r\n}\r\n","export default function getBaseRevisionAndMaxClientRevision(node) {\r\n /// \r\n if (node.remoteBaseRevisions.length === 0)\r\n return {\r\n // No remoteBaseRevisions have arrived yet. No limit on clientRevision and provide null as remoteBaseRevision:\r\n maxClientRevision: Infinity,\r\n remoteBaseRevision: null\r\n };\r\n for (var i = node.remoteBaseRevisions.length - 1; i >= 0; --i) {\r\n if (node.myRevision >= node.remoteBaseRevisions[i].local) {\r\n // Found a remoteBaseRevision that fits node.myRevision. Return remoteBaseRevision and eventually a roof maxClientRevision pointing out where next remoteBaseRevision bases its changes on.\r\n return {\r\n maxClientRevision: i === node.remoteBaseRevisions.length - 1 ? Infinity : node.remoteBaseRevisions[i + 1].local,\r\n remoteBaseRevision: node.remoteBaseRevisions[i].remote\r\n };\r\n }\r\n }\r\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.\r\n return {\r\n maxClientRevision: node.remoteBaseRevisions[0].local,\r\n remoteBaseRevision: null\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function combineCreateAndUpdate(prevChange, nextChange) {\r\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\r\n Object.keys(nextChange.mods).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]);\r\n });\r\n return clonedChange;\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nexport default function combineUpdateAndUpdate(prevChange, nextChange) {\r\n var clonedChange = Dexie.deepClone(prevChange); // Clone object before modifying since the earlier change in db.changes[] would otherwise be altered.\r\n Object.keys(nextChange.mods).forEach(function (keyPath) {\r\n // If prev-change was changing a parent path of this keyPath, we must update the parent path rather than adding this keyPath\r\n var hadParentPath = false;\r\n Object.keys(prevChange.mods).filter(function (parentPath) { return keyPath.indexOf(parentPath + '.') === 0; }).forEach(function (parentPath) {\r\n Dexie.setByKeyPath(clonedChange.mods[parentPath], keyPath.substr(parentPath.length + 1), nextChange.mods[keyPath]);\r\n hadParentPath = true;\r\n });\r\n if (!hadParentPath) {\r\n // Add or replace this keyPath and its new value\r\n clonedChange.mods[keyPath] = nextChange.mods[keyPath];\r\n }\r\n // In case prevChange contained sub-paths to the new keyPath, we must make sure that those sub-paths are removed since\r\n // we must mimic what would happen if applying the two changes after each other:\r\n Object.keys(prevChange.mods).filter(function (subPath) { return subPath.indexOf(keyPath + '.') === 0; }).forEach(function (subPath) {\r\n delete clonedChange.mods[subPath];\r\n });\r\n });\r\n return clonedChange;\r\n}\r\n","import { CREATE, UPDATE, DELETE } from './change_types';\r\nimport combineCreateAndUpdate from './combine-create-and-update.js';\r\nimport combineUpdateAndUpdate from './combine-update-and-update.js';\r\n\r\nexport default function mergeChange(prevChange, nextChange) {\r\n switch (prevChange.type) {\r\n case CREATE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // Another CREATE replaces previous CREATE.\r\n case UPDATE:\r\n return combineCreateAndUpdate(prevChange, nextChange); // Apply nextChange.mods into prevChange.obj\r\n case DELETE:\r\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!\r\n }\r\n break;\r\n case UPDATE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // Another CREATE replaces previous update.\r\n case UPDATE:\r\n return combineUpdateAndUpdate(prevChange, nextChange); // Add the additional modifications to existing modification set.\r\n case DELETE:\r\n return nextChange; // Only send the delete change. What was updated earlier is no longer of interest.\r\n }\r\n break;\r\n case DELETE:\r\n switch (nextChange.type) {\r\n case CREATE:\r\n return nextChange; // A resurection occurred. Only create change is of interest.\r\n case UPDATE:\r\n return prevChange; // Nothing to do. We cannot update an object that doesnt exist. Leave the delete change there.\r\n case DELETE:\r\n return prevChange; // Still a delete change. Leave as is.\r\n }\r\n break;\r\n }\r\n}\r\n","import {CREATE, UPDATE} from '../change_types';\r\nimport mergeChange from '../merge-change';\r\n\r\nexport default function initGetChangesSinceRevision(db, node, hasMoreToGive) {\r\n return function getChangesSinceRevision(revision, maxChanges, maxRevision, cb) {\r\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.\r\n var changeSet = {};\r\n var numChanges = 0;\r\n var partial = false;\r\n var ignoreSource = node.id;\r\n var nextRevision = revision;\r\n return db.transaction('r', db._changes, function () {\r\n var query = db._changes.where('rev').between(revision, maxRevision, false, true);\r\n return query.until(() => {\r\n if (numChanges === maxChanges) {\r\n partial = true;\r\n return true;\r\n }\r\n }).each(function (change) {\r\n // Note the revision in nextRevision:\r\n nextRevision = change.rev;\r\n // change.source is set based on currentTransaction.source\r\n if (change.source === ignoreSource) return;\r\n // Our _changes table contains more info than required (old objs, source etc). Just make sure to include the necessary info:\r\n var changeToSend = {\r\n type: change.type,\r\n table: change.table,\r\n key: change.key\r\n };\r\n if (change.type === CREATE)\r\n changeToSend.obj = change.obj;\r\n else if (change.type === UPDATE)\r\n changeToSend.mods = change.mods;\r\n\r\n var id = change.table + \":\" + change.key;\r\n var prevChange = changeSet[id];\r\n if (!prevChange) {\r\n // This is the first change on this key. Add it unless it comes from the source that we are working against\r\n changeSet[id] = changeToSend;\r\n ++numChanges;\r\n } else {\r\n // Merge the oldchange with the new change\r\n var nextChange = changeToSend;\r\n var mergedChange = mergeChange(prevChange, nextChange);\r\n changeSet[id] = mergedChange;\r\n }\r\n });\r\n }).then(function () {\r\n var changes = Object.keys(changeSet).map(function (key) {\r\n return changeSet[key];\r\n });\r\n hasMoreToGive.hasMoreToGive = partial;\r\n return cb(changes, partial, {myRevision: nextRevision});\r\n });\r\n };\r\n}\r\n","import {CREATE} from '../change_types';\r\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\r\n\r\nexport default function initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb) {\r\n return function getTableObjectsAsChanges(state, changes, collection) {\r\n /// \r\n /// \r\n /// \r\n var limitReached = false;\r\n return collection.until(function () {\r\n if (changes.length === MAX_CHANGES_PER_CHUNK) {\r\n limitReached = true;\r\n return true;\r\n }\r\n }).each(function (item, cursor) {\r\n changes.push({\r\n type: CREATE,\r\n table: state.currentTable,\r\n key: cursor.key,\r\n obj: cursor.value\r\n });\r\n state.currentKey = cursor.key;\r\n }).then(function () {\r\n if (limitReached) {\r\n // Limit reached. Send partial result.\r\n hasMoreToGive.hasMoreToGive = true;\r\n return cb(changes, null, true, {dbUploadState: state});\r\n } else {\r\n // Done iterating this table. Check if there are more tables to go through:\r\n if (state.tablesToUpload.length === 0) {\r\n // Done iterating all tables\r\n // Now append changes occurred during our dbUpload:\r\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\r\n return getChangesSinceRevision(state.localBaseRevision, MAX_CHANGES_PER_CHUNK - changes.length, brmcr.maxClientRevision, function (additionalChanges, partial, nodeModificationsOnAck) {\r\n changes = changes.concat(additionalChanges);\r\n nodeModificationsOnAck.dbUploadState = null;\r\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\r\n });\r\n } else {\r\n // Not done iterating all tables. Continue on next table:\r\n state.currentTable = state.tablesToUpload.shift();\r\n return getTableObjectsAsChanges(state, changes, db.table(state.currentTable).orderBy(':id'));\r\n }\r\n }\r\n });\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport getBaseRevisionAndMaxClientRevision from './get-base-revision-and-max-client-revision';\r\nimport initGetChangesSinceRevision from './get-changes-since-revision';\r\nimport initGetTableObjectsAsChanges from './get-table-objects-as-changes';\r\n\r\nexport default function initGetLocalChangesForNode(db, hasMoreToGive, partialsThreshold) {\r\n var MAX_CHANGES_PER_CHUNK = partialsThreshold;\r\n\r\n return function getLocalChangesForNode(node, cb) {\r\n /// \r\n /// Based on given node's current revision and state, this function makes sure to retrieve next chunk of changes\r\n /// for that node.\r\n /// \r\n /// \r\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.\r\n\r\n const getChangesSinceRevision = initGetChangesSinceRevision(db, node, hasMoreToGive);\r\n const getTableObjectsAsChanges = initGetTableObjectsAsChanges(db, node, MAX_CHANGES_PER_CHUNK, getChangesSinceRevision, hasMoreToGive, cb);\r\n\r\n // Only a \"remote\" SyncNode created by Dexie.Syncable\r\n // could not pass this test (remote nodes have myRevision: -1 on instantiation)\r\n if (node.myRevision >= 0) {\r\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.\r\n var brmcr = getBaseRevisionAndMaxClientRevision(node);\r\n return getChangesSinceRevision(node.myRevision, MAX_CHANGES_PER_CHUNK, brmcr.maxClientRevision, function (changes, partial, nodeModificationsOnAck) {\r\n return cb(changes, brmcr.remoteBaseRevision, partial, nodeModificationsOnAck);\r\n });\r\n } else {\r\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.\r\n // Check if we're in the middle of already doing that:\r\n if (node.dbUploadState === null) {\r\n // Initialize dbUploadState\r\n var tablesToUpload = db.tables.filter(function (table) {\r\n return table.schema.observable;\r\n }).map(function (table) {\r\n return table.name;\r\n });\r\n if (tablesToUpload.length === 0) return Dexie.Promise.resolve(cb([], null, false, {})); // There are no synced tables at all.\r\n var dbUploadState = {\r\n tablesToUpload: tablesToUpload,\r\n currentTable: tablesToUpload.shift(),\r\n currentKey: null\r\n };\r\n return db._changes.orderBy('rev').last(function (lastChange) {\r\n dbUploadState.localBaseRevision = (lastChange && lastChange.rev) || 0;\r\n var collection = db.table(dbUploadState.currentTable).orderBy(':id');\r\n return getTableObjectsAsChanges(dbUploadState, [], collection);\r\n });\r\n } else if (node.dbUploadState.currentKey) {\r\n const collection = db.table(node.dbUploadState.currentTable).where(':id').above(node.dbUploadState.currentKey);\r\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\r\n } else {\r\n const collection = db.table(dbUploadState.currentTable).orderBy(':id');\r\n return getTableObjectsAsChanges(Dexie.deepClone(node.dbUploadState), [], collection);\r\n }\r\n }\r\n };\r\n}\r\n","export const Statuses = {\r\n ERROR: -1, // An irreparable error occurred and the sync provider is dead.\r\n OFFLINE: 0, // The sync provider hasn't yet become online, or it has been disconnected.\r\n CONNECTING: 1, // Trying to connect to server\r\n ONLINE: 2, // Connected to server and currently in sync with server\r\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.\r\n ERROR_WILL_RETRY: 4 // An error occurred such as net down but the sync provider will retry to connect.\r\n};\r\n\r\nexport const StatusTexts = {\r\n \"-1\": \"ERROR\",\r\n \"0\": \"OFFLINE\",\r\n \"1\": \"CONNECTING\",\r\n \"2\": \"ONLINE\",\r\n \"3\": \"SYNCING\",\r\n \"4\": \"ERROR_WILL_RETRY\"\r\n};\r\n","import Dexie from 'dexie';\r\n\r\nimport initEnqueue from './enqueue';\r\nimport initSaveToUncommittedChanges from './save-to-uncommitted-changes';\r\nimport initFinallyCommitAllChanges from './finally-commit-all-changes';\r\nimport initGetLocalChangesForNode from './get-local-changes-for-node/get-local-changes-for-node';\r\nimport {Statuses} from './statuses';\r\n\r\nconst Promise = Dexie.Promise;\r\n\r\nexport default function initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise) {\r\n const enqueue = initEnqueue(db);\r\n var hasMoreToGive = {hasMoreToGive: true};\r\n\r\n function stillAlive() {\r\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\r\n // because the new instance should be considered a fresh instance and will have another local node.\r\n return db._localSyncNode && db._localSyncNode.id === dbAliveID;\r\n }\r\n\r\n return function connectProtocol(node, activePeer) {\r\n /// \r\n const getLocalChangesForNode = initGetLocalChangesForNode(db, hasMoreToGive, protocolInstance.partialsThreshold);\r\n\r\n const url = activePeer.url;\r\n\r\n function changeStatusTo(newStatus) {\r\n if (node.status !== newStatus) {\r\n node.status = newStatus;\r\n node.save().then(()=> {\r\n db.syncable.on.statusChanged.fire(newStatus, url);\r\n // Also broadcast message to other nodes about the status\r\n db.observable.broadcastMessage(\"syncStatusChanged\", {newStatus: newStatus, url: url}, false);\r\n }).catch('DatabaseClosedError', ()=> {\r\n });\r\n }\r\n }\r\n\r\n activePeer.on('disconnect', function (newStatus) {\r\n if (!isNaN(newStatus)) changeStatusTo(newStatus);\r\n });\r\n\r\n var connectedContinuation;\r\n changeStatusTo(Statuses.CONNECTING);\r\n return doSync();\r\n\r\n function doSync() {\r\n // Use enqueue() to ensure only a single promise execution at a time.\r\n return enqueue(doSync, function () {\r\n // By returning the Promise returned by getLocalChangesForNode() a final catch() on the sync() method will also catch error occurring in entire sequence.\r\n return getLocalChangesForNode_autoAckIfEmpty(node, sendChangesToProvider);\r\n }, dbAliveID);\r\n }\r\n\r\n function sendChangesToProvider(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n // Create a final Promise for the entire sync() operation that will resolve when provider calls onSuccess().\r\n // By creating finalPromise before calling protocolInstance.sync() it is possible for provider to call onError() immediately if it wants.\r\n var finalSyncPromise = new Promise(function (resolve, reject) {\r\n rejectConnectPromise.p = function (err) {\r\n reject(err);\r\n };\r\n Dexie.asap(function () {\r\n try {\r\n protocolInstance.sync(\r\n node.syncContext,\r\n url,\r\n options,\r\n remoteBaseRevision,\r\n node.appliedRemoteRevision,\r\n changes,\r\n partial,\r\n applyRemoteChanges,\r\n onChangesAccepted,\r\n function (continuation) {\r\n resolve(continuation);\r\n },\r\n onError);\r\n } catch (ex) {\r\n onError(ex, Infinity);\r\n }\r\n\r\n function onError(error, again) {\r\n reject(error);\r\n if (stillAlive()) {\r\n if (!isNaN(again) && again < Infinity) {\r\n setTimeout(function () {\r\n if (stillAlive()) {\r\n changeStatusTo(Statuses.SYNCING);\r\n doSync().catch('DatabaseClosedError', abortTheProvider);\r\n }\r\n }, again);\r\n changeStatusTo(Statuses.ERROR_WILL_RETRY, error);\r\n if (connectedContinuation && connectedContinuation.disconnect) connectedContinuation.disconnect();\r\n connectedContinuation = null;\r\n } else {\r\n abortTheProvider(error); // Will fire ERROR on statusChanged event.\r\n }\r\n }\r\n }\r\n });\r\n });\r\n\r\n return finalSyncPromise.then(function () {\r\n // Resolve caller of db.syncable.connect() with undefined. Not with continuation!\r\n return undefined;\r\n }).finally(()=> {\r\n // In case error happens after connect, don't try reject the connect promise anymore.\r\n // This is important. A Dexie unit test that verifies unhandled rejections will fail when Dexie.Syncable addon\r\n // is active and this happens. It would fire unhandledrejection but that we do not want.\r\n rejectConnectPromise.p = null;\r\n });\r\n\r\n function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n // We dont know if onSuccess() was called by provider yet. If it's already called, finalPromise.then() will execute immediately,\r\n // otherwise it will execute when finalSyncPromise resolves.\r\n finalSyncPromise.then(continueSendingChanges);\r\n return node.save();\r\n }\r\n }\r\n\r\n function abortTheProvider(error) {\r\n activePeer.disconnect(Statuses.ERROR, error);\r\n }\r\n\r\n function getLocalChangesForNode_autoAckIfEmpty(node, cb) {\r\n return getLocalChangesForNode(node, function autoAck(changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n if (changes.length === 0 && 'myRevision' in nodeModificationsOnAck && nodeModificationsOnAck.myRevision !== node.myRevision) {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n return getLocalChangesForNode(node, autoAck);\r\n } else {\r\n return cb(changes, remoteBaseRevision, partial, nodeModificationsOnAck);\r\n }\r\n });\r\n }\r\n\r\n function applyRemoteChanges(remoteChanges, remoteRevision, partial/*, clear*/) {\r\n const saveToUncommittedChanges = initSaveToUncommittedChanges(db, node);\r\n const finallyCommitAllChanges = initFinallyCommitAllChanges(db, node);\r\n\r\n return enqueue(applyRemoteChanges, function () {\r\n if (!stillAlive()) return Promise.reject(new Dexie.DatabaseClosedError());\r\n // FIXTHIS: Check what to do if clear() is true!\r\n return (partial ? saveToUncommittedChanges(remoteChanges, remoteRevision) : finallyCommitAllChanges(remoteChanges, remoteRevision))\r\n .catch(function (error) {\r\n abortTheProvider(error);\r\n return Promise.reject(error);\r\n });\r\n }, dbAliveID);\r\n }\r\n\r\n //\r\n //\r\n // Continuation Patterns Follows\r\n //\r\n //\r\n\r\n function continueSendingChanges(continuation) {\r\n if (!stillAlive()) { // Database was closed.\r\n if (continuation.disconnect)\r\n continuation.disconnect();\r\n return;\r\n }\r\n\r\n connectedContinuation = continuation;\r\n activePeer.on('disconnect', function () {\r\n if (connectedContinuation) {\r\n if (connectedContinuation.react) {\r\n try {\r\n // react pattern must provide a disconnect function.\r\n connectedContinuation.disconnect();\r\n } catch (e) {\r\n }\r\n }\r\n connectedContinuation = null; // Stop poll() pattern from polling again and abortTheProvider() from being called twice.\r\n }\r\n });\r\n\r\n if (continuation.react) {\r\n continueUsingReactPattern(continuation);\r\n } else {\r\n continueUsingPollPattern(continuation);\r\n }\r\n }\r\n\r\n // React Pattern (eager)\r\n function continueUsingReactPattern(continuation) {\r\n var changesWaiting, // Boolean\r\n isWaitingForServer; // Boolean\r\n\r\n\r\n function onChanges() {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n if (isWaitingForServer)\r\n changesWaiting = true;\r\n else {\r\n reactToChanges();\r\n }\r\n }\r\n }\r\n\r\n db.on('changes', onChanges);\r\n\r\n activePeer.on('disconnect', function () {\r\n db.on.changes.unsubscribe(onChanges);\r\n });\r\n\r\n function reactToChanges() {\r\n if (!connectedContinuation) return;\r\n changesWaiting = false;\r\n isWaitingForServer = true;\r\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n if (!connectedContinuation) return;\r\n if (changes.length > 0) {\r\n continuation.react(changes, remoteBaseRevision, partial, function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n // More changes may be waiting:\r\n reactToChanges();\r\n });\r\n } else {\r\n isWaitingForServer = false;\r\n if (changesWaiting) {\r\n // A change jumped in between the time-spot of quering _changes and getting called back with zero changes.\r\n // This is an expreemely rare scenario, and eventually impossible. But need to be here because it could happen in theory.\r\n reactToChanges();\r\n } else {\r\n changeStatusTo(Statuses.ONLINE);\r\n }\r\n }\r\n }).catch(ex => {\r\n console.error(`Got ${ex.message} caught by reactToChanges`);\r\n abortTheProvider(ex);\r\n });\r\n }\r\n\r\n reactToChanges();\r\n }\r\n\r\n // Poll Pattern\r\n function continueUsingPollPattern() {\r\n\r\n function syncAgain() {\r\n getLocalChangesForNode_autoAckIfEmpty(node, function (changes, remoteBaseRevision, partial, nodeModificationsOnAck) {\r\n\r\n protocolInstance.sync(node.syncContext, url, options, remoteBaseRevision, node.appliedRemoteRevision, changes, partial, applyRemoteChanges, onChangesAccepted, onSuccess, onError);\r\n\r\n function onChangesAccepted() {\r\n Object.keys(nodeModificationsOnAck).forEach(function (keyPath) {\r\n Dexie.setByKeyPath(node, keyPath, nodeModificationsOnAck[keyPath]);\r\n });\r\n node.save().catch('DatabaseClosedError', ()=> {\r\n });\r\n }\r\n\r\n function onSuccess(continuation) {\r\n if (!connectedContinuation) {\r\n // Got disconnected before succeeding. Quit.\r\n return;\r\n }\r\n connectedContinuation = continuation;\r\n if (partial) {\r\n // We only sent partial changes. Need to do another round asap.\r\n syncAgain();\r\n } else {\r\n // We've sent all changes now (in sync!)\r\n if (!isNaN(continuation.again) && continuation.again < Infinity) {\r\n // Provider wants to keep polling. Set Status to ONLINE.\r\n changeStatusTo(Statuses.ONLINE);\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, continuation.again);\r\n } else {\r\n // Provider seems finished polling. Since we are never going to poll again,\r\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\r\n activePeer.disconnect(Statuses.OFFLINE);\r\n }\r\n }\r\n }\r\n\r\n function onError(error, again) {\r\n if (!isNaN(again) && again < Infinity) {\r\n if (connectedContinuation) {\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, again);\r\n changeStatusTo(Statuses.ERROR_WILL_RETRY);\r\n } // else status is already changed since we got disconnected.\r\n } else {\r\n abortTheProvider(error); // Will fire ERROR on onStatusChanged.\r\n }\r\n }\r\n }).catch(abortTheProvider);\r\n }\r\n\r\n if (hasMoreToGive.hasMoreToGive) {\r\n syncAgain();\r\n } else if (connectedContinuation && !isNaN(connectedContinuation.again) && connectedContinuation.again < Infinity) {\r\n changeStatusTo(Statuses.ONLINE);\r\n setTimeout(function () {\r\n if (connectedContinuation) {\r\n changeStatusTo(Statuses.SYNCING);\r\n syncAgain();\r\n }\r\n }, connectedContinuation.again);\r\n } else {\r\n // Provider seems finished polling. Since we are never going to poll again,\r\n // disconnect provider and set status to OFFLINE until another call to db.syncable.connect().\r\n activePeer.disconnect(Statuses.OFFLINE);\r\n }\r\n }\r\n };\r\n}\r\n","import Dexie from 'dexie';\r\n\r\nimport initGetOrCreateSyncNode from './get-or-create-sync-node';\r\nimport initConnectProtocol from './connect-protocol';\r\nimport {Statuses} from './statuses';\r\n\r\nexport default function initConnectFn(db, activePeers) {\r\n return function connect(protocolInstance, protocolName, url, options, dbAliveID) {\r\n /// \r\n var existingPeer = activePeers.filter(function (peer) {\r\n return peer.url === url;\r\n });\r\n if (existingPeer.length > 0) {\r\n const activePeer = existingPeer[0];\r\n const diffObject = {};\r\n Dexie.getObjectDiff(activePeer.syncOptions, options, diffObject);\r\n // Options have been changed\r\n // We need to disconnect and reconnect\r\n if (Object.keys(diffObject).length !== 0) {\r\n return db.syncable.disconnect(url)\r\n .then(() => {\r\n return execConnect();\r\n })\r\n } else {\r\n // Never create multiple syncNodes with same protocolName and url. Instead, let the next call to connect() return the same promise that\r\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.\r\n return existingPeer[0].connectPromise;\r\n }\r\n }\r\n\r\n function execConnect() {\r\n // Use an object otherwise we wouldn't be able to get the reject promise from\r\n // connectProtocol\r\n var rejectConnectPromise = {p: null};\r\n const connectProtocol = initConnectProtocol(db, protocolInstance, dbAliveID, options, rejectConnectPromise);\r\n const getOrCreateSyncNode = initGetOrCreateSyncNode(db, protocolName, url);\r\n var connectPromise = getOrCreateSyncNode(options).then(function (node) {\r\n return connectProtocol(node, activePeer);\r\n });\r\n\r\n var disconnected = false;\r\n var activePeer = {\r\n url: url,\r\n status: Statuses.OFFLINE,\r\n connectPromise: connectPromise,\r\n syncOptions: options,\r\n on: Dexie.Events(null, \"disconnect\"),\r\n disconnect: function (newStatus, error) {\r\n var pos = activePeers.indexOf(activePeer);\r\n if (pos >= 0) activePeers.splice(pos, 1);\r\n if (error && rejectConnectPromise.p) rejectConnectPromise.p(error);\r\n if (!disconnected) {\r\n activePeer.on.disconnect.fire(newStatus, error);\r\n }\r\n disconnected = true;\r\n }\r\n };\r\n activePeers.push(activePeer);\r\n\r\n return connectPromise;\r\n }\r\n\r\n return execConnect();\r\n };\r\n}\r\n","/* ========================================================================== \r\n * dexie-syncable.js\r\n * ==========================================================================\r\n *\r\n * Dexie addon for syncing indexedDB with remote endpoints.\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com,\r\n * Nikolas Poniros, https://github.com/nponiros\r\n *\r\n * ==========================================================================\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n * \r\n */\r\n\r\nimport Dexie from \"dexie\";\r\n// Depend on 'dexie-observable'\r\n// To support both ES6,AMD,CJS and UMD (plain script), we just import it and then access it as \"Dexie.Observable\".\r\n// That way, our plugin works in all UMD cases.\r\n// If target platform would only be module based (ES6/AMD/CJS), we could have done 'import Observable from \"dexie-observable\"'.\r\nimport \"dexie-observable\";\r\n\r\nimport initSyncableConnect from './syncable-connect';\r\nimport initConnectFn from './connect-fn';\r\nimport {Statuses, StatusTexts} from './statuses';\r\n\r\nvar override = Dexie.override,\r\n Promise = Dexie.Promise,\r\n Observable = Dexie.Observable;\r\n\r\nexport default function Syncable (db) {\r\n /// \r\n\r\n var activePeers = [];\r\n\r\n const connectFn = initConnectFn(db, activePeers);\r\n const syncableConnect = initSyncableConnect(db, connectFn);\r\n\r\n db.on('message', function(msg) {\r\n // Message from other local node arrives...\r\n Dexie.vip(function() {\r\n if (msg.type === 'connect') {\r\n // We are master node and another non-master node wants us to do the connect.\r\n db.syncable.connect(msg.message.protocolName, msg.message.url, msg.message.options).then(msg.resolve, msg.reject);\r\n } else if (msg.type === 'disconnect') {\r\n db.syncable.disconnect(msg.message.url).then(msg.resolve, msg.reject);\r\n } else if (msg.type === 'syncStatusChanged') {\r\n // We are client and a master node informs us about syncStatus change.\r\n // Lookup the connectedProvider and call its event\r\n db.syncable.on.statusChanged.fire(msg.message.newStatus, msg.message.url);\r\n }\r\n });\r\n });\r\n\r\n db.on('cleanup', function(weBecameMaster) {\r\n // A cleanup (done in Dexie.Observable) may result in that a master node is removed and we become master.\r\n if (weBecameMaster) {\r\n // We took over the master role in Observable's cleanup method.\r\n // We should connect to remote servers now.\r\n // At this point, also reconnect servers with status ERROR_WILL_RETRY as well as plain ERROR.\r\n // Reason to reconnect to those with plain \"ERROR\" is that the ERROR state may occur when a database\r\n // connection has been closed. The new master would then be expected to reconnect.\r\n // Also, this is not an infinite poll(). This is rare event that a new browser tab takes over from\r\n // an old closed one. \r\n Dexie.ignoreTransaction(()=>Dexie.vip(()=>{\r\n return db._syncNodes.where({type: 'remote'})\r\n .filter(node => node.status !== Statuses.OFFLINE)\r\n .toArray(connectedRemoteNodes => Promise.all(connectedRemoteNodes.map(node => \r\n db.syncable.connect(node.syncProtocol, node.url, node.syncOptions).catch(e => {\r\n console.warn(`Dexie.Syncable: Could not connect to ${node.url}. ${e.stack || e}`);\r\n })\r\n )));\r\n })).catch('DatabaseClosedError', ()=>{});\r\n }\r\n });\r\n\r\n // \"ready\" subscriber for the master node that makes sure it will always connect to sync server\r\n // when the database opens. It will not wait for the connection to complete, just initiate the\r\n // connection so that it will continue syncing as long as the database is open.\r\n\r\n // Dexie.Observable's 'ready' subscriber will have been invoked prior to this, making sure\r\n // that db._localSyncNode exists and persisted before this subscriber kicks in.\r\n db.on('ready', function onReady() {\r\n // Again, in onReady: If we ARE master, make sure to connect to remote servers that is in a connected state.\r\n if (db._localSyncNode && db._localSyncNode.isMaster) {\r\n // Make sure to connect to remote servers that is in a connected state (NOT OFFLINE or ERROR!)\r\n // This \"ready\" subscriber will never be the one performing the initial sync request, because\r\n // even after calling db.syncable.connect(), there won't exist any \"remote\" sync node yet.\r\n // Instead, db.syncable.connect() will subscribe to \"ready\" also, and that subscriber will be\r\n // called after this one. There, in that subscriber, the initial sync request will take place\r\n // and the \"remote\" node will be created so that this \"ready\" subscriber can auto-connect the\r\n // next time this database is opened.\r\n // CONCLUSION: We can always assume that the local DB has been in sync with the server at least\r\n // once in the past for each \"connectedRemoteNode\" we find in query below.\r\n\r\n // Don't halt db.ready while connecting (i.e. we do not return a promise here!)\r\n db._syncNodes\r\n .where('type').equals('remote')\r\n .and(node => node.status !== Statuses.OFFLINE)\r\n .toArray(connectedRemoteNodes => {\r\n // There are connected remote nodes that we must manage (or take over to manage)\r\n connectedRemoteNodes.forEach(\r\n node => db.syncable.connect(\r\n node.syncProtocol,\r\n node.url,\r\n node.syncOptions) \r\n .catch (()=>{}) // A failure will be triggered in on('statusChanged'). We can ignore.\r\n );\r\n }).catch('DatabaseClosedError', ()=>{});\r\n }\r\n }, true); // True means the ready event will survive a db reopen - db.close()/db.open()\r\n\r\n db.syncable = {};\r\n\r\n db.syncable.getStatus = function(url, cb) {\r\n if (db.isOpen()) {\r\n return Dexie.vip(function() {\r\n return db._syncNodes.where('url').equals(url).first(function(node) {\r\n return node ? node.status : Statuses.OFFLINE;\r\n });\r\n }).then(cb);\r\n } else {\r\n return Promise.resolve(Syncable.Statuses.OFFLINE).then(cb);\r\n }\r\n };\r\n\r\n db.syncable.getOptions = function(url, cb) {\r\n return db.transaction('r?', db._syncNodes, () => {\r\n return db._syncNodes.where('url').equals(url).first(function(node) {\r\n return node.syncOptions;\r\n }).then(cb);\r\n });\r\n };\r\n\r\n db.syncable.list = function() {\r\n return db.transaction('r?', db._syncNodes, ()=>{\r\n return db._syncNodes.where('type').equals('remote').toArray(function(a) {\r\n return a.map(function(node) { return node.url; });\r\n });\r\n });\r\n };\r\n\r\n db.syncable.on = Dexie.Events(db, { statusChanged: \"asap\" });\r\n\r\n db.syncable.disconnect = function(url) {\r\n return Dexie.ignoreTransaction(()=>{\r\n return Promise.resolve().then(()=>{\r\n if (db._localSyncNode && db._localSyncNode.isMaster) {\r\n return Promise.all(activePeers.filter(peer => peer.url === url).map(peer => {\r\n return peer.disconnect(Statuses.OFFLINE);\r\n }));\r\n } else {\r\n return db._syncNodes.where('isMaster').above(0).first(masterNode => {\r\n return db.observable.sendMessage('disconnect', { url: url }, masterNode.id, {wantReply: true});\r\n });\r\n }\r\n }).then(()=>{\r\n return db._syncNodes.where(\"url\").equals(url).modify(node => {\r\n node.status = Statuses.OFFLINE;\r\n });\r\n });\r\n });\r\n };\r\n\r\n db.syncable.connect = function(protocolName, url, options) {\r\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.\r\n var protocolInstance = Syncable.registeredProtocols[protocolName];\r\n if (protocolInstance) {\r\n return syncableConnect(protocolInstance, protocolName, url, options);\r\n } else {\r\n return Promise.reject(\r\n new Error(\"ISyncProtocol '\" + protocolName + \"' is not registered in Dexie.Syncable.registerSyncProtocol()\")\r\n );\r\n }\r\n };\r\n\r\n db.syncable.delete = function(url) {\r\n return db.syncable.disconnect(url).then(()=>{\r\n return db.transaction('rw!', db._syncNodes, db._changes, db._uncommittedChanges, ()=>{\r\n // Find the node(s)\r\n // Several can be found, as detected by @martindiphoorn,\r\n // let's delete them and cleanup _uncommittedChanges and _changes \r\n // accordingly.\r\n let nodeIDsToDelete;\r\n return db._syncNodes\r\n .where(\"url\").equals(url)\r\n .toArray(nodes => nodes.map(node => node.id))\r\n .then(nodeIDs => {\r\n nodeIDsToDelete = nodeIDs;\r\n // Delete the syncNode that represents the remote endpoint.\r\n return db._syncNodes.where('id').anyOf(nodeIDs).delete()\r\n })\r\n .then (() =>\r\n // In case there were uncommittedChanges belonging to this, delete them as well\r\n db._uncommittedChanges.where('node').anyOf(nodeIDsToDelete).delete());\r\n }).then(()=> {\r\n // Spawn background job to delete old changes, now that a node has been deleted,\r\n // there might be changes in _changes table that is not needed to keep anymore.\r\n // This is done in its own transaction, or possible several transaction to prohibit\r\n // starvation\r\n Observable.deleteOldChanges(db);\r\n });\r\n });\r\n };\r\n\r\n db.syncable.unsyncedChanges = function(url) {\r\n return db._syncNodes.where(\"url\").equals(url).first(function(node) {\r\n return db._changes.where('rev').above(node.myRevision).toArray();\r\n });\r\n };\r\n\r\n db.close = override(db.close, function(origClose) {\r\n return function() {\r\n activePeers.forEach(function(peer) {\r\n peer.disconnect();\r\n });\r\n return origClose.apply(this, arguments);\r\n };\r\n });\r\n\r\n Object.defineProperty(\r\n db.observable.SyncNode.prototype,\r\n 'save', {\r\n enumerable: false,\r\n configurable: true,\r\n writable: true,\r\n value() {\r\n return db.transaction('rw?', db._syncNodes, () => {\r\n return db._syncNodes.put(this);\r\n });\r\n }\r\n });\r\n}\r\n\r\nSyncable.Statuses = Statuses;\r\n\r\nSyncable.StatusTexts = StatusTexts;\r\n\r\nSyncable.registeredProtocols = {}; // Map when key is the provider name.\r\n\r\nSyncable.registerSyncProtocol = function(name, protocolInstance) {\r\n /// \r\n /// Register a synchronization protocol that can synchronize databases with remote servers.\r\n /// \r\n /// Provider name\r\n /// Implementation of ISyncProtocol\r\n const partialsThreshold = protocolInstance.partialsThreshold;\r\n if (typeof partialsThreshold === 'number') {\r\n // Don't allow NaN or negative threshold\r\n if (isNaN(partialsThreshold) || partialsThreshold < 0) {\r\n throw new Error('The given number for the threshold is not supported');\r\n }\r\n // If the threshold is 0 we will not send any client changes but will get server changes\r\n } else {\r\n // Use Infinity as the default so simple protocols don't have to care about partial synchronization\r\n protocolInstance.partialsThreshold = Infinity;\r\n }\r\n Syncable.registeredProtocols[name] = protocolInstance;\r\n};\r\n\r\n// Register addon in Dexie:\r\nDexie.Syncable = Syncable;\r\nDexie.addons.push(Syncable);\r\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..e245180f5 --- /dev/null +++ b/dist/dexie.d.ts @@ -0,0 +1,527 @@ +// Type definitions for Dexie v2.0.1 +// 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..02c19bcb3 --- /dev/null +++ b/dist/dexie.es.js @@ -0,0 +1,4503 @@ +/* + * 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 doFakeAutoComplete(fn) { + var to = setTimeout(fn, 1000); + clearTimeout(to); +} +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. +// By default, debug will be true only if platform is a web platform and its page is served from localhost. +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); + }; +} + +// +// 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 +// 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. +// Callbacks to call in this or next physical tick. +var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. +// 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. +// 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 : + { + 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) { } +} +doFakeAutoComplete(function () { + // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. + asap$1 = function (fn, args) { + setTimeout(function () { fn.apply(null, args); }, 0); + }; +}); +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 + * =============================================== + * + * 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 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; + fakeAutoComplete(function () { + upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear. + }); + 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 fake || 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) { + doFakeAutoComplete(function () { return resolve(); }); + // 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) { + } + } + 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); + }); + } + }); + }; + }); + fakeAutoComplete(function () { + db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema)); + }); + 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")); }) + : 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 (fake && autoSchema) + return new Table(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) { + if (fake) + return new Promise(fn); // Simplify the work for Intellisense/Code completion. + 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) { + fake && resolve(self.schema.instanceTemplate); + 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]) : + 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); + })(); + } + function getInstanceTemplate(ctx) { + return ctx.table.schema.instanceTemplate; + } + 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; + if (fake) { + var item = getInstanceTemplate(ctx), primKeyPath = ctx.table.schema.primKey.keyPath, key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath), primaryKey = getByKeyPath(item, primKeyPath); + fn(item, { key: key, primaryKey: primaryKey }); + } + return this._read(function (resolve, reject, idbstore) { + iter(ctx, fn, resolve, reject, idbstore); + }); + }, + count: function (cb) { + if (fake) + return Promise.resolve(0).then(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) { + fake && resolve([getInstanceTemplate(ctx)]); + 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; + fake && filterFunction(getInstanceTemplate(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} + fake && filterFunction(getInstanceTemplate(this._ctx)); + 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; + fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate); + 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); + }); +} +var fakeAutoComplete = function () { }; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) +var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete()) +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, result = req.result, ctx = req._hookCtx, // Contains the hook error handler. Put here instead of closure to boost performance. + 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. + /// + properties ? extend(this, properties) : fake && applyStructure(this, structure); + } + 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) : + 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)); }), + fakeAutoComplete: fakeAutoComplete, + // 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; +// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015. +doFakeAutoComplete(function () { + Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete; + Dexie.fake = fake = true; +}); +// 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..20d93d147 --- /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;\r\nexport var isArray = Array.isArray;\r\nexport var _global =\r\n typeof self !== 'undefined' ? self :\r\n typeof window !== 'undefined' ? window :\r\n global;\r\n\r\nexport function extend(obj, extension) {\r\n if (typeof extension !== 'object') return obj;\r\n keys(extension).forEach(function (key) {\r\n obj[key] = extension[key];\r\n });\r\n return obj;\r\n}\r\n\r\nexport const getProto = Object.getPrototypeOf;\r\nexport const _hasOwn = {}.hasOwnProperty;\r\nexport function hasOwn(obj, prop) {\r\n return _hasOwn.call(obj, prop);\r\n}\r\n\r\nexport function props (proto, extension) {\r\n if (typeof extension === 'function') extension = extension(getProto(proto));\r\n keys(extension).forEach(key => {\r\n setProp(proto, key, extension[key]);\r\n });\r\n}\r\n\r\nexport const defineProperty = Object.defineProperty;\r\n\r\nexport function setProp(obj, prop, functionOrGetSet, options) {\r\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\r\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\r\n {value: functionOrGetSet, configurable: true, writable: true}, options));\r\n}\r\n\r\nexport function derive(Child) {\r\n return {\r\n from: function (Parent) {\r\n Child.prototype = Object.create(Parent.prototype);\r\n setProp(Child.prototype, \"constructor\", Child);\r\n return {\r\n extend: props.bind(null, Child.prototype)\r\n };\r\n }\r\n };\r\n}\r\n\r\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\r\n\r\nexport function getPropertyDescriptor(obj, prop) {\r\n var pd = getOwnPropertyDescriptor(obj, prop),\r\n proto;\r\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\r\n}\r\n\r\nvar _slice = [].slice;\r\nexport function slice(args, start, end) {\r\n return _slice.call(args, start, end);\r\n}\r\n\r\nexport function override(origFunc, overridedFactory) {\r\n return overridedFactory(origFunc);\r\n}\r\n\r\nexport function doFakeAutoComplete(fn) {\r\n var to = setTimeout(fn, 1000);\r\n clearTimeout(to);\r\n}\r\n\r\nexport function assert (b) {\r\n if (!b) throw new Error(\"Assertion Failed\");\r\n}\r\n\r\nexport function asap(fn) {\r\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\r\n}\r\n\r\nexport function getUniqueArray(a) {\r\n return a.filter((value, index, self) => self.indexOf(value) === index);\r\n}\r\n\r\n/** Generate an object (hash map) based on given array.\r\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\r\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\r\n * current item wont affect the resulting object.\r\n */\r\nexport function arrayToObject (array, extractor) {\r\n return array.reduce((result, item, i) => {\r\n var nameAndValue = extractor(item, i);\r\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\r\n return result;\r\n }, {});\r\n}\r\n\r\nexport function trycatcher(fn, reject) {\r\n return function () {\r\n try {\r\n fn.apply(this, arguments);\r\n } catch (e) {\r\n reject(e);\r\n }\r\n };\r\n}\r\n\r\nexport function tryCatch(fn, onerror, args) {\r\n try {\r\n fn.apply(null, args);\r\n } catch (ex) {\r\n onerror && onerror(ex);\r\n }\r\n}\r\n\r\nexport function getByKeyPath(obj, keyPath) {\r\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\r\n if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\r\n if (!keyPath) return obj;\r\n if (typeof keyPath !== 'string') {\r\n var rv = [];\r\n for (var i = 0, l = keyPath.length; i < l; ++i) {\r\n var val = getByKeyPath(obj, keyPath[i]);\r\n rv.push(val);\r\n }\r\n return rv;\r\n }\r\n var period = keyPath.indexOf('.');\r\n if (period !== -1) {\r\n var innerObj = obj[keyPath.substr(0, period)];\r\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\r\n }\r\n return undefined;\r\n}\r\n\r\nexport function setByKeyPath(obj, keyPath, value) {\r\n if (!obj || keyPath === undefined) return;\r\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\r\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\r\n assert(typeof value !== 'string' && 'length' in value);\r\n for (var i = 0, l = keyPath.length; i < l; ++i) {\r\n setByKeyPath(obj, keyPath[i], value[i]);\r\n }\r\n } else {\r\n var period = keyPath.indexOf('.');\r\n if (period !== -1) {\r\n var currentKeyPath = keyPath.substr(0, period);\r\n var remainingKeyPath = keyPath.substr(period + 1);\r\n if (remainingKeyPath === \"\")\r\n if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;\r\n else {\r\n var innerObj = obj[currentKeyPath];\r\n if (!innerObj) innerObj = (obj[currentKeyPath] = {});\r\n setByKeyPath(innerObj, remainingKeyPath, value);\r\n }\r\n } else {\r\n if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;\r\n }\r\n }\r\n}\r\n\r\nexport function delByKeyPath(obj, keyPath) {\r\n if (typeof keyPath === 'string')\r\n setByKeyPath(obj, keyPath, undefined);\r\n else if ('length' in keyPath)\r\n [].map.call(keyPath, function(kp) {\r\n setByKeyPath(obj, kp, undefined);\r\n });\r\n}\r\n\r\nexport function shallowClone(obj) {\r\n var rv = {};\r\n for (var m in obj) {\r\n if (hasOwn(obj, m)) rv[m] = obj[m];\r\n }\r\n return rv;\r\n}\r\n\r\nconst concat = [].concat;\r\nexport function flatten (a) {\r\n return concat.apply([], a);\r\n}\r\n\r\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\r\nvar intrinsicTypes =\r\n \"Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set\"\r\n .split(',').concat(\r\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\r\n ).filter(t=>_global[t]).map(t=>_global[t])\r\n\r\nexport function deepClone(any) {\r\n if (!any || typeof any !== 'object') return any;\r\n var rv;\r\n if (isArray(any)) {\r\n rv = [];\r\n for (var i = 0, l = any.length; i < l; ++i) {\r\n rv.push(deepClone(any[i]));\r\n }\r\n } else if (intrinsicTypes.indexOf(any.constructor) >= 0) {\r\n rv = any;\r\n } else {\r\n rv = any.constructor ? Object.create(any.constructor.prototype) : {};\r\n for (var prop in any) {\r\n if (hasOwn(any, prop)) {\r\n rv[prop] = deepClone(any[prop]);\r\n }\r\n }\r\n }\r\n return rv;\r\n}\r\n\r\nexport function getObjectDiff(a, b, rv, prfx) {\r\n // Compares objects a and b and produces a diff object.\r\n rv = rv || {};\r\n prfx = prfx || '';\r\n keys(a).forEach(prop => {\r\n if (!hasOwn(b, prop))\r\n rv[prfx+prop] = undefined; // Property removed\r\n else {\r\n var ap = a[prop],\r\n bp = b[prop];\r\n if (typeof ap === 'object' && typeof bp === 'object' &&\r\n ap && bp &&\r\n // Now compare constructors are same (not equal because wont work in Safari)\r\n (''+ap.constructor) === (''+bp.constructor))\r\n // Same type of object but its properties may have changed\r\n getObjectDiff (ap, bp, rv, prfx + prop + \".\");\r\n else if (ap !== bp)\r\n rv[prfx + prop] = b[prop];// Primitive value changed\r\n }\r\n });\r\n keys(b).forEach(prop => {\r\n if (!hasOwn(a, prop)) {\r\n rv[prfx+prop] = b[prop]; // Property added\r\n }\r\n });\r\n return rv;\r\n}\r\n\r\n// If first argument is iterable or array-like, return it as an array\r\nexport const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;\r\nexport const getIteratorOf = iteratorSymbol ? function(x) {\r\n var i;\r\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\r\n} : function () { return null; };\r\n\r\nexport const NO_CHAR_ARRAY = {};\r\n// Takes one or several arguments and returns an array based on the following criteras:\r\n// * If several arguments provided, return arguments converted to an array in a way that\r\n// still allows javascript engine to optimize the code.\r\n// * If single argument is an array, return a clone of it.\r\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\r\n// case to the two bullets below.\r\n// * If single argument is an iterable, convert it to an array and return the resulting array.\r\n// * If single argument is array-like (has length of type number), convert it to an array.\r\nexport function getArrayOf (arrayLike) {\r\n var i, a, x, it;\r\n if (arguments.length === 1) {\r\n if (isArray(arrayLike)) return arrayLike.slice();\r\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\r\n if ((it = getIteratorOf(arrayLike))) {\r\n a = [];\r\n while ((x = it.next()), !x.done) a.push(x.value);\r\n return a;\r\n }\r\n if (arrayLike == null) return [arrayLike];\r\n i = arrayLike.length;\r\n if (typeof i === 'number') {\r\n a = new Array(i);\r\n while (i--) a[i] = arrayLike[i];\r\n return a;\r\n }\r\n return [arrayLike];\r\n }\r\n i = arguments.length;\r\n a = new Array(i);\r\n while (i--) a[i] = arguments[i];\r\n return a;\r\n}\r\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\r\n// When debug = true, error's stacks will contain asyncronic long stacks.\r\nexport var debug = typeof location !== 'undefined' &&\r\n // By default, use debug mode if served from localhost.\r\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\r\n\r\nexport function setDebug(value, filter) {\r\n debug = value;\r\n libraryFilter = filter;\r\n}\r\n\r\nexport var libraryFilter = () => true;\r\n\r\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\r\n\r\nexport function getErrorWithStack() {\r\n \"use strict\";\r\n if (NEEDS_THROW_FOR_STACK) try {\r\n // Doing something naughty in strict mode here to trigger a specific error\r\n // that can be explicitely ignored in debugger's exception settings.\r\n // If we'd just throw new Error() here, IE's debugger's exception settings\r\n // will just consider it as \"exception thrown by javascript code\" which is\r\n // something you wouldn't want it to ignore.\r\n getErrorWithStack.arguments;\r\n throw new Error(); // Fallback if above line don't throw.\r\n } catch(e) {\r\n return e;\r\n }\r\n return new Error();\r\n}\r\n\r\nexport function prettyStack(exception, numIgnoredFrames) {\r\n var stack = exception.stack;\r\n if (!stack) return \"\";\r\n numIgnoredFrames = (numIgnoredFrames || 0);\r\n if (stack.indexOf(exception.name) === 0)\r\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\r\n return stack.split('\\n')\r\n .slice(numIgnoredFrames)\r\n .filter(libraryFilter)\r\n .map(frame => \"\\n\" + frame)\r\n .join('');\r\n}\r\n\r\nexport function deprecated (what, fn) {\r\n return function () {\r\n console.warn(`${what} is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\r\n return fn.apply(this, arguments);\r\n }\r\n}\r\n","import { derive, setProp } from './utils';\r\nimport { getErrorWithStack, prettyStack } from './debug';\r\n\r\nvar dexieErrorNames = [\r\n 'Modify',\r\n 'Bulk',\r\n 'OpenFailed',\r\n 'VersionChange',\r\n 'Schema',\r\n 'Upgrade',\r\n 'InvalidTable',\r\n 'MissingAPI',\r\n 'NoSuchDatabase',\r\n 'InvalidArgument',\r\n 'SubTransaction',\r\n 'Unsupported',\r\n 'Internal',\r\n 'DatabaseClosed',\r\n 'PrematureCommit',\r\n 'ForeignAwait'\r\n];\r\n\r\nvar idbDomErrorNames = [\r\n 'Unknown',\r\n 'Constraint',\r\n 'Data',\r\n 'TransactionInactive',\r\n 'ReadOnly',\r\n 'Version',\r\n 'NotFound',\r\n 'InvalidState',\r\n 'InvalidAccess',\r\n 'Abort',\r\n 'Timeout',\r\n 'QuotaExceeded',\r\n 'Syntax',\r\n 'DataClone'\r\n];\r\n\r\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\r\n\r\nvar defaultTexts = {\r\n VersionChanged: \"Database version changed by other database connection\",\r\n DatabaseClosed: \"Database has been closed\",\r\n Abort: \"Transaction aborted\",\r\n TransactionInactive: \"Transaction has already completed or failed\"\r\n};\r\n\r\n//\r\n// DexieError - base class of all out exceptions.\r\n//\r\nexport function DexieError (name, msg) {\r\n // Reason we don't use ES6 classes is because:\r\n // 1. It bloats transpiled code and increases size of minified code.\r\n // 2. It doesn't give us much in this case.\r\n // 3. It would require sub classes to call super(), which\r\n // is not needed when deriving from Error.\r\n this._e = getErrorWithStack();\r\n this.name = name;\r\n this.message = msg;\r\n}\r\n\r\nderive(DexieError).from(Error).extend({\r\n stack: {\r\n get: function() {\r\n return this._stack ||\r\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\r\n }\r\n },\r\n toString: function(){ return this.name + \": \" + this.message; }\r\n});\r\n\r\nfunction getMultiErrorMessage (msg, failures) {\r\n return msg + \". Errors: \" + failures\r\n .map(f=>f.toString())\r\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\r\n .join('\\n');\r\n}\r\n\r\n//\r\n// ModifyError - thrown in Collection.modify()\r\n// Specific constructor because it contains members failures and failedKeys.\r\n//\r\nexport function ModifyError (msg, failures, successCount, failedKeys) {\r\n this._e = getErrorWithStack();\r\n this.failures = failures;\r\n this.failedKeys = failedKeys;\r\n this.successCount = successCount;\r\n}\r\nderive(ModifyError).from(DexieError);\r\n\r\nexport function BulkError (msg, failures) {\r\n this._e = getErrorWithStack();\r\n this.name = \"BulkError\";\r\n this.failures = failures;\r\n this.message = getMultiErrorMessage(msg, failures);\r\n}\r\nderive(BulkError).from(DexieError);\r\n\r\n//\r\n//\r\n// Dynamically generate error names and exception classes based\r\n// on the names in errorList.\r\n//\r\n//\r\n\r\n// Map of {ErrorName -> ErrorName + \"Error\"}\r\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\r\n\r\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\r\nconst BaseException = DexieError;\r\n// Map of {ErrorName -> exception constructor}\r\nexport var exceptions = errorList.reduce((obj,name)=>{\r\n // Let the name be \"DexieError\" because this name may\r\n // be shown in call stack and when debugging. DexieError is\r\n // the most true name because it derives from DexieError,\r\n // and we cannot change Function.name programatically without\r\n // dynamically create a Function object, which would be considered\r\n // 'eval-evil'.\r\n var fullName = name + \"Error\";\r\n function DexieError (msgOrInner, inner){\r\n this._e = getErrorWithStack();\r\n this.name = fullName;\r\n if (!msgOrInner) {\r\n this.message = defaultTexts[name] || fullName;\r\n this.inner = null;\r\n } else if (typeof msgOrInner === 'string') {\r\n this.message = msgOrInner;\r\n this.inner = inner || null;\r\n } else if (typeof msgOrInner === 'object') {\r\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\r\n this.inner = msgOrInner;\r\n }\r\n }\r\n derive(DexieError).from(BaseException);\r\n obj[name]=DexieError;\r\n return obj;\r\n},{});\r\n\r\n// Use ECMASCRIPT standard exceptions where applicable:\r\nexceptions.Syntax = SyntaxError;\r\nexceptions.Type = TypeError;\r\nexceptions.Range = RangeError;\r\n\r\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\r\n obj[name + \"Error\"] = exceptions[name];\r\n return obj;\r\n}, {});\r\n\r\nexport function mapError (domError, message) {\r\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\r\n return domError;\r\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\r\n if (\"stack\" in domError) {\r\n // Derive stack from inner exception if it has a stack\r\n setProp(rv, \"stack\", {get: function(){\r\n return this.inner.stack;\r\n }});\r\n }\r\n return rv;\r\n}\r\n\r\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\r\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\r\n obj[name + \"Error\"] = exceptions[name];\r\n return obj;\r\n}, {});\r\n\r\nfullNameExceptions.ModifyError = ModifyError;\r\nfullNameExceptions.DexieError = DexieError;\r\nfullNameExceptions.BulkError = BulkError;\r\n","import {extend} from './utils';\r\n\r\nexport function nop() { }\r\nexport function mirror(val) { return val; }\r\nexport function pureFunctionChain(f1, f2) {\r\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\r\n // This pattern is used in the hook(\"reading\") event.\r\n if (f1 == null || f1 === mirror) return f2;\r\n return function (val) {\r\n return f2(f1(val));\r\n };\r\n}\r\n\r\nexport function callBoth(on1, on2) {\r\n return function () {\r\n on1.apply(this, arguments);\r\n on2.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function hookCreatingChain(f1, f2) {\r\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\r\n // This pattern is used in the hook(\"creating\") event.\r\n if (f1 === nop) return f2;\r\n return function () {\r\n var res = f1.apply(this, arguments);\r\n if (res !== undefined) arguments[0] = res;\r\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\r\n onerror = this.onerror; // In case event listener has set this.onerror\r\n this.onsuccess = null;\r\n this.onerror = null;\r\n var res2 = f2.apply(this, arguments);\r\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\r\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\r\n return res2 !== undefined ? res2 : res;\r\n };\r\n}\r\n\r\nexport function hookDeletingChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n f1.apply(this, arguments);\r\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\r\n onerror = this.onerror; // In case event listener has set this.onerror\r\n this.onsuccess = this.onerror = null;\r\n f2.apply(this, arguments);\r\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\r\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\r\n };\r\n}\r\n\r\nexport function hookUpdatingChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function (modifications) {\r\n var res = f1.apply(this, arguments);\r\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\r\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\r\n onerror = this.onerror; // In case event listener has set this.onerror\r\n this.onsuccess = null;\r\n this.onerror = null;\r\n var res2 = f2.apply(this, arguments);\r\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\r\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\r\n return res === undefined ?\r\n (res2 === undefined ? undefined : res2) :\r\n (extend(res, res2));\r\n };\r\n}\r\n\r\nexport function reverseStoppableEventChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n if (f2.apply(this, arguments) === false) return false;\r\n return f1.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function nonStoppableEventChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n f1.apply(this, arguments);\r\n f2.apply(this, arguments);\r\n };\r\n}\r\n\r\nexport function promisableChain(f1, f2) {\r\n if (f1 === nop) return f2;\r\n return function () {\r\n var res = f1.apply(this, arguments);\r\n if (res && typeof res.then === 'function') {\r\n var thiz = this,\r\n i = arguments.length,\r\n args = new Array(i);\r\n while (i--) args[i] = arguments[i];\r\n return res.then(function () {\r\n return f2.apply(thiz, args);\r\n });\r\n }\r\n return f2.apply(this, arguments);\r\n };\r\n}\r\n","import {doFakeAutoComplete, tryCatch, props, setProp, _global,\r\n getPropertyDescriptor, getArrayOf, extend} from './utils';\r\nimport {nop, callBoth, mirror} from './chaining-functions';\r\nimport {debug, prettyStack, getErrorWithStack} from './debug';\r\nimport {exceptions} from './errors';\r\n\r\n//\r\n// Promise and Zone (PSD) for Dexie library\r\n//\r\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\r\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\r\n//\r\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\r\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\r\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\r\n// engine that is indexedDB compliant across all browsers.\r\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\r\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\r\n//\r\n// Specific non-standard features of this Promise class:\r\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\r\n// native async / await.\r\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\r\n// and below + all promises that those promises creates or awaits.\r\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \r\n//\r\n// David Fahlander, https://github.com/dfahlander\r\n//\r\n\r\n// Just a pointer that only this module knows about.\r\n// Used in Promise constructor to emulate a private constructor.\r\nvar INTERNAL = {};\r\n\r\n// Async stacks (long stacks) must not grow infinitely.\r\nconst\r\n LONG_STACKS_CLIP_LIMIT = 100,\r\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \r\n MAX_LONG_STACKS = 20,\r\n ZONE_ECHO_LIMIT = 7,\r\n nativePromiseInstanceAndProto = (()=>{\r\n try {\r\n // Be able to patch native async functions\r\n return new Function(`let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];`)();\r\n } catch(e) {\r\n var P = _global.Promise;\r\n return P ?\r\n [P.resolve(), P.prototype, P.resolve()] :\r\n []; \r\n }\r\n })(),\r\n resolvedNativePromise = nativePromiseInstanceAndProto[0],\r\n nativePromiseProto = nativePromiseInstanceAndProto[1],\r\n resolvedGlobalPromise = nativePromiseInstanceAndProto[2],\r\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\r\n\r\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\r\nexport const AsyncFunction = nativePromiseInstanceAndProto[3];\r\nconst patchGlobalPromise = !!resolvedGlobalPromise;\r\n\r\nvar stack_being_generated = false;\r\n\r\n/* The default function used only for the very first promise in a promise chain.\r\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\r\n emulated in this module. For indexedDB compatibility, this means that every method needs to \r\n execute at least one promise before doing an indexedDB operation. Dexie will always call \r\n db.ready().then() for every operation to make sure the indexedDB event is started in an\r\n indexedDB-compatible emulated micro task loop.\r\n*/\r\nvar schedulePhysicalTick = resolvedGlobalPromise ?\r\n () => {resolvedGlobalPromise.then(physicalTick);}\r\n :\r\n _global.setImmediate ? \r\n // setImmediate supported. Those modern platforms also supports Function.bind().\r\n setImmediate.bind(null, physicalTick) :\r\n _global.MutationObserver ?\r\n // MutationObserver supported\r\n () => {\r\n var hiddenDiv = document.createElement(\"div\");\r\n (new MutationObserver(() => {\r\n physicalTick();\r\n hiddenDiv = null;\r\n })).observe(hiddenDiv, { attributes: true });\r\n hiddenDiv.setAttribute('i', '1');\r\n } :\r\n // No support for setImmediate or MutationObserver. No worry, setTimeout is only called\r\n // once time. Every tick that follows will be our emulated micro tick.\r\n // Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug \r\n ()=>{setTimeout(physicalTick,0);};\r\n\r\n// Configurable through Promise.scheduler.\r\n// Don't export because it would be unsafe to let unknown\r\n// code call it unless they do try..catch within their callback.\r\n// This function can be retrieved through getter of Promise.scheduler though,\r\n// but users must not do Promise.scheduler = myFuncThatThrowsException\r\nvar asap = function (callback, args) {\r\n microtickQueue.push([callback, args]);\r\n if (needsNewPhysicalTick) {\r\n schedulePhysicalTick();\r\n needsNewPhysicalTick = false;\r\n }\r\n};\r\n\r\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\r\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\r\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\r\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\r\n currentFulfiller = null,\r\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\r\n \r\nexport var globalPSD = {\r\n id: 'global',\r\n global: true,\r\n ref: 0,\r\n unhandleds: [],\r\n onunhandled: globalError,\r\n pgp: false,\r\n env: {},\r\n finalize: function () {\r\n this.unhandleds.forEach(uh => {\r\n try {\r\n globalError(uh[0], uh[1]);\r\n } catch (e) {}\r\n });\r\n }\r\n};\r\n\r\nexport var PSD = globalPSD;\r\n\r\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\r\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\r\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\r\n\r\nexport default function Promise(fn) {\r\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \r\n this._listeners = [];\r\n this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.\r\n \r\n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\r\n // execute the microtask engine implicitely within the call to resolve() or reject().\r\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\r\n // only contains library code when calling resolve() or reject().\r\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\r\n // global scope (event handler, timer etc)!\r\n this._lib = false;\r\n // Current async scope\r\n var psd = (this._PSD = PSD);\r\n\r\n if (debug) {\r\n this._stackHolder = getErrorWithStack();\r\n this._prev = null;\r\n this._numPrev = 0; // Number of previous promises (for long stacks)\r\n }\r\n \r\n if (typeof fn !== 'function') {\r\n if (fn !== INTERNAL) throw new TypeError('Not a function');\r\n // Private constructor (INTERNAL, state, value).\r\n // Used internally by Promise.resolve() and Promise.reject().\r\n this._state = arguments[1];\r\n this._value = arguments[2];\r\n if (this._state === false)\r\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\r\n return;\r\n }\r\n \r\n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\r\n this._value = null; // error or result\r\n ++psd.ref; // Refcounting current scope\r\n executePromiseTask(this, fn);\r\n}\r\n\r\n// Prepare a property descriptor to put onto Promise.prototype.then\r\nconst thenProp = {\r\n get: function() {\r\n var psd = PSD, microTaskId = totalEchoes;\r\n\r\n function then (onFulfilled, onRejected) {\r\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\r\n if (possibleAwait) decrementExpectedAwaits();\r\n var rv = new Promise((resolve, reject) => {\r\n propagateToListener(this, new Listener(\r\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait),\r\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait),\r\n resolve,\r\n reject,\r\n psd));\r\n });\r\n debug && linkToPreviousPromise(rv, this);\r\n return rv;\r\n }\r\n\r\n then.prototype = INTERNAL; // For idempotense, see setter below.\r\n\r\n return then;\r\n },\r\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\r\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\r\n set: function (value) {\r\n setProp (this, 'then', value && value.prototype === INTERNAL ?\r\n thenProp : // Restore to original property descriptor.\r\n {\r\n get: function(){\r\n return value; // Getter returning provided value (behaves like value is just changed)\r\n },\r\n set: thenProp.set // Keep a setter that is prepared to restore original.\r\n }\r\n );\r\n }\r\n};\r\n\r\nprops(Promise.prototype, {\r\n then: thenProp, // Defined above.\r\n _then: function (onFulfilled, onRejected) {\r\n // A little tinier version of then() that don't have to create a resulting promise.\r\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \r\n },\r\n\r\n catch: function (onRejected) {\r\n if (arguments.length === 1) return this.then(null, onRejected);\r\n // First argument is the Error type to catch\r\n var type = arguments[0],\r\n handler = arguments[1];\r\n return typeof type === 'function' ? this.then(null, err =>\r\n // Catching errors by its constructor type (similar to java / c++ / c#)\r\n // Sample: promise.catch(TypeError, function (e) { ... });\r\n err instanceof type ? handler(err) : PromiseReject(err))\r\n : this.then(null, err =>\r\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\r\n // is always DOMError but where e.name tells the actual error type.\r\n // Sample: promise.catch('ConstraintError', function (e) { ... });\r\n err && err.name === type ? handler(err) : PromiseReject(err));\r\n },\r\n\r\n finally: function (onFinally) {\r\n return this.then(value => {\r\n onFinally();\r\n return value;\r\n }, err => {\r\n onFinally();\r\n return PromiseReject(err);\r\n });\r\n },\r\n \r\n stack: {\r\n get: function() {\r\n if (this._stack) return this._stack;\r\n try {\r\n stack_being_generated = true;\r\n var stacks = getStack (this, [], MAX_LONG_STACKS);\r\n var stack = stacks.join(\"\\nFrom previous: \");\r\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\r\n return stack;\r\n } finally {\r\n stack_being_generated = false;\r\n }\r\n }\r\n },\r\n\r\n timeout: function (ms, msg) {\r\n return ms < Infinity ?\r\n new Promise((resolve, reject) => {\r\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\r\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\r\n }) : this;\r\n }\r\n});\r\n\r\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\r\n setProp(Promise.prototype, Symbol.toStringTag, 'Promise');\r\n\r\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\r\n// Environment globals snapshotted on leaving global zone\r\nglobalPSD.env = snapShot();\r\n\r\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\r\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\r\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n this.psd = zone;\r\n}\r\n\r\n// Promise Static Properties\r\nprops (Promise, {\r\n all: function () {\r\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\r\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \r\n return new Promise(function (resolve, reject) {\r\n if (values.length === 0) resolve([]);\r\n var remaining = values.length;\r\n values.forEach((a,i) => Promise.resolve(a).then(x => {\r\n values[i] = x;\r\n if (!--remaining) resolve(values);\r\n }, reject));\r\n });\r\n },\r\n \r\n resolve: value => {\r\n if (value instanceof Promise) return value;\r\n if (value && typeof value.then === 'function') return new Promise((resolve, reject)=>{\r\n value.then(resolve, reject);\r\n });\r\n var rv = new Promise(INTERNAL, true, value);\r\n linkToPreviousPromise(rv, currentFulfiller);\r\n return rv;\r\n },\r\n \r\n reject: PromiseReject,\r\n \r\n race: function () {\r\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\r\n return new Promise((resolve, reject) => {\r\n values.map(value => Promise.resolve(value).then(resolve, reject));\r\n });\r\n },\r\n\r\n PSD: {\r\n get: ()=>PSD,\r\n set: value => PSD = value\r\n },\r\n\r\n //totalEchoes: {get: ()=>totalEchoes},\r\n\r\n //task: {get: ()=>task},\r\n \r\n newPSD: newScope,\r\n \r\n usePSD: usePSD,\r\n \r\n scheduler: {\r\n get: () => asap,\r\n set: value => {asap = value}\r\n },\r\n \r\n rejectionMapper: {\r\n get: () => rejectionMapper,\r\n set: value => {rejectionMapper = value;} // Map reject failures\r\n },\r\n \r\n follow: (fn, zoneProps) => {\r\n return new Promise((resolve, reject) => {\r\n return newScope((resolve, reject) => {\r\n var psd = PSD;\r\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\r\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\r\n psd.finalize = callBoth(function () {\r\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\r\n // examined upon scope completion while unhandled rejections in this Promise\r\n // will trigger directly through psd.onunhandled\r\n run_at_end_of_this_or_next_physical_tick(()=>{\r\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\r\n });\r\n }, psd.finalize);\r\n fn();\r\n }, zoneProps, resolve, reject);\r\n });\r\n }\r\n});\r\n\r\n/**\r\n* Take a potentially misbehaving resolver function and make sure\r\n* onFulfilled and onRejected are only called once.\r\n*\r\n* Makes no guarantees about asynchrony.\r\n*/\r\nfunction executePromiseTask (promise, fn) {\r\n // Promise Resolution Procedure:\r\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\r\n try {\r\n fn(value => {\r\n if (promise._state !== null) return; // Already settled\r\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\r\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\r\n if (value && typeof value.then === 'function') {\r\n executePromiseTask(promise, (resolve, reject) => {\r\n value instanceof Promise ?\r\n value._then(resolve, reject) :\r\n value.then(resolve, reject);\r\n });\r\n } else {\r\n promise._state = true;\r\n promise._value = value;\r\n propagateAllListeners(promise);\r\n }\r\n if (shouldExecuteTick) endMicroTickScope();\r\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\r\n } catch (ex) {\r\n handleRejection(promise, ex);\r\n }\r\n}\r\n\r\nfunction handleRejection (promise, reason) {\r\n rejectingErrors.push(reason);\r\n if (promise._state !== null) return;\r\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\r\n reason = rejectionMapper(reason);\r\n promise._state = false;\r\n promise._value = reason;\r\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\r\n var origProp = getPropertyDescriptor(reason, \"stack\"); \r\n reason._promise = promise; \r\n setProp(reason, \"stack\", {\r\n get: () =>\r\n stack_being_generated ?\r\n origProp && (origProp.get ?\r\n origProp.get.apply(reason) :\r\n origProp.value) :\r\n promise.stack\r\n });\r\n });\r\n // Add the failure to a list of possibly uncaught errors\r\n addPossiblyUnhandledError(promise);\r\n propagateAllListeners(promise);\r\n if (shouldExecuteTick) endMicroTickScope();\r\n}\r\n\r\nfunction propagateAllListeners (promise) {\r\n //debug && linkToPreviousPromise(promise);\r\n var listeners = promise._listeners;\r\n promise._listeners = [];\r\n for (var i = 0, len = listeners.length; i < len; ++i) {\r\n propagateToListener(promise, listeners[i]);\r\n }\r\n var psd = promise._PSD;\r\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\r\n if (numScheduledCalls === 0) {\r\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\r\n // and that no deferreds where listening to this rejection or success.\r\n // Since there is a risk that our stack can contain application code that may\r\n // do stuff after this code is finished that may generate new calls, we cannot\r\n // call finalizers here.\r\n ++numScheduledCalls;\r\n asap(()=>{\r\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\r\n }, []);\r\n }\r\n}\r\n\r\nfunction propagateToListener(promise, listener) {\r\n if (promise._state === null) {\r\n promise._listeners.push(listener);\r\n return;\r\n }\r\n\r\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\r\n if (cb === null) {\r\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()\r\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\r\n }\r\n ++listener.psd.ref;\r\n ++numScheduledCalls;\r\n asap (callListener, [cb, promise, listener]);\r\n}\r\n\r\nfunction callListener (cb, promise, listener) {\r\n try {\r\n // Set static variable currentFulfiller to the promise that is being fullfilled,\r\n // so that we connect the chain of promises (for long stacks support)\r\n currentFulfiller = promise;\r\n \r\n // Call callback and resolve our listener with it's return value.\r\n var ret, value = promise._value;\r\n \r\n if (promise._state) {\r\n // cb is onResolved\r\n ret = cb (value);\r\n } else {\r\n // cb is onRejected\r\n if (rejectingErrors.length) rejectingErrors = [];\r\n ret = cb(value);\r\n if (rejectingErrors.indexOf(value) === -1)\r\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\r\n }\r\n listener.resolve(ret);\r\n } catch (e) {\r\n // Exception thrown in callback. Reject our listener.\r\n listener.reject(e);\r\n } finally {\r\n // Restore env and currentFulfiller.\r\n currentFulfiller = null;\r\n if (--numScheduledCalls === 0) finalizePhysicalTick();\r\n --listener.psd.ref || listener.psd.finalize();\r\n }\r\n}\r\n\r\nfunction getStack (promise, stacks, limit) {\r\n if (stacks.length === limit) return stacks;\r\n var stack = \"\";\r\n if (promise._state === false) {\r\n var failure = promise._value,\r\n errorName,\r\n message;\r\n \r\n if (failure != null) {\r\n errorName = failure.name || \"Error\";\r\n message = failure.message || failure;\r\n stack = prettyStack(failure, 0);\r\n } else {\r\n errorName = failure; // If error is undefined or null, show that.\r\n message = \"\";\r\n }\r\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\r\n }\r\n if (debug) {\r\n stack = prettyStack(promise._stackHolder, 2);\r\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\r\n if (promise._prev) getStack(promise._prev, stacks, limit);\r\n }\r\n return stacks;\r\n}\r\n\r\nfunction linkToPreviousPromise(promise, prev) {\r\n // Support long stacks by linking to previous completed promise.\r\n var numPrev = prev ? prev._numPrev + 1 : 0;\r\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\r\n promise._prev = prev;\r\n promise._numPrev = numPrev;\r\n }\r\n}\r\n\r\n/* The callback to schedule with setImmediate() or setTimeout().\r\n It runs a virtual microtick and executes any callback registered in microtickQueue.\r\n */\r\nfunction physicalTick() {\r\n beginMicroTickScope() && endMicroTickScope();\r\n}\r\n\r\nfunction beginMicroTickScope() {\r\n var wasRootExec = isOutsideMicroTick;\r\n isOutsideMicroTick = false;\r\n needsNewPhysicalTick = false;\r\n return wasRootExec;\r\n}\r\n\r\n/* Executes micro-ticks without doing try..catch.\r\n This can be possible because we only use this internally and\r\n the registered functions are exception-safe (they do try..catch\r\n internally before calling any external method). If registering\r\n functions in the microtickQueue that are not exception-safe, this\r\n would destroy the framework and make it instable. So we don't export\r\n our asap method.\r\n*/\r\nfunction endMicroTickScope() {\r\n var callbacks, i, l;\r\n do {\r\n while (microtickQueue.length > 0) {\r\n callbacks = microtickQueue;\r\n microtickQueue = [];\r\n l = callbacks.length;\r\n for (i = 0; i < l; ++i) {\r\n var item = callbacks[i];\r\n item[0].apply(null, item[1]);\r\n }\r\n }\r\n } while (microtickQueue.length > 0);\r\n isOutsideMicroTick = true;\r\n needsNewPhysicalTick = true;\r\n}\r\n\r\nfunction finalizePhysicalTick() {\r\n var unhandledErrs = unhandledErrors;\r\n unhandledErrors = [];\r\n unhandledErrs.forEach(p => {\r\n p._PSD.onunhandled.call(null, p._value, p);\r\n });\r\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\r\n var i = finalizers.length;\r\n while (i) finalizers[--i](); \r\n}\r\n\r\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\r\n function finalizer() {\r\n fn();\r\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\r\n }\r\n tickFinalizers.push(finalizer);\r\n ++numScheduledCalls;\r\n asap(()=>{\r\n if (--numScheduledCalls === 0) finalizePhysicalTick();\r\n }, []);\r\n}\r\n\r\nfunction addPossiblyUnhandledError(promise) {\r\n // Only add to unhandledErrors if not already there. The first one to add to this list\r\n // will be upon the first rejection so that the root cause (first promise in the\r\n // rejection chain) is the one listed.\r\n if (!unhandledErrors.some(p => p._value === promise._value))\r\n unhandledErrors.push(promise);\r\n}\r\n\r\nfunction markErrorAsHandled(promise) {\r\n // Called when a reject handled is actually being called.\r\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\r\n // contains only rejected promises, and only one item per error)\r\n var i = unhandledErrors.length;\r\n while (i) if (unhandledErrors[--i]._value === promise._value) {\r\n // Found a promise that failed with this same error object pointer,\r\n // Remove that since there is a listener that actually takes care of it.\r\n unhandledErrors.splice(i, 1);\r\n return;\r\n }\r\n}\r\n\r\nfunction PromiseReject (reason) {\r\n return new Promise(INTERNAL, false, reason);\r\n}\r\n\r\nexport function wrap (fn, errorCatcher) {\r\n var psd = PSD;\r\n return function() {\r\n var wasRootExec = beginMicroTickScope(),\r\n outerScope = PSD;\r\n\r\n try {\r\n switchToZone(psd, true);\r\n return fn.apply(this, arguments);\r\n } catch (e) {\r\n errorCatcher && errorCatcher(e);\r\n } finally {\r\n switchToZone(outerScope, false);\r\n if (wasRootExec) endMicroTickScope();\r\n }\r\n };\r\n}\r\n\r\n\r\n//\r\n// variables used for native await support\r\n//\r\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\r\nvar taskCounter = 0; // ID counter for macro tasks.\r\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\r\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\r\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\r\n\r\n\r\nvar zone_id_counter = 0;\r\nexport function newScope (fn, props, a1, a2) {\r\n var parent = PSD,\r\n psd = Object.create(parent);\r\n psd.parent = parent;\r\n psd.ref = 0;\r\n psd.global = false;\r\n psd.id = ++zone_id_counter;\r\n // Prepare for promise patching (done in usePSD):\r\n var globalEnv = globalPSD.env;\r\n psd.env = patchGlobalPromise ? {\r\n Promise: Promise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\r\n PromiseProp: {value: Promise, configurable: true, writable: true},\r\n all: Promise.all,\r\n race: Promise.race,\r\n resolve: Promise.resolve,\r\n reject: Promise.reject,\r\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\r\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\r\n } : {};\r\n if (props) extend(psd, props);\r\n \r\n // unhandleds and onunhandled should not be specifically set here.\r\n // Leave them on parent prototype.\r\n // unhandleds.push(err) will push to parent's prototype\r\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\r\n ++parent.ref;\r\n psd.finalize = function () {\r\n --this.parent.ref || this.parent.finalize();\r\n }\r\n var rv = usePSD (psd, fn, a1, a2);\r\n if (psd.ref === 0) psd.finalize();\r\n return rv;\r\n}\r\n\r\n// Function to call if scopeFunc returns NativePromise\r\n// Also for each NativePromise in the arguments to Promise.all()\r\nexport function incrementExpectedAwaits() {\r\n if (!task.id) task.id = ++taskCounter;\r\n ++task.awaits;\r\n task.echoes += ZONE_ECHO_LIMIT;\r\n return task.id;\r\n}\r\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\r\n// Also call this when a native await calls then method on a promise. In that case, don't supply\r\n// sourceTaskId because we already know it refers to current task.\r\nexport function decrementExpectedAwaits(sourceTaskId) {\r\n if (!task.awaits || (sourceTaskId && sourceTaskId !== task.id)) return;\r\n if (--task.awaits === 0) task.id = 0;\r\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\r\n}\r\n\r\n// Call from Promise.all() and Promise.race()\r\nexport function onPossibleParallellAsync (possiblePromise) {\r\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\r\n incrementExpectedAwaits(); \r\n return possiblePromise.then(x => {\r\n decrementExpectedAwaits();\r\n return x;\r\n }, e => {\r\n decrementExpectedAwaits();\r\n return rejection(e);\r\n });\r\n }\r\n return possiblePromise;\r\n}\r\n\r\nfunction zoneEnterEcho(targetZone) {\r\n ++totalEchoes;\r\n if (!task.echoes || --task.echoes === 0) {\r\n task.echoes = task.id = 0; // Cancel zone echoing.\r\n }\r\n\r\n zoneStack.push(PSD);\r\n switchToZone(targetZone, true);\r\n}\r\n\r\nfunction zoneLeaveEcho() {\r\n var zone = zoneStack[zoneStack.length-1];\r\n zoneStack.pop();\r\n switchToZone(zone, false);\r\n}\r\n\r\nfunction switchToZone (targetZone, bEnteringZone) {\r\n var currentZone = PSD;\r\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\r\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\r\n // will be surrounded by the zone when they are invoked.\r\n enqueueNativeMicroTask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\r\n }\r\n if (targetZone === PSD) return;\r\n\r\n PSD = targetZone; // The actual zone switch occurs at this line.\r\n\r\n // Snapshot on every leave from global zone.\r\n if (currentZone === globalPSD) globalPSD.env = snapShot();\r\n\r\n if (patchGlobalPromise) {\r\n // Let's patch the global and native Promises (may be same or may be different)\r\n var GlobalPromise = globalPSD.env.Promise;\r\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\r\n var targetEnv = targetZone.env;\r\n\r\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\r\n // Must be done on each zone change because the patched method contains targetZone in its closure.\r\n nativePromiseProto.then = targetEnv.nthen;\r\n GlobalPromise.prototype.then = targetEnv.gthen;\r\n\r\n if (currentZone.global || targetZone.global) {\r\n // Leaving or entering global zone. It's time to patch / restore global Promise.\r\n\r\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.\r\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\r\n\r\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\r\n // not be accessing global.Promise but a local reference to it)\r\n GlobalPromise.all = targetEnv.all;\r\n GlobalPromise.race = targetEnv.race;\r\n GlobalPromise.resolve = targetEnv.resolve;\r\n GlobalPromise.reject = targetEnv.reject;\r\n }\r\n }\r\n}\r\n\r\nfunction snapShot () {\r\n var GlobalPromise = _global.Promise;\r\n return patchGlobalPromise ? {\r\n Promise: GlobalPromise,\r\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\r\n all: GlobalPromise.all,\r\n race: GlobalPromise.race,\r\n resolve: GlobalPromise.resolve,\r\n reject: GlobalPromise.reject,\r\n nthen: nativePromiseProto.then,\r\n gthen: GlobalPromise.prototype.then\r\n } : {};\r\n}\r\n\r\nexport function usePSD (psd, fn, a1, a2, a3) {\r\n var outerScope = PSD;\r\n try {\r\n switchToZone(psd, true);\r\n return fn(a1, a2, a3);\r\n } finally {\r\n switchToZone(outerScope, false);\r\n }\r\n}\r\n\r\nfunction enqueueNativeMicroTask (job) {\r\n //\r\n // Precondition: nativePromiseThen !== undefined\r\n //\r\n nativePromiseThen.call(resolvedNativePromise, job);\r\n}\r\n\r\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait) {\r\n return typeof fn !== 'function' ? fn : function () {\r\n var outerZone = PSD;\r\n if (possibleAwait) incrementExpectedAwaits();\r\n switchToZone(zone, true);\r\n try {\r\n return fn.apply(this, arguments);\r\n } finally {\r\n switchToZone(outerZone, false);\r\n }\r\n };\r\n}\r\n\r\nfunction getPatchedPromiseThen (origThen, zone) {\r\n return function (onResolved, onRejected) {\r\n return origThen.call(this,\r\n nativeAwaitCompatibleWrap(onResolved, zone, false),\r\n nativeAwaitCompatibleWrap(onRejected, zone, false));\r\n };\r\n}\r\n\r\nconst UNHANDLEDREJECTION = \"unhandledrejection\";\r\n\r\nfunction globalError(err, promise) {\r\n var rv;\r\n try {\r\n rv = promise.onuncatched(err);\r\n } catch (e) {}\r\n if (rv !== false) try {\r\n var event, eventData = {promise: promise, reason: err};\r\n if (_global.document && document.createEvent) {\r\n event = document.createEvent('Event');\r\n event.initEvent(UNHANDLEDREJECTION, true, true);\r\n extend(event, eventData);\r\n } else if (_global.CustomEvent) {\r\n event = new CustomEvent(UNHANDLEDREJECTION, {detail: eventData});\r\n extend(event, eventData);\r\n }\r\n if (event && _global.dispatchEvent) {\r\n dispatchEvent(event);\r\n if (!_global.PromiseRejectionEvent && _global.onunhandledrejection)\r\n // No native support for PromiseRejectionEvent but user has set window.onunhandledrejection. Manually call it.\r\n try {_global.onunhandledrejection(event);} catch (_) {}\r\n }\r\n if (!event.defaultPrevented) {\r\n console.warn(`Unhandled rejection: ${err.stack || err}`);\r\n }\r\n } catch (e) {}\r\n}\r\n\r\ndoFakeAutoComplete(() => {\r\n // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie.\r\n asap = (fn, args) => {\r\n setTimeout(()=>{fn.apply(null, args);}, 0);\r\n };\r\n});\r\n\r\nexport var rejection = Promise.reject;\r\n","import {keys, isArray, asap} from './utils';\r\nimport {nop, mirror, reverseStoppableEventChain} from './chaining-functions';\r\nimport {exceptions} from './errors';\r\n\r\nexport default function Events(ctx) {\r\n var evs = {};\r\n var rv = function (eventName, subscriber) {\r\n if (subscriber) {\r\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\r\n var i = arguments.length, args = new Array(i - 1);\r\n while (--i) args[i - 1] = arguments[i];\r\n evs[eventName].subscribe.apply(null, args);\r\n return ctx;\r\n } else if (typeof (eventName) === 'string') {\r\n // Return interface allowing to fire or unsubscribe from event\r\n return evs[eventName];\r\n }\r\n };\r\n rv.addEventType = add;\r\n \r\n for (var i = 1, l = arguments.length; i < l; ++i) {\r\n add(arguments[i]);\r\n }\r\n \r\n return rv;\r\n\r\n function add(eventName, chainFunction, defaultFunction) {\r\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\r\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\r\n if (!defaultFunction) defaultFunction = nop;\r\n\r\n var context = {\r\n subscribers: [],\r\n fire: defaultFunction,\r\n subscribe: function (cb) {\r\n if (context.subscribers.indexOf(cb) === -1) {\r\n context.subscribers.push(cb);\r\n context.fire = chainFunction(context.fire, cb);\r\n }\r\n },\r\n unsubscribe: function (cb) {\r\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\r\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\r\n }\r\n };\r\n evs[eventName] = rv[eventName] = context;\r\n return context;\r\n }\r\n\r\n function addConfiguredEvents(cfg) {\r\n // events(this, {reading: [functionChain, nop]});\r\n keys(cfg).forEach(function (eventName) {\r\n var args = cfg[eventName];\r\n if (isArray(args)) {\r\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\r\n } else if (args === 'asap') {\r\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\r\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\r\n var context = add(eventName, mirror, function fire() {\r\n // Optimazation-safe cloning of arguments into args.\r\n var i = arguments.length, args = new Array(i);\r\n while (i--) args[i] = arguments[i];\r\n // All each subscriber:\r\n context.subscribers.forEach(function (fn) {\r\n asap(function fireEvent() {\r\n fn.apply(null, args);\r\n });\r\n });\r\n });\r\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\r\n });\r\n }\r\n}\r\n","/*\r\n * Dexie.js - a minimalistic wrapper for IndexedDB\r\n * ===============================================\r\n *\r\n * By David Fahlander, david.fahlander@gmail.com\r\n *\r\n * Version {version}, {date}\r\n *\r\n * http://dexie.org\r\n *\r\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\r\n */\r\n\r\nimport {\r\n keys,\r\n setProp,\r\n isArray,\r\n extend,\r\n props,\r\n derive,\r\n slice,\r\n override,\r\n _global,\r\n doFakeAutoComplete,\r\n asap,\r\n trycatcher,\r\n tryCatch,\r\n getByKeyPath,\r\n setByKeyPath,\r\n delByKeyPath,\r\n shallowClone,\r\n deepClone,\r\n getObjectDiff,\r\n assert,\r\n NO_CHAR_ARRAY,\r\n getArrayOf,\r\n arrayToObject,\r\n hasOwn,\r\n flatten\r\n\r\n} from './utils';\r\nimport { ModifyError, BulkError, errnames, exceptions, fullNameExceptions, mapError } from './errors';\r\nimport Promise, {wrap, PSD, newScope, usePSD, rejection, NativePromise,\r\n incrementExpectedAwaits, decrementExpectedAwaits, AsyncFunction} from './Promise';\r\nimport Events from './Events';\r\nimport {\r\n nop,\r\n mirror,\r\n pureFunctionChain,\r\n hookCreatingChain,\r\n hookUpdatingChain,\r\n hookDeletingChain,\r\n promisableChain\r\n} from './chaining-functions';\r\nimport * as Debug from './debug';\r\n\r\nvar DEXIE_VERSION = '{version}',\r\n maxString = String.fromCharCode(65535),\r\n // maxKey is an Array if indexedDB implementations supports array keys (not supported by IE,Edge or Safari at the moment)\r\n // Otherwise maxKey is maxString. This is handy when needing an open upper border without limit.\r\n maxKey = (function(){try {IDBKeyRange.only([[]]);return [[]];}catch(e){return maxString;}})(),\r\n minKey = -Infinity,\r\n INVALID_KEY_ARGUMENT = \"Invalid key provided. Keys must be of type string, number, Date or Array.\",\r\n STRING_EXPECTED = \"String expected.\",\r\n connections = [],\r\n isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent),\r\n hasIEDeleteObjectStoreBug = isIEOrEdge,\r\n hangsOnDeleteLargeKeyRange = isIEOrEdge,\r\n dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame),\r\n dbNamesDB;// Global database for backing Dexie.getDatabaseNames() on browser without indexedDB.webkitGetDatabaseNames() \r\n\r\n// Init debug\r\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\r\n\r\nexport default function Dexie(dbName, options) {\r\n /// Specify only if you wich to control which addons that should run on this instance\r\n var deps = Dexie.dependencies;\r\n var opts = extend({\r\n // Default Options\r\n addons: Dexie.addons, // Pick statically registered addons by default\r\n autoOpen: true, // Don't require db.open() explicitely.\r\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\r\n IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to browser env.\r\n }, options);\r\n var addons = opts.addons,\r\n autoOpen = opts.autoOpen,\r\n indexedDB = opts.indexedDB,\r\n IDBKeyRange = opts.IDBKeyRange;\r\n\r\n var globalSchema = this._dbSchema = {};\r\n var versions = [];\r\n var dbStoreNames = [];\r\n var allTables = {};\r\n ///\r\n var idbdb = null; // Instance of IDBDatabase\r\n var dbOpenError = null;\r\n var isBeingOpened = false;\r\n var onReadyBeingFired = null;\r\n var openComplete = false;\r\n var READONLY = \"readonly\", READWRITE = \"readwrite\";\r\n var db = this;\r\n var dbReadyResolve,\r\n dbReadyPromise = new Promise(resolve => {\r\n dbReadyResolve = resolve;\r\n }),\r\n cancelOpen,\r\n openCanceller = new Promise((_, reject) => {\r\n cancelOpen = reject;\r\n });\r\n var autoSchema = true;\r\n var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),\r\n hasGetAll;\r\n\r\n function init() {\r\n // Default subscribers to \"versionchange\" and \"blocked\".\r\n // Can be overridden by custom handlers. If custom handlers return false, these default\r\n // behaviours will be prevented.\r\n db.on(\"versionchange\", function (ev) {\r\n // Default behavior for versionchange event is to close database connection.\r\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\r\n // Let's not block the other window from making it's delete() or open() call.\r\n // NOTE! This event is never fired in IE,Edge or Safari.\r\n if (ev.newVersion > 0)\r\n console.warn(`Another connection wants to upgrade database '${db.name}'. Closing db now to resume the upgrade.`);\r\n else\r\n console.warn(`Another connection wants to delete database '${db.name}'. Closing db now to resume the delete request.`);\r\n db.close();\r\n // In many web applications, it would be recommended to force window.reload()\r\n // when this event occurs. To do that, subscribe to the versionchange event\r\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\r\n // The reason for this is that your current web app obviously has old schema code that needs\r\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\r\n // your window is blocking it unless we close it here.\r\n });\r\n db.on(\"blocked\", ev => {\r\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\r\n console.warn(`Dexie.delete('${db.name}') was blocked`);\r\n else\r\n console.warn(`Upgrade '${db.name}' blocked by other connection holding version ${ev.oldVersion/10}`);\r\n });\r\n }\r\n\r\n //\r\n //\r\n //\r\n // ------------------------- Versioning Framework---------------------------\r\n //\r\n //\r\n //\r\n\r\n this.version = function (versionNumber) {\r\n /// \r\n /// \r\n if (idbdb || isBeingOpened) throw new exceptions.Schema(\"Cannot add version when database is open\");\r\n this.verno = Math.max(this.verno, versionNumber);\r\n var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0];\r\n if (versionInstance) return versionInstance;\r\n versionInstance = new Version(versionNumber);\r\n versions.push(versionInstance);\r\n versions.sort(lowerVersionFirst);\r\n // Disable autoschema mode, as at least one version is specified.\r\n autoSchema = false;\r\n return versionInstance;\r\n };\r\n\r\n function Version(versionNumber) {\r\n this._cfg = {\r\n version: versionNumber,\r\n storesSource: null,\r\n dbschema: {},\r\n tables: {},\r\n contentUpgrade: null\r\n };\r\n this.stores({}); // Derive earlier schemas by default.\r\n }\r\n\r\n extend(Version.prototype, {\r\n stores: function (stores) {\r\n /// \r\n /// Defines the schema for a particular version\r\n /// \r\n /// \r\n /// Example:
\r\n /// {users: \"id++,first,last,&username,*email\",
\r\n /// passwords: \"id++,&username\"}
\r\n ///
\r\n /// Syntax: {Table: \"[primaryKey][++],[&][*]index1,[&][*]index2,...\"}

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

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

\r\n /// Special characters:
\r\n /// \"&\" means unique key,
\r\n /// \"*\" means value is multiEntry,
\r\n /// \"++\" means auto-increment and only applicable for primary key
\r\n /// \r\n this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;\r\n\r\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\r\n var storesSpec = {};\r\n versions.forEach(function (version) { // 'versions' is always sorted by lowest version first.\r\n extend(storesSpec, version._cfg.storesSource);\r\n });\r\n\r\n var dbschema = (this._cfg.dbschema = {});\r\n this._parseStoresSpec(storesSpec, dbschema);\r\n // Update the latest schema to this version\r\n // Update API\r\n globalSchema = db._dbSchema = dbschema;\r\n removeTablesApi([allTables, db, Transaction.prototype]); // Keep Transaction.prototype even though it should be depr.\r\n setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\r\n dbStoreNames = keys(dbschema);\r\n return this;\r\n },\r\n upgrade: function (upgradeFunction) {\r\n /// Function that performs upgrading actions.\r\n var self = this;\r\n fakeAutoComplete(function () {\r\n upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema));// BUGBUG: No code completion for prev version's tables wont appear.\r\n });\r\n this._cfg.contentUpgrade = upgradeFunction;\r\n return this;\r\n },\r\n _parseStoresSpec: function (stores, outSchema) {\r\n keys(stores).forEach(function (tableName) {\r\n if (stores[tableName] !== null) {\r\n var instanceTemplate = {};\r\n var indexes = parseIndexSyntax(stores[tableName]);\r\n var primKey = indexes.shift();\r\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\r\n if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);\r\n indexes.forEach(function (idx) {\r\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\r\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\r\n setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () { return \"\"; }) : \"\");\r\n });\r\n outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);\r\n }\r\n });\r\n }\r\n });\r\n \r\n function runUpgraders (oldVersion, idbtrans, reject) {\r\n var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);\r\n trans.create(idbtrans);\r\n trans._completion.catch(reject);\r\n var rejectTransaction = trans._reject.bind(trans);\r\n newScope(function () {\r\n PSD.trans = trans;\r\n if (oldVersion === 0) {\r\n // Create tables:\r\n keys(globalSchema).forEach(function (tableName) {\r\n createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\r\n });\r\n Promise.follow(()=>db.on.populate.fire(trans)).catch(rejectTransaction);\r\n } else\r\n updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);\r\n });\r\n }\r\n\r\n function updateTablesAndIndexes (oldVersion, trans, idbtrans) {\r\n // Upgrade version to version, step-by-step from oldest to newest version.\r\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)\r\n var queue = [];\r\n var oldVersionStruct = versions.filter(version => version._cfg.version === oldVersion)[0];\r\n if (!oldVersionStruct) throw new exceptions.Upgrade(\"Dexie specification of currently installed DB version is missing\");\r\n globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;\r\n var anyContentUpgraderHasRun = false;\r\n\r\n var versToRun = versions.filter(v => v._cfg.version > oldVersion);\r\n versToRun.forEach(function (version) {\r\n /// \r\n queue.push(()=>{\r\n var oldSchema = globalSchema;\r\n var newSchema = version._cfg.dbschema;\r\n adjustToExistingIndexNames(oldSchema, idbtrans);\r\n adjustToExistingIndexNames(newSchema, idbtrans);\r\n globalSchema = db._dbSchema = newSchema;\r\n var diff = getSchemaDiff(oldSchema, newSchema); \r\n // Add tables \r\n diff.add.forEach(function (tuple) {\r\n createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\r\n });\r\n // Change tables\r\n diff.change.forEach(function (change) {\r\n if (change.recreate) {\r\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\r\n } else {\r\n var store = idbtrans.objectStore(change.name);\r\n // Add indexes\r\n change.add.forEach(function (idx) {\r\n addIndex(store, idx);\r\n });\r\n // Update indexes\r\n change.change.forEach(function (idx) {\r\n store.deleteIndex(idx.name);\r\n addIndex(store, idx);\r\n });\r\n // Delete indexes\r\n change.del.forEach(function (idxName) {\r\n store.deleteIndex(idxName);\r\n });\r\n }\r\n });\r\n if (version._cfg.contentUpgrade) {\r\n anyContentUpgraderHasRun = true;\r\n return Promise.follow(()=>{\r\n version._cfg.contentUpgrade(trans);\r\n });\r\n }\r\n });\r\n queue.push(function (idbtrans) {\r\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.\r\n var newSchema = version._cfg.dbschema;\r\n // Delete old tables\r\n deleteRemovedTables(newSchema, idbtrans);\r\n }\r\n });\r\n });\r\n\r\n // Now, create a queue execution engine\r\n function runQueue () {\r\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\r\n Promise.resolve();\r\n }\r\n \r\n return runQueue().then(()=>{\r\n createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\r\n });\r\n }\r\n\r\n function getSchemaDiff(oldSchema, newSchema) {\r\n var diff = {\r\n del: [], // Array of table names\r\n add: [], // Array of [tableName, newDefinition]\r\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\r\n };\r\n for (var table in oldSchema) {\r\n if (!newSchema[table]) diff.del.push(table);\r\n }\r\n for (table in newSchema) {\r\n var oldDef = oldSchema[table],\r\n newDef = newSchema[table];\r\n if (!oldDef) {\r\n diff.add.push([table, newDef]);\r\n } else {\r\n var change = {\r\n name: table,\r\n def: newDef,\r\n recreate: false,\r\n del: [],\r\n add: [],\r\n change: []\r\n };\r\n if (oldDef.primKey.src !== newDef.primKey.src) {\r\n // Primary key has changed. Remove and re-add table.\r\n change.recreate = true;\r\n diff.change.push(change);\r\n } else {\r\n // Same primary key. Just find out what differs:\r\n var oldIndexes = oldDef.idxByName;\r\n var newIndexes = newDef.idxByName;\r\n for (var idxName in oldIndexes) {\r\n if (!newIndexes[idxName]) change.del.push(idxName);\r\n }\r\n for (idxName in newIndexes) {\r\n var oldIdx = oldIndexes[idxName],\r\n newIdx = newIndexes[idxName];\r\n if (!oldIdx) change.add.push(newIdx);\r\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\r\n }\r\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\r\n diff.change.push(change);\r\n }\r\n }\r\n }\r\n }\r\n return diff;\r\n }\r\n\r\n function createTable(idbtrans, tableName, primKey, indexes) {\r\n /// \r\n var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });\r\n indexes.forEach(function (idx) { addIndex(store, idx); });\r\n return store;\r\n }\r\n\r\n function createMissingTables(newSchema, idbtrans) {\r\n keys(newSchema).forEach(function (tableName) {\r\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\r\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\r\n }\r\n });\r\n }\r\n\r\n function deleteRemovedTables(newSchema, idbtrans) {\r\n for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {\r\n var storeName = idbtrans.db.objectStoreNames[i];\r\n if (newSchema[storeName] == null) {\r\n idbtrans.db.deleteObjectStore(storeName);\r\n }\r\n }\r\n }\r\n\r\n function addIndex(store, idx) {\r\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\r\n }\r\n\r\n //\r\n //\r\n // Dexie Protected API\r\n //\r\n //\r\n\r\n this._allTables = allTables;\r\n\r\n this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {\r\n return new Transaction(mode, storeNames, dbschema, parentTransaction);\r\n };\r\n\r\n /* Generate a temporary transaction when db operations are done outside a transaction scope.\r\n */\r\n function tempTransaction(mode, storeNames, fn) { // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\r\n if (!openComplete && (!PSD.letThrough)) {\r\n if (!isBeingOpened) {\r\n if (!autoOpen)\r\n return rejection (new exceptions.DatabaseClosed());\r\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\r\n }\r\n return dbReadyPromise.then(()=>tempTransaction(mode, storeNames, fn));\r\n } else {\r\n var trans = db._createTransaction(mode, storeNames, globalSchema);\r\n try { trans.create(); } catch (ex) { return rejection(ex); }\r\n return trans._promise(mode, function (resolve, reject) {\r\n return newScope(function () { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\r\n PSD.trans = trans;\r\n return fn(resolve, reject, trans);\r\n });\r\n }).then(result => {\r\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\r\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\r\n // Specifically, to ensure that the following expression will work:\r\n //\r\n // db.friends.put({name: \"Arne\"}).then(function () {\r\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\r\n // assert (count === 1);\r\n // });\r\n // });\r\n //\r\n return trans._completion.then(()=>result);\r\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.\r\n trans._reject(err);\r\n return rejection(err);\r\n });*/\r\n }\r\n }\r\n\r\n this._whenReady = function (fn) {\r\n return fake || openComplete || PSD.letThrough ? fn() : new Promise ((resolve, reject) => {\r\n if (!isBeingOpened) {\r\n if (!autoOpen) {\r\n reject(new exceptions.DatabaseClosed());\r\n return;\r\n }\r\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\r\n }\r\n dbReadyPromise.then(resolve, reject);\r\n }).then(fn);\r\n };\r\n \r\n //\r\n //\r\n //\r\n //\r\n // Dexie API\r\n //\r\n //\r\n //\r\n\r\n this.verno = 0;\r\n\r\n this.open = function () {\r\n if (isBeingOpened || idbdb)\r\n return dbReadyPromise.then(()=> dbOpenError ? rejection (dbOpenError) : db);\r\n Debug.debug && (openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\r\n isBeingOpened = true;\r\n dbOpenError = null;\r\n openComplete = false;\r\n \r\n // Function pointers to call when the core opening process completes.\r\n var resolveDbReady = dbReadyResolve,\r\n // upgradeTransaction to abort on failure.\r\n upgradeTransaction = null;\r\n \r\n return Promise.race([openCanceller, new Promise((resolve, reject) => {\r\n doFakeAutoComplete(()=>resolve());\r\n \r\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\r\n // IE fails when deleting objectStore after reading from it.\r\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\r\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.\r\n \r\n // If no API, throw!\r\n if (!indexedDB) throw new exceptions.MissingAPI(\r\n \"indexedDB API not found. If using IE10+, make sure to run your code on a server URL \"+\r\n \"(not locally). If using old Safari versions, make sure to include indexedDB polyfill.\");\r\n \r\n var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));\r\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\r\n req.onerror = eventRejectHandler(reject);\r\n req.onblocked = wrap(fireOnBlocked);\r\n req.onupgradeneeded = wrap (function (e) {\r\n upgradeTransaction = req.transaction;\r\n if (autoSchema && !db._allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\r\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\r\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\r\n // do not create a new database by accident here.\r\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\r\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\r\n // Close database and delete it.\r\n req.result.close();\r\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!\r\n delreq.onsuccess = delreq.onerror = wrap(function () {\r\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\r\n });\r\n } else {\r\n upgradeTransaction.onerror = eventRejectHandler(reject);\r\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\r\n runUpgraders(oldVer / 10, upgradeTransaction, reject, req);\r\n }\r\n }, reject);\r\n \r\n req.onsuccess = wrap (function () {\r\n // Core opening procedure complete. Now let's just record some stuff.\r\n upgradeTransaction = null;\r\n idbdb = req.result;\r\n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\r\n\r\n if (autoSchema) readGlobalSchema();\r\n else if (idbdb.objectStoreNames.length > 0) {\r\n try {\r\n adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));\r\n } catch (e) {\r\n // Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\r\n }\r\n }\r\n \r\n idbdb.onversionchange = wrap(ev => {\r\n db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\r\n db.on(\"versionchange\").fire(ev);\r\n });\r\n \r\n if (!hasNativeGetDatabaseNames && dbName !== '__dbnames') {\r\n dbNamesDB.dbnames.put({name: dbName}).catch(nop);\r\n }\r\n\r\n resolve();\r\n\r\n }, reject);\r\n })]).then(() => {\r\n // Before finally resolving the dbReadyPromise and this promise,\r\n // call and await all on('ready') subscribers:\r\n // Dexie.vip() makes subscribers able to use the database while being opened.\r\n // This is a must since these subscribers take part of the opening procedure.\r\n onReadyBeingFired = [];\r\n return Promise.resolve(Dexie.vip(db.on.ready.fire)).then(function fireRemainders() {\r\n if (onReadyBeingFired.length > 0) {\r\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\r\n let remainders = onReadyBeingFired.reduce(promisableChain, nop);\r\n onReadyBeingFired = [];\r\n return Promise.resolve(Dexie.vip(remainders)).then(fireRemainders)\r\n }\r\n });\r\n }).finally(()=>{\r\n onReadyBeingFired = null;\r\n }).then(()=>{\r\n // Resolve the db.open() with the db instance.\r\n isBeingOpened = false;\r\n return db;\r\n }).catch(err => {\r\n try {\r\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\r\n upgradeTransaction && upgradeTransaction.abort();\r\n } catch (e) { }\r\n isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).\r\n db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\r\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.\r\n dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\r\n return rejection (dbOpenError);\r\n }).finally(()=>{\r\n openComplete = true;\r\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\r\n });\r\n };\r\n \r\n this.close = function () {\r\n var idx = connections.indexOf(db);\r\n if (idx >= 0) connections.splice(idx, 1); \r\n if (idbdb) {\r\n try {idbdb.close();} catch(e){}\r\n idbdb = null;\r\n }\r\n autoOpen = false;\r\n dbOpenError = new exceptions.DatabaseClosed();\r\n if (isBeingOpened)\r\n cancelOpen(dbOpenError);\r\n // Reset dbReadyPromise promise:\r\n dbReadyPromise = new Promise(resolve => {\r\n dbReadyResolve = resolve;\r\n });\r\n openCanceller = new Promise((_, reject) => {\r\n cancelOpen = reject;\r\n });\r\n };\r\n \r\n this.delete = function () {\r\n var hasArguments = arguments.length > 0;\r\n return new Promise(function (resolve, reject) {\r\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\r\n if (isBeingOpened) {\r\n dbReadyPromise.then(doDelete);\r\n } else {\r\n doDelete();\r\n }\r\n function doDelete() {\r\n db.close();\r\n var req = indexedDB.deleteDatabase(dbName);\r\n req.onsuccess = wrap(function () {\r\n if (!hasNativeGetDatabaseNames) {\r\n dbNamesDB.dbnames.delete(dbName).catch(nop);\r\n }\r\n resolve();\r\n });\r\n req.onerror = eventRejectHandler(reject);\r\n req.onblocked = fireOnBlocked;\r\n }\r\n });\r\n };\r\n\r\n this.backendDB = function () {\r\n return idbdb;\r\n };\r\n\r\n this.isOpen = function () {\r\n return idbdb !== null;\r\n };\r\n this.hasBeenClosed = function () {\r\n return dbOpenError && (dbOpenError instanceof exceptions.DatabaseClosed);\r\n }\r\n this.hasFailed = function () {\r\n return dbOpenError !== null;\r\n };\r\n this.dynamicallyOpened = function() {\r\n return autoSchema;\r\n };\r\n\r\n //\r\n // Properties\r\n //\r\n this.name = dbName;\r\n\r\n // db.tables - an array of all Table instances.\r\n props(this, {\r\n tables: {\r\n get () {\r\n /// \r\n return keys(allTables).map(function (name) { return allTables[name]; });\r\n }\r\n }\r\n });\r\n\r\n //\r\n // Events\r\n //\r\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", {ready: [promisableChain, nop]});\r\n\r\n this.on.ready.subscribe = override (this.on.ready.subscribe, function (subscribe) {\r\n return (subscriber, bSticky) => {\r\n Dexie.vip(()=>{\r\n if (openComplete) {\r\n // Database already open. Call subscriber asap.\r\n if (!dbOpenError) Promise.resolve().then(subscriber);\r\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \r\n if (bSticky) subscribe(subscriber);\r\n } else if (onReadyBeingFired) {\r\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\r\n onReadyBeingFired.push(subscriber);\r\n if (bSticky) subscribe(subscriber);\r\n } else {\r\n // Database not yet open. Subscribe to it.\r\n subscribe(subscriber);\r\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\r\n if (!bSticky) subscribe(function unsubscribe() {\r\n db.on.ready.unsubscribe(subscriber);\r\n db.on.ready.unsubscribe(unsubscribe);\r\n });\r\n }\r\n });\r\n }\r\n });\r\n\r\n fakeAutoComplete(function () {\r\n db.on(\"populate\").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));\r\n });\r\n \r\n this.transaction = function () {\r\n /// \r\n ///\r\n /// \r\n /// \"r\" for readonly, or \"rw\" for readwrite\r\n /// Table instance, Array of Table instances, String or String Array of object stores to include in the transaction\r\n /// Function to execute with transaction\r\n\r\n var args = extractTransactionArgs.apply(this, arguments);\r\n return this._transaction.apply(this, args);\r\n }\r\n \r\n function extractTransactionArgs (mode, _tableArgs_, scopeFunc) {\r\n // Let table arguments be all arguments between mode and last argument.\r\n var i = arguments.length;\r\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\r\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\r\n // and clone arguments except the first one into local var 'args'.\r\n var args = new Array(i - 1);\r\n while (--i) args[i-1] = arguments[i];\r\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\r\n scopeFunc = args.pop();\r\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\r\n return [mode, tables, scopeFunc];\r\n }\r\n\r\n this._transaction = function (mode, tables, scopeFunc) {\r\n var parentTransaction = PSD.trans;\r\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\r\n if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;\r\n var onlyIfCompatible = mode.indexOf('?') !== -1;\r\n mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\r\n \r\n try {\r\n //\r\n // Get storeNames from arguments. Either through given table instances, or through given table names.\r\n //\r\n var storeNames = tables.map(table => {\r\n var storeName = table instanceof Table ? table.name : table;\r\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\r\n return storeName;\r\n });\r\n\r\n //\r\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\r\n //\r\n if (mode == \"r\" || mode == READONLY)\r\n mode = READONLY;\r\n else if (mode == \"rw\" || mode == READWRITE)\r\n mode = READWRITE;\r\n else\r\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\r\n\r\n if (parentTransaction) {\r\n // Basic checks\r\n if (parentTransaction.mode === READONLY && mode === READWRITE) {\r\n if (onlyIfCompatible) {\r\n // Spawn new transaction instead.\r\n parentTransaction = null; \r\n }\r\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\r\n }\r\n if (parentTransaction) {\r\n storeNames.forEach(function (storeName) {\r\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\r\n if (onlyIfCompatible) {\r\n // Spawn new transaction instead.\r\n parentTransaction = null; \r\n }\r\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\r\n \" not included in parent transaction.\");\r\n }\r\n });\r\n }\r\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\r\n // '?' mode should not keep using an inactive transaction.\r\n parentTransaction = null;\r\n }\r\n }\r\n } catch (e) {\r\n return parentTransaction ?\r\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\r\n rejection (e);\r\n }\r\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\r\n return (parentTransaction ?\r\n parentTransaction._promise(mode, enterTransactionScope, \"lock\") :\r\n PSD.trans ?\r\n // no parent transaction despite PSD.trans exists. Make sure also\r\n // that the zone we create is not a sub-zone of current, because\r\n // Promise.follow() should not wait for it if so.\r\n usePSD(PSD.transless, ()=>db._whenReady(enterTransactionScope)) :\r\n db._whenReady (enterTransactionScope));\r\n \r\n function enterTransactionScope() {\r\n return Promise.resolve().then(()=>{\r\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\r\n var transless = PSD.transless || PSD;\r\n // Our transaction.\r\n //return new Promise((resolve, reject) => {\r\n var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);\r\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\r\n var zoneProps = {\r\n trans: trans,\r\n transless: transless\r\n };\r\n\r\n if (parentTransaction) {\r\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\r\n trans.idbtrans = parentTransaction.idbtrans;\r\n } else {\r\n trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.\r\n }\r\n\r\n // Support for native async await.\r\n if (scopeFunc.constructor === AsyncFunction) {\r\n incrementExpectedAwaits();\r\n }\r\n\r\n var returnValue;\r\n var promiseFollowed = Promise.follow(()=>{\r\n // Finally, call the scope function with our table and transaction arguments.\r\n returnValue = scopeFunc.call(trans, trans);\r\n if (returnValue) {\r\n if (returnValue.constructor === NativePromise) {\r\n var decrementor = decrementExpectedAwaits.bind(null, null);\r\n returnValue.then(decrementor, decrementor);\r\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\r\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\r\n returnValue = awaitIterator(returnValue);\r\n }\r\n }\r\n }, zoneProps);\r\n return (returnValue && typeof returnValue.then === 'function' ?\r\n // Promise returned. User uses promise-style transactions.\r\n Promise.resolve(returnValue).then(x => trans.active ?\r\n x // Transaction still active. Continue.\r\n : rejection(new exceptions.PrematureCommit(\r\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\r\n // No promise returned. Wait for all outstanding promises before continuing. \r\n : promiseFollowed.then(()=>returnValue)\r\n ).then(x => {\r\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\r\n if (parentTransaction) trans._resolve();\r\n // wait for trans._completion\r\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\r\n return trans._completion.then(()=>x);\r\n }).catch (e => {\r\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\r\n return rejection(e);\r\n });\r\n });\r\n }\r\n };\r\n\r\n this.table = function (tableName) {\r\n /// \r\n if (fake && autoSchema) return new Table(tableName);\r\n if (!hasOwn(allTables, tableName)) { throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\r\n return allTables[tableName];\r\n };\r\n\r\n //\r\n //\r\n //\r\n // Table Class\r\n //\r\n //\r\n //\r\n function Table(name, tableSchema, optionalTrans) {\r\n /// \r\n this.name = name;\r\n this.schema = tableSchema;\r\n this._tx = optionalTrans;\r\n this.hook = allTables[name] ? allTables[name].hook : Events(null, {\r\n \"creating\": [hookCreatingChain, nop],\r\n \"reading\": [pureFunctionChain, mirror],\r\n \"updating\": [hookUpdatingChain, nop],\r\n \"deleting\": [hookDeletingChain, nop]\r\n });\r\n }\r\n\r\n function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {\r\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\r\n errorList.push(e);\r\n done && done();\r\n });\r\n }\r\n\r\n function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {\r\n // If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],\r\n // else keysOrTuples must be just an array of keys: [key1, key2, ...].\r\n return new Promise((resolve, reject)=>{\r\n var len = keysOrTuples.length,\r\n lastItem = len - 1;\r\n if (len === 0) return resolve();\r\n if (!hasDeleteHook) {\r\n for (var i=0; i < len; ++i) {\r\n var req = idbstore.delete(keysOrTuples[i]);\r\n req.onerror = eventRejectHandler(reject);\r\n if (i === lastItem) req.onsuccess = wrap(()=>resolve());\r\n }\r\n } else {\r\n var hookCtx,\r\n errorHandler = hookedEventRejectHandler(reject),\r\n successHandler = hookedEventSuccessHandler(null);\r\n tryCatch(()=> {\r\n for (var i = 0; i < len; ++i) {\r\n hookCtx = {onsuccess: null, onerror: null};\r\n var tuple = keysOrTuples[i];\r\n deletingHook.call(hookCtx, tuple[0], tuple[1], trans);\r\n var req = idbstore.delete(tuple[0]);\r\n req._hookCtx = hookCtx;\r\n req.onerror = errorHandler;\r\n if (i === lastItem)\r\n req.onsuccess = hookedEventSuccessHandler(resolve);\r\n else\r\n req.onsuccess = successHandler;\r\n }\r\n }, err=>{\r\n hookCtx.onerror && hookCtx.onerror(err);\r\n throw err;\r\n });\r\n }\r\n });\r\n } \r\n\r\n props(Table.prototype, {\r\n\r\n //\r\n // Table Protected Methods\r\n //\r\n\r\n _trans: function getTransaction(mode, fn, writeLocked) {\r\n var trans = this._tx || PSD.trans;\r\n return trans && trans.db === db ?\r\n trans === PSD.trans ?\r\n trans._promise (mode, fn, writeLocked) :\r\n newScope(()=>trans._promise(mode, fn, writeLocked), {trans: trans, transless: PSD.transless || PSD}) :\r\n tempTransaction (mode, [this.name], fn);\r\n },\r\n _idbstore: function getIDBObjectStore(mode, fn, writeLocked) {\r\n if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion.\r\n var tableName = this.name;\r\n function supplyIdbStore (resolve, reject, trans) {\r\n if (trans.storeNames.indexOf(tableName) === -1)\r\n throw new exceptions.NotFound(\"Table\" + tableName + \" not part of transaction\");\r\n return fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);\r\n }\r\n return this._trans(mode, supplyIdbStore, writeLocked);\r\n },\r\n\r\n //\r\n // Table Public Methods\r\n //\r\n get: function (keyOrCrit, cb) {\r\n if (keyOrCrit && keyOrCrit.constructor === Object)\r\n return this.where(keyOrCrit).first(cb);\r\n var self = this;\r\n return this._idbstore(READONLY, function (resolve, reject, idbstore) {\r\n fake && resolve(self.schema.instanceTemplate);\r\n var req = idbstore.get(keyOrCrit);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = wrap(function () {\r\n resolve(self.hook.reading.fire(req.result));\r\n }, reject);\r\n }).then(cb);\r\n },\r\n where: function (indexOrCrit) {\r\n if (typeof indexOrCrit === 'string')\r\n return new WhereClause(this, indexOrCrit);\r\n if (isArray(indexOrCrit))\r\n return new WhereClause(this, `[${indexOrCrit.join('+')}]`);\r\n // indexOrCrit is an object map of {[keyPath]:value} \r\n var keyPaths = keys(indexOrCrit);\r\n if (keyPaths.length === 1)\r\n // Only one critera. This was the easy case:\r\n return this\r\n .where(keyPaths[0])\r\n .equals(indexOrCrit[keyPaths[0]]);\r\n \r\n // Multiple criterias.\r\n // Let's try finding a compound index that matches all keyPaths in\r\n // arbritary order:\r\n var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix =>\r\n ix.compound &&\r\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0) &&\r\n ix.keyPath.every(keyPath => keyPaths.indexOf(keyPath) >= 0))[0];\r\n\r\n if (compoundIndex && maxKey !== maxString)\r\n // Cool! We found such compound index\r\n // and this browser supports compound indexes (maxKey !== maxString)!\r\n return this\r\n .where(compoundIndex.name)\r\n .equals(compoundIndex.keyPath.map(kp => indexOrCrit[kp]));\r\n\r\n if (!compoundIndex) console.warn(\r\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\r\n `compound index [${keyPaths.join('+')}]`);\r\n \r\n // Ok, now let's fallback to finding at least one matching index\r\n // and filter the rest.\r\n var idxByName = this.schema.idxByName;\r\n var simpleIndex = keyPaths.reduce((r,keyPath)=>[\r\n r[0] || idxByName[keyPath],\r\n r[0] || !idxByName[keyPath] ?\r\n combine(\r\n r[1],\r\n x =>''+getByKeyPath(x, keyPath) ==\r\n ''+indexOrCrit[keyPath])\r\n : r[1]\r\n ], [null, null]);\r\n \r\n var idx = simpleIndex[0];\r\n return idx ?\r\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\r\n .filter(simpleIndex[1]) :\r\n compoundIndex ?\r\n this.filter(simpleIndex[1]) : // Has compound but browser bad. Allow filter.\r\n this.where(keyPaths).equals(''); // No index at all. Fail lazily.\r\n },\r\n count: function (cb) {\r\n return this.toCollection().count(cb);\r\n },\r\n offset: function (offset) {\r\n return this.toCollection().offset(offset);\r\n },\r\n limit: function (numRows) {\r\n return this.toCollection().limit(numRows);\r\n },\r\n reverse: function () {\r\n return this.toCollection().reverse();\r\n },\r\n filter: function (filterFunction) {\r\n return this.toCollection().and(filterFunction);\r\n },\r\n each: function (fn) {\r\n return this.toCollection().each(fn);\r\n },\r\n toArray: function (cb) {\r\n return this.toCollection().toArray(cb);\r\n },\r\n orderBy: function (index) {\r\n return new Collection(\r\n new WhereClause(this, isArray(index) ?\r\n `[${index.join('+')}]` :\r\n index));\r\n },\r\n\r\n toCollection: function () {\r\n return new Collection(new WhereClause(this));\r\n },\r\n\r\n mapToClass: function (constructor, structure) {\r\n /// \r\n /// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making\r\n /// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.\r\n /// \r\n /// Constructor function representing the class.\r\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\r\n /// know what type each member has. Example: {name: String, emailAddresses: [String], password}\r\n this.schema.mappedClass = constructor;\r\n var instanceTemplate = Object.create(constructor.prototype);\r\n if (structure) {\r\n // structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.\r\n applyStructure(instanceTemplate, structure);\r\n }\r\n this.schema.instanceTemplate = instanceTemplate;\r\n\r\n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\r\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\r\n var readHook = function (obj) {\r\n if (!obj) return obj; // No valid object. (Value is null). Return as is.\r\n // Create a new object that derives from constructor:\r\n var res = Object.create(constructor.prototype);\r\n // Clone members:\r\n for (var m in obj) if (hasOwn(obj, m)) try {res[m] = obj[m];} catch(_){}\r\n return res;\r\n };\r\n\r\n if (this.schema.readHook) {\r\n this.hook.reading.unsubscribe(this.schema.readHook);\r\n }\r\n this.schema.readHook = readHook;\r\n this.hook(\"reading\", readHook);\r\n return constructor;\r\n },\r\n defineClass: function (structure) {\r\n /// \r\n /// Define all members of the class that represents the table. This will help code completion of when objects are read from the database\r\n /// as well as making it possible to extend the prototype of the returned constructor function.\r\n /// \r\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\r\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\r\n return this.mapToClass(Dexie.defineClass(structure), structure);\r\n },\r\n\r\n bulkDelete: function (keys) {\r\n if (this.hook.deleting.fire === nop) {\r\n return this._idbstore(READWRITE, (resolve, reject, idbstore, trans) => {\r\n resolve (bulkDelete(idbstore, trans, keys, false, nop));\r\n });\r\n } else {\r\n return this\r\n .where(':id')\r\n .anyOf(keys)\r\n .delete()\r\n .then(()=>{}); // Resolve with undefined.\r\n }\r\n },\r\n bulkPut: function(objects, keys) {\r\n return this._idbstore(READWRITE, (resolve, reject, idbstore) => {\r\n if (!idbstore.keyPath && !this.schema.primKey.auto && !keys)\r\n throw new exceptions.InvalidArgument(\"bulkPut() with non-inbound keys requires keys array in second argument\");\r\n if (idbstore.keyPath && keys)\r\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\r\n if (keys && keys.length !== objects.length)\r\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\r\n if (objects.length === 0) return resolve(); // Caller provided empty list.\r\n const done = result => {\r\n if (errorList.length === 0) resolve(result);\r\n else reject(new BulkError(`${this.name}.bulkPut(): ${errorList.length} of ${numObjs} operations failed`, errorList));\r\n };\r\n var req,\r\n errorList = [],\r\n errorHandler,\r\n numObjs = objects.length,\r\n table = this;\r\n if (this.hook.creating.fire === nop && this.hook.updating.fire === nop) {\r\n //\r\n // Standard Bulk (no 'creating' or 'updating' hooks to care about)\r\n //\r\n errorHandler = BulkErrorHandlerCatchAll(errorList);\r\n for (var i = 0, l = objects.length; i < l; ++i) {\r\n req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);\r\n req.onerror = errorHandler;\r\n }\r\n // Only need to catch success or error on the last operation\r\n // according to the IDB spec.\r\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\r\n req.onsuccess = eventSuccessHandler(done);\r\n } else {\r\n var effectiveKeys = keys || idbstore.keyPath && objects.map(o=>getByKeyPath(o, idbstore.keyPath));\r\n // Generate map of {[key]: object}\r\n var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, (key, i) => key != null && [key, objects[i]]); \r\n var promise = !effectiveKeys ?\r\n\r\n // Auto-incremented key-less objects only without any keys argument.\r\n table.bulkAdd(objects) :\r\n\r\n // Keys provided. Either as inbound in provided objects, or as a keys argument.\r\n // Begin with updating those that exists in DB:\r\n table.where(':id').anyOf(effectiveKeys.filter(key => key != null)).modify(function () {\r\n this.value = objectLookup[this.primKey];\r\n objectLookup[this.primKey] = null; // Mark as \"don't add this\"\r\n }).catch(ModifyError, e => {\r\n errorList = e.failures; // No need to concat here. These are the first errors added.\r\n }).then(()=> {\r\n // Now, let's examine which items didnt exist so we can add them:\r\n var objsToAdd = [],\r\n keysToAdd = keys && [];\r\n // Iterate backwards. Why? Because if same key was used twice, just add the last one.\r\n for (var i=effectiveKeys.length-1; i>=0; --i) {\r\n var key = effectiveKeys[i];\r\n if (key == null || objectLookup[key]) {\r\n objsToAdd.push(objects[i]);\r\n keys && keysToAdd.push(key);\r\n if (key != null) objectLookup[key] = null; // Mark as \"dont add again\"\r\n }\r\n }\r\n // The items are in reverse order so reverse them before adding.\r\n // Could be important in order to get auto-incremented keys the way the caller\r\n // would expect. Could have used unshift instead of push()/reverse(),\r\n // but: http://jsperf.com/unshift-vs-reverse\r\n objsToAdd.reverse();\r\n keys && keysToAdd.reverse();\r\n return table.bulkAdd(objsToAdd, keysToAdd);\r\n }).then(lastAddedKey => {\r\n // Resolve with key of the last object in given arguments to bulkPut():\r\n var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.\r\n return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;\r\n });\r\n\r\n promise.then(done).catch(BulkError, e => {\r\n // Concat failure from ModifyError and reject using our 'done' method.\r\n errorList = errorList.concat(e.failures);\r\n done();\r\n }).catch(reject);\r\n }\r\n }, \"locked\"); // If called from transaction scope, lock transaction til all steps are done.\r\n },\r\n bulkAdd: function(objects, keys) {\r\n var self = this,\r\n creatingHook = this.hook.creating.fire;\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\r\n if (!idbstore.keyPath && !self.schema.primKey.auto && !keys)\r\n throw new exceptions.InvalidArgument(\"bulkAdd() with non-inbound keys requires keys array in second argument\");\r\n if (idbstore.keyPath && keys)\r\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\r\n if (keys && keys.length !== objects.length)\r\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\r\n if (objects.length === 0) return resolve(); // Caller provided empty list.\r\n function done(result) {\r\n if (errorList.length === 0) resolve(result);\r\n else reject(new BulkError(`${self.name}.bulkAdd(): ${errorList.length} of ${numObjs} operations failed`, errorList));\r\n }\r\n var req,\r\n errorList = [],\r\n errorHandler,\r\n successHandler,\r\n numObjs = objects.length;\r\n if (creatingHook !== nop) {\r\n //\r\n // There are subscribers to hook('creating')\r\n // Must behave as documented.\r\n //\r\n var keyPath = idbstore.keyPath,\r\n hookCtx;\r\n errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);\r\n successHandler = hookedEventSuccessHandler(null);\r\n\r\n tryCatch(() => {\r\n for (var i=0, l = objects.length; i < l; ++i) {\r\n hookCtx = { onerror: null, onsuccess: null };\r\n var key = keys && keys[i];\r\n var obj = objects[i],\r\n effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,\r\n keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);\r\n if (effectiveKey == null && keyToUse != null) {\r\n if (keyPath) {\r\n obj = deepClone(obj);\r\n setByKeyPath(obj, keyPath, keyToUse);\r\n } else {\r\n key = keyToUse;\r\n }\r\n }\r\n req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\r\n req._hookCtx = hookCtx;\r\n if (i < l - 1) {\r\n req.onerror = errorHandler;\r\n if (hookCtx.onsuccess)\r\n req.onsuccess = successHandler;\r\n }\r\n }\r\n }, err => {\r\n hookCtx.onerror && hookCtx.onerror(err);\r\n throw err;\r\n });\r\n\r\n req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);\r\n req.onsuccess = hookedEventSuccessHandler(done);\r\n } else {\r\n //\r\n // Standard Bulk (no 'creating' hook to care about)\r\n //\r\n errorHandler = BulkErrorHandlerCatchAll(errorList);\r\n for (var i = 0, l = objects.length; i < l; ++i) {\r\n req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);\r\n req.onerror = errorHandler;\r\n }\r\n // Only need to catch success or error on the last operation\r\n // according to the IDB spec.\r\n req.onerror = BulkErrorHandlerCatchAll(errorList, done);\r\n req.onsuccess = eventSuccessHandler(done);\r\n }\r\n });\r\n },\r\n add: function (obj, key) {\r\n /// \r\n /// Add an object to the database. In case an object with same primary key already exists, the object will not be added.\r\n /// \r\n /// A javascript object to insert\r\n /// Primary key\r\n var creatingHook = this.hook.creating.fire;\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {\r\n var hookCtx = {onsuccess: null, onerror: null};\r\n if (creatingHook !== nop) {\r\n var effectiveKey = (key != null) ? key : (idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined);\r\n var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when(\"creating\") to generate the key.\r\n if (effectiveKey == null && keyToUse != null) { // Using \"==\" and \"!=\" to check for either null or undefined!\r\n if (idbstore.keyPath)\r\n setByKeyPath(obj, idbstore.keyPath, keyToUse);\r\n else\r\n key = keyToUse;\r\n }\r\n }\r\n try {\r\n var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);\r\n req._hookCtx = hookCtx;\r\n req.onerror = hookedEventRejectHandler(reject);\r\n req.onsuccess = hookedEventSuccessHandler(function (result) {\r\n // TODO: Remove these two lines in next major release (2.0?)\r\n // It's no good practice to have side effects on provided parameters\r\n var keyPath = idbstore.keyPath;\r\n if (keyPath) setByKeyPath(obj, keyPath, result);\r\n resolve(result);\r\n });\r\n } catch (e) {\r\n if (hookCtx.onerror) hookCtx.onerror(e);\r\n throw e;\r\n }\r\n });\r\n },\r\n\r\n put: function (obj, key) {\r\n /// \r\n /// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.\r\n /// \r\n /// A javascript object to insert or update\r\n /// Primary key\r\n var creatingHook = this.hook.creating.fire,\r\n updatingHook = this.hook.updating.fire;\r\n if (creatingHook !== nop || updatingHook !== nop) {\r\n //\r\n // People listens to when(\"creating\") or when(\"updating\") events!\r\n // We must know whether the put operation results in an CREATE or UPDATE.\r\n //\r\n var keyPath = this.schema.primKey.keyPath;\r\n var effectiveKey = (key !== undefined) ? key : (keyPath && getByKeyPath(obj, keyPath));\r\n if (effectiveKey == null) // \"== null\" means checking for either null or undefined.\r\n return this.add(obj);\r\n \r\n // Since key is optional, make sure we get it from obj if not provided\r\n \r\n // Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().\r\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.\r\n obj = deepClone(obj);\r\n return this._trans(READWRITE, () =>\r\n this.where(\":id\").equals(effectiveKey).modify(function () {\r\n // Replace extisting value with our object\r\n // CRUD event firing handled in Collection.modify()\r\n this.value = obj;\r\n }).then(count => count === 0 ? this.add(obj, key) : effectiveKey),\r\n \"locked\"); // Lock needed because operation is splitted into modify() and add().\r\n } else {\r\n // Use the standard IDB put() method.\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\r\n var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = wrap(function (ev) {\r\n var keyPath = idbstore.keyPath;\r\n if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);\r\n resolve(req.result);\r\n });\r\n });\r\n }\r\n },\r\n\r\n 'delete': function (key) {\r\n /// Primary key of the object to delete\r\n if (this.hook.deleting.subscribers.length) {\r\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\r\n // call the CRUD event. Only Collection.delete() will know whether an object was actually deleted.\r\n return this.where(\":id\").equals(key).delete();\r\n } else {\r\n // No one listens. Use standard IDB delete() method.\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\r\n var req = idbstore.delete(key);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = wrap(function () {\r\n resolve(req.result);\r\n });\r\n });\r\n }\r\n },\r\n\r\n clear: function () {\r\n if (this.hook.deleting.subscribers.length) {\r\n // People listens to when(\"deleting\") event. Must implement delete using Collection.delete() that will\r\n // call the CRUD event. Only Collection.delete() will knows which objects that are actually deleted.\r\n return this.toCollection().delete();\r\n } else {\r\n return this._idbstore(READWRITE, function (resolve, reject, idbstore) {\r\n var req = idbstore.clear();\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = wrap(function () {\r\n resolve(req.result);\r\n });\r\n });\r\n }\r\n },\r\n\r\n update: function (keyOrObject, modifications) {\r\n if (typeof modifications !== 'object' || isArray(modifications))\r\n throw new exceptions.InvalidArgument(\"Modifications must be an object.\");\r\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\r\n // object to modify. Also modify given object with the modifications:\r\n keys(modifications).forEach(function (keyPath) {\r\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\r\n });\r\n var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\r\n if (key === undefined) return rejection (new exceptions.InvalidArgument(\r\n \"Given object does not contain its primary key\"));\r\n return this.where(\":id\").equals(key).modify(modifications);\r\n } else {\r\n // key to modify\r\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\r\n }\r\n }\r\n });\r\n \r\n //\r\n //\r\n //\r\n // Transaction Class\r\n //\r\n //\r\n //\r\n function Transaction(mode, storeNames, dbschema, parent) {\r\n /// \r\n /// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.\r\n /// \r\n /// Any of \"readwrite\" or \"readonly\"\r\n /// Array of table names to operate on\r\n this.db = db;\r\n this.mode = mode;\r\n this.storeNames = storeNames;\r\n this.idbtrans = null;\r\n this.on = Events(this, \"complete\", \"error\", \"abort\");\r\n this.parent = parent || null;\r\n this.active = true;\r\n this._reculock = 0;\r\n this._blockedFuncs = [];\r\n this._resolve = null;\r\n this._reject = null;\r\n this._waitingFor = null;\r\n this._waitingQueue = null;\r\n this._spinCount = 0; // Just for debugging waitFor()\r\n this._completion = new Promise ((resolve, reject) => {\r\n this._resolve = resolve;\r\n this._reject = reject;\r\n });\r\n \r\n this._completion.then(\r\n ()=> {\r\n this.active = false;\r\n this.on.complete.fire();\r\n },\r\n e => {\r\n var wasActive = this.active;\r\n this.active = false;\r\n this.on.error.fire(e);\r\n this.parent ?\r\n this.parent._reject(e) :\r\n wasActive && this.idbtrans && this.idbtrans.abort();\r\n return rejection(e); // Indicate we actually DO NOT catch this error.\r\n });\r\n }\r\n\r\n props(Transaction.prototype, {\r\n //\r\n // Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)\r\n //\r\n _lock: function () {\r\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\r\n // Temporary set all requests into a pending queue if they are called before database is ready.\r\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\r\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\r\n return this;\r\n },\r\n _unlock: function () {\r\n assert (!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\r\n if (--this._reculock === 0) {\r\n if (!PSD.global) PSD.lockOwnerFor = null;\r\n while (this._blockedFuncs.length > 0 && !this._locked()) {\r\n var fnAndPSD = this._blockedFuncs.shift();\r\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\r\n }\r\n }\r\n return this;\r\n },\r\n _locked: function () {\r\n // Checks if any write-lock is applied on this transaction.\r\n // To simplify the Dexie API for extension implementations, we support recursive locks.\r\n // This is accomplished by using \"Promise Specific Data\" (PSD).\r\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\r\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\r\n // * callback given to the Promise() constructor (function (resolve, reject){...})\r\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\r\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.\r\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\r\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\r\n return this._reculock && PSD.lockOwnerFor !== this;\r\n },\r\n create: function (idbtrans) {\r\n if (!this.mode) return this;\r\n assert(!this.idbtrans);\r\n if (!idbtrans && !idbdb) {\r\n switch (dbOpenError && dbOpenError.name) {\r\n case \"DatabaseClosedError\":\r\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\r\n throw new exceptions.DatabaseClosed(dbOpenError);\r\n case \"MissingAPIError\":\r\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\r\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\r\n default:\r\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\r\n throw new exceptions.OpenFailed(dbOpenError);\r\n }\r\n }\r\n if (!this.active) throw new exceptions.TransactionInactive();\r\n assert(this._completion._state === null);\r\n\r\n idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);\r\n idbtrans.onerror = wrap(ev => {\r\n preventDefault(ev);// Prohibit default bubbling to window.error\r\n this._reject(idbtrans.error);\r\n });\r\n idbtrans.onabort = wrap(ev => {\r\n preventDefault(ev);\r\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\r\n this.active = false;\r\n this.on(\"abort\").fire(ev);\r\n });\r\n idbtrans.oncomplete = wrap(() => {\r\n this.active = false;\r\n this._resolve();\r\n });\r\n return this;\r\n },\r\n _promise: function (mode, fn, bWriteLock) {\r\n\r\n if (mode === READWRITE && this.mode !== READWRITE)\r\n return rejection (new exceptions.ReadOnly(\"Transaction is readonly\"));\r\n\r\n if (!this.active)\r\n return rejection (new exceptions.TransactionInactive());\r\n\r\n if (this._locked()) {\r\n return new Promise((resolve, reject) => {\r\n this._blockedFuncs.push([() => {\r\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\r\n }, PSD]);\r\n });\r\n\r\n } else if (bWriteLock) {\r\n return newScope(()=>{\r\n var p = new Promise((resolve, reject) => {\r\n this._lock();\r\n var rv = fn(resolve, reject, this);\r\n if (rv && rv.then) rv.then(resolve, reject);\r\n });\r\n p.finally(()=>this._unlock());\r\n p._lib = true;\r\n return p;\r\n });\r\n\r\n } else {\r\n var p = new Promise((resolve, reject) => {\r\n var rv = fn(resolve, reject, this);\r\n if (rv && rv.then) rv.then(resolve, reject);\r\n });\r\n p._lib = true;\r\n return p;\r\n }\r\n },\r\n\r\n _root: function () {\r\n return this.parent ? this.parent._root() : this;\r\n },\r\n\r\n waitFor (promise) {\r\n // Always operate on the root transaction (in case this is a sub stransaction)\r\n var root = this._root();\r\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\r\n // (We must be able to call .then() on it.)\r\n promise = Promise.resolve(promise);\r\n if (root._waitingFor) {\r\n // Already called waitFor(). Wait for both to complete.\r\n root._waitingFor = root._waitingFor.then(()=>promise);\r\n } else {\r\n // We're not in waiting state. Start waiting state.\r\n root._waitingFor = promise;\r\n root._waitingQueue = [];\r\n // Start interacting with indexedDB until promise completes:\r\n var store = root.idbtrans.objectStore(root.storeNames[0]);\r\n (function spin(){\r\n ++root._spinCount; // For debugging only\r\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\r\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\r\n }());\r\n }\r\n var currentWaitPromise = root._waitingFor;\r\n return new Promise ((resolve, reject) => {\r\n promise.then (\r\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\r\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\r\n ).finally(() => {\r\n if (root._waitingFor === currentWaitPromise) {\r\n // No one added a wait after us. Safe to stop the spinning.\r\n root._waitingFor = null;\r\n }\r\n });\r\n });\r\n },\r\n\r\n //\r\n // Transaction Public Properties and Methods\r\n //\r\n abort: function () {\r\n this.active && this._reject(new exceptions.Abort());\r\n this.active = false;\r\n },\r\n\r\n tables: {\r\n get: Debug.deprecated (\"Transaction.tables\", ()=>allTables)\r\n },\r\n\r\n table: function (name) {\r\n var table = db.table(name); // Don't check that table is part of transaction. It must fail lazily!\r\n return new Table(name, table.schema, this);\r\n }\r\n });\r\n\r\n //\r\n //\r\n //\r\n // WhereClause\r\n //\r\n //\r\n //\r\n function WhereClause(table, index, orCollection) {\r\n /// \r\n /// \r\n /// \r\n this._ctx = {\r\n table: table,\r\n index: index === \":id\" ? null : index,\r\n or: orCollection\r\n };\r\n }\r\n\r\n props(WhereClause.prototype, function () {\r\n\r\n // WhereClause private methods\r\n\r\n function fail(collectionOrWhereClause, err, T) {\r\n var collection = collectionOrWhereClause instanceof WhereClause ?\r\n new Collection (collectionOrWhereClause) :\r\n collectionOrWhereClause;\r\n \r\n collection._ctx.error = T ? new T(err) : new TypeError(err);\r\n return collection;\r\n }\r\n\r\n function emptyCollection(whereClause) {\r\n return new Collection (whereClause, function() { return IDBKeyRange.only(\"\"); }).limit(0);\r\n }\r\n\r\n function upperFactory(dir) {\r\n return dir === \"next\" ? function (s) { return s.toUpperCase(); } : function (s) { return s.toLowerCase(); };\r\n }\r\n function lowerFactory(dir) {\r\n return dir === \"next\" ? function (s) { return s.toLowerCase(); } : function (s) { return s.toUpperCase(); };\r\n }\r\n function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\r\n var length = Math.min(key.length, lowerNeedle.length);\r\n var llp = -1;\r\n for (var i = 0; i < length; ++i) {\r\n var lwrKeyChar = lowerKey[i];\r\n if (lwrKeyChar !== lowerNeedle[i]) {\r\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\r\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\r\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\r\n return null;\r\n }\r\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\r\n }\r\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\r\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\r\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\r\n }\r\n\r\n function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {\r\n /// \r\n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\r\n needlesLen = needles.length;\r\n if (!needles.every(s => typeof s === 'string')) {\r\n return fail(whereClause, STRING_EXPECTED);\r\n }\r\n function initDirection(dir) {\r\n upper = upperFactory(dir);\r\n lower = lowerFactory(dir);\r\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\r\n var needleBounds = needles.map(function (needle){\r\n return {lower: lower(needle), upper: upper(needle)};\r\n }).sort(function(a,b) {\r\n return compare(a.lower, b.lower);\r\n });\r\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\r\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\r\n direction = dir;\r\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\r\n }\r\n initDirection(\"next\");\r\n\r\n var c = new Collection (whereClause, function() {\r\n return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix);\r\n });\r\n\r\n c._ondirectionchange = function (direction) {\r\n // This event onlys occur before filter is called the first time.\r\n initDirection(direction);\r\n };\r\n\r\n var firstPossibleNeedle = 0;\r\n\r\n c._addAlgorithm(function (cursor, advance, resolve) {\r\n /// \r\n /// \r\n /// \r\n var key = cursor.key;\r\n if (typeof key !== 'string') return false;\r\n var lowerKey = lower(key);\r\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\r\n return true;\r\n } else {\r\n var lowestPossibleCasing = null;\r\n for (var i=firstPossibleNeedle; i 0) {\r\n lowestPossibleCasing = casing;\r\n }\r\n }\r\n if (lowestPossibleCasing !== null) {\r\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\r\n } else {\r\n advance(resolve);\r\n }\r\n return false;\r\n }\r\n });\r\n return c;\r\n }\r\n\r\n //\r\n // WhereClause public methods\r\n //\r\n return {\r\n between: function (lower, upper, includeLower, includeUpper) {\r\n /// \r\n /// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.\r\n /// \r\n /// \r\n /// \r\n /// Whether items that equals lower should be included. Default true.\r\n /// Whether items that equals upper should be included. Default false.\r\n /// \r\n includeLower = includeLower !== false; // Default to true\r\n includeUpper = includeUpper === true; // Default to false\r\n try {\r\n if ((cmp(lower, upper) > 0) ||\r\n (cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\r\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.\r\n return new Collection (this, function() { return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper); });\r\n } catch (e) {\r\n return fail(this, INVALID_KEY_ARGUMENT);\r\n }\r\n },\r\n equals: function (value) {\r\n return new Collection (this, function() { return IDBKeyRange.only(value); });\r\n },\r\n above: function (value) {\r\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value, true); });\r\n },\r\n aboveOrEqual: function (value) {\r\n return new Collection (this, function() { return IDBKeyRange.lowerBound(value); });\r\n },\r\n below: function (value) {\r\n return new Collection (this, function() { return IDBKeyRange.upperBound(value, true); });\r\n },\r\n belowOrEqual: function (value) {\r\n return new Collection (this, function() { return IDBKeyRange.upperBound(value); });\r\n },\r\n startsWith: function (str) {\r\n /// \r\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\r\n return this.between(str, str + maxString, true, true);\r\n },\r\n startsWithIgnoreCase: function (str) {\r\n /// \r\n if (str === \"\") return this.startsWith(str);\r\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString);\r\n },\r\n equalsIgnoreCase: function (str) {\r\n /// \r\n return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], \"\");\r\n },\r\n anyOfIgnoreCase: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n if (set.length === 0) return emptyCollection(this);\r\n return addIgnoreCaseAlgorithm(this, function (x, a) { return a.indexOf(x) !== -1; }, set, \"\");\r\n },\r\n startsWithAnyOfIgnoreCase: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n if (set.length === 0) return emptyCollection(this);\r\n return addIgnoreCaseAlgorithm(this, function (x, a) {\r\n return a.some(function(n){\r\n return x.indexOf(n) === 0;\r\n });}, set, maxString);\r\n },\r\n anyOf: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n var compare = ascending;\r\n try { set.sort(compare); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT); }\r\n if (set.length === 0) return emptyCollection(this);\r\n var c = new Collection (this, function () { return IDBKeyRange.bound(set[0], set[set.length - 1]); });\r\n\r\n c._ondirectionchange = function (direction) {\r\n compare = (direction === \"next\" ? ascending : descending);\r\n set.sort(compare);\r\n };\r\n var i = 0;\r\n c._addAlgorithm(function (cursor, advance, resolve) {\r\n var key = cursor.key;\r\n while (compare(key, set[i]) > 0) {\r\n // The cursor has passed beyond this key. Check next.\r\n ++i;\r\n if (i === set.length) {\r\n // There is no next. Stop searching.\r\n advance(resolve);\r\n return false;\r\n }\r\n }\r\n if (compare(key, set[i]) === 0) {\r\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.\r\n return true;\r\n } else {\r\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\r\n advance(function () { cursor.continue(set[i]); });\r\n return false;\r\n }\r\n });\r\n return c;\r\n },\r\n\r\n notEqual: function(value) {\r\n return this.inAnyRange([[minKey, value],[value, maxKey]], {includeLowers: false, includeUppers: false});\r\n },\r\n\r\n noneOf: function() {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n if (set.length === 0) return new Collection (this); // Return entire collection.\r\n try { set.sort(ascending); } catch(e) { return fail(this, INVALID_KEY_ARGUMENT);}\r\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\r\n var ranges = set.reduce(function (res, val) { return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; }, null);\r\n ranges.push([set[set.length - 1], maxKey]);\r\n return this.inAnyRange(ranges, {includeLowers: false, includeUppers: false});\r\n },\r\n\r\n /** Filter out values withing given set of ranges.\r\n * Example, give children and elders a rebate of 50%:\r\n *\r\n * db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});\r\n *\r\n * @param {(string|number|Date|Array)[][]} ranges\r\n * @param {{includeLowers: boolean, includeUppers: boolean}} options\r\n */\r\n inAnyRange: function (ranges, options) {\r\n if (ranges.length === 0) return emptyCollection(this);\r\n if (!ranges.every(function (range) { return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;})) {\r\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);\r\n }\r\n var includeLowers = !options || options.includeLowers !== false; // Default to true\r\n var includeUppers = options && options.includeUppers === true; // Default to false\r\n\r\n function addRange (ranges, newRange) {\r\n for (var i=0,l=ranges.length;i 0) {\r\n range[0] = min(range[0], newRange[0]);\r\n range[1] = max(range[1], newRange[1]);\r\n break;\r\n }\r\n }\r\n if (i === l)\r\n ranges.push(newRange);\r\n return ranges;\r\n }\r\n\r\n var sortDirection = ascending;\r\n function rangeSorter(a,b) { return sortDirection(a[0], b[0]);}\r\n\r\n // Join overlapping ranges\r\n var set;\r\n try {\r\n set = ranges.reduce(addRange, []);\r\n set.sort(rangeSorter);\r\n } catch(ex) {\r\n return fail(this, INVALID_KEY_ARGUMENT);\r\n }\r\n\r\n var i = 0;\r\n var keyIsBeyondCurrentEntry = includeUppers ?\r\n function(key) { return ascending(key, set[i][1]) > 0; } :\r\n function(key) { return ascending(key, set[i][1]) >= 0; };\r\n\r\n var keyIsBeforeCurrentEntry = includeLowers ?\r\n function(key) { return descending(key, set[i][0]) > 0; } :\r\n function(key) { return descending(key, set[i][0]) >= 0; };\r\n\r\n function keyWithinCurrentRange (key) {\r\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\r\n }\r\n\r\n var checkKey = keyIsBeyondCurrentEntry;\r\n\r\n var c = new Collection (this, function () {\r\n return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);\r\n });\r\n\r\n c._ondirectionchange = function (direction) {\r\n if (direction === \"next\") {\r\n checkKey = keyIsBeyondCurrentEntry;\r\n sortDirection = ascending;\r\n } else {\r\n checkKey = keyIsBeforeCurrentEntry;\r\n sortDirection = descending;\r\n }\r\n set.sort(rangeSorter);\r\n };\r\n\r\n c._addAlgorithm(function (cursor, advance, resolve) {\r\n var key = cursor.key;\r\n while (checkKey(key)) {\r\n // The cursor has passed beyond this key. Check next.\r\n ++i;\r\n if (i === set.length) {\r\n // There is no next. Stop searching.\r\n advance(resolve);\r\n return false;\r\n }\r\n }\r\n if (keyWithinCurrentRange(key)) {\r\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.\r\n return true;\r\n } else if (cmp(key,set[i][1]) === 0 || cmp(key,set[i][0]) === 0) {\r\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\r\n // Continue to next key but don't include this one.\r\n return false;\r\n } else {\r\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\r\n advance(function() {\r\n if (sortDirection === ascending) cursor.continue(set[i][0]);\r\n else cursor.continue(set[i][1]);\r\n });\r\n return false;\r\n }\r\n });\r\n return c;\r\n },\r\n startsWithAnyOf: function () {\r\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\r\n\r\n if (!set.every(function (s) { return typeof s === 'string'; })) {\r\n return fail(this, \"startsWithAnyOf() only works with strings\");\r\n }\r\n if (set.length === 0) return emptyCollection(this);\r\n\r\n return this.inAnyRange(set.map(function(str) {\r\n return [str, str + maxString];\r\n }));\r\n }\r\n };\r\n });\r\n\r\n\r\n\r\n\r\n //\r\n //\r\n //\r\n // Collection Class\r\n //\r\n //\r\n //\r\n function Collection(whereClause, keyRangeGenerator) {\r\n /// \r\n ///\r\n /// \r\n /// Where clause instance\r\n /// \r\n var keyRange = null, error = null;\r\n if (keyRangeGenerator) try {\r\n keyRange = keyRangeGenerator();\r\n } catch (ex) {\r\n error = ex;\r\n }\r\n\r\n var whereCtx = whereClause._ctx,\r\n table = whereCtx.table;\r\n this._ctx = {\r\n table: table,\r\n index: whereCtx.index,\r\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\r\n range: keyRange,\r\n keysOnly: false,\r\n dir: \"next\",\r\n unique: \"\",\r\n algorithm: null,\r\n filter: null,\r\n replayFilter: null,\r\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\r\n isMatch: null,\r\n offset: 0,\r\n limit: Infinity,\r\n error: error, // If set, any promise must be rejected with this error\r\n or: whereCtx.or,\r\n valueMapper: table.hook.reading.fire\r\n };\r\n }\r\n \r\n function isPlainKeyRange (ctx, ignoreLimitFilter) {\r\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\r\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\r\n } \r\n\r\n props(Collection.prototype, function () {\r\n\r\n //\r\n // Collection Private Functions\r\n //\r\n\r\n function addFilter(ctx, fn) {\r\n ctx.filter = combine(ctx.filter, fn);\r\n }\r\n\r\n function addReplayFilter (ctx, factory, isLimitFilter) {\r\n var curr = ctx.replayFilter;\r\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\r\n ctx.justLimit = isLimitFilter && !curr;\r\n }\r\n\r\n function addMatchFilter(ctx, fn) {\r\n ctx.isMatch = combine(ctx.isMatch, fn);\r\n }\r\n\r\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string\r\n * }\r\n * @param store IDBObjectStore\r\n **/\r\n function getIndexOrStore(ctx, store) {\r\n if (ctx.isPrimKey) return store;\r\n var indexSpec = ctx.table.schema.idxByName[ctx.index];\r\n if (!indexSpec) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + store.name + \" is not indexed\");\r\n return store.index(indexSpec.name);\r\n }\r\n\r\n /** @param ctx {\r\n * isPrimKey: boolean,\r\n * table: Table,\r\n * index: string,\r\n * keysOnly: boolean,\r\n * range?: IDBKeyRange,\r\n * dir: \"next\" | \"prev\"\r\n * }\r\n */\r\n function openCursor(ctx, store) {\r\n var idxOrStore = getIndexOrStore(ctx, store);\r\n return ctx.keysOnly && 'openKeyCursor' in idxOrStore ?\r\n idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) :\r\n idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);\r\n }\r\n\r\n function iter(ctx, fn, resolve, reject, idbstore) {\r\n var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\r\n if (!ctx.or) {\r\n iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);\r\n } else (()=>{\r\n var set = {};\r\n var resolved = 0;\r\n\r\n function resolveboth() {\r\n if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.\r\n }\r\n\r\n function union(item, cursor, advance) {\r\n if (!filter || filter(cursor, advance, resolveboth, reject)) {\r\n var primaryKey = cursor.primaryKey;\r\n var key = '' + primaryKey;\r\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\r\n if (!hasOwn(set, key)) {\r\n set[key] = true;\r\n fn(item, cursor, advance);\r\n }\r\n }\r\n }\r\n\r\n ctx.or._iterate(union, resolveboth, reject, idbstore);\r\n iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);\r\n })();\r\n }\r\n function getInstanceTemplate(ctx) {\r\n return ctx.table.schema.instanceTemplate;\r\n }\r\n \r\n return {\r\n\r\n //\r\n // Collection Protected Functions\r\n //\r\n\r\n _read: function (fn, cb) {\r\n var ctx = this._ctx;\r\n return ctx.error ?\r\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\r\n ctx.table._idbstore(READONLY, fn).then(cb);\r\n },\r\n _write: function (fn) {\r\n var ctx = this._ctx;\r\n return ctx.error ?\r\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\r\n ctx.table._idbstore(READWRITE, fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\r\n },\r\n _addAlgorithm: function (fn) {\r\n var ctx = this._ctx;\r\n ctx.algorithm = combine(ctx.algorithm, fn);\r\n },\r\n\r\n _iterate: function (fn, resolve, reject, idbstore) {\r\n return iter(this._ctx, fn, resolve, reject, idbstore);\r\n },\r\n\r\n clone: function (props) {\r\n var rv = Object.create(this.constructor.prototype),\r\n ctx = Object.create(this._ctx);\r\n if (props) extend(ctx, props);\r\n rv._ctx = ctx;\r\n return rv;\r\n },\r\n\r\n raw: function () {\r\n this._ctx.valueMapper = null;\r\n return this;\r\n },\r\n\r\n //\r\n // Collection Public methods\r\n //\r\n\r\n each: function (fn) {\r\n var ctx = this._ctx;\r\n\r\n if (fake) {\r\n var item = getInstanceTemplate(ctx),\r\n primKeyPath = ctx.table.schema.primKey.keyPath,\r\n key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath),\r\n primaryKey = getByKeyPath(item, primKeyPath);\r\n fn(item, {key: key, primaryKey: primaryKey});\r\n }\r\n \r\n return this._read(function (resolve, reject, idbstore) {\r\n iter(ctx, fn, resolve, reject, idbstore);\r\n });\r\n },\r\n\r\n count: function (cb) {\r\n if (fake) return Promise.resolve(0).then(cb);\r\n var ctx = this._ctx;\r\n\r\n if (isPlainKeyRange(ctx, true)) {\r\n // This is a plain key range. We can use the count() method if the index.\r\n return this._read(function (resolve, reject, idbstore) {\r\n var idx = getIndexOrStore(ctx, idbstore);\r\n var req = (ctx.range ? idx.count(ctx.range) : idx.count());\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = function (e) {\r\n resolve(Math.min(e.target.result, ctx.limit));\r\n };\r\n }, cb);\r\n } else {\r\n // Algorithms, filters or expressions are applied. Need to count manually.\r\n var count = 0;\r\n return this._read(function (resolve, reject, idbstore) {\r\n iter(ctx, function () { ++count; return false; }, function () { resolve(count); }, reject, idbstore);\r\n }, cb);\r\n }\r\n },\r\n\r\n sortBy: function (keyPath, cb) {\r\n /// \r\n var parts = keyPath.split('.').reverse(),\r\n lastPart = parts[0],\r\n lastIndex = parts.length - 1;\r\n function getval(obj, i) {\r\n if (i) return getval(obj[parts[i]], i - 1);\r\n return obj[lastPart];\r\n }\r\n var order = this._ctx.dir === \"next\" ? 1 : -1;\r\n\r\n function sorter(a, b) {\r\n var aVal = getval(a, lastIndex),\r\n bVal = getval(b, lastIndex);\r\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\r\n }\r\n return this.toArray(function (a) {\r\n return a.sort(sorter);\r\n }).then(cb);\r\n },\r\n\r\n toArray: function (cb) {\r\n var ctx = this._ctx;\r\n return this._read(function (resolve, reject, idbstore) {\r\n fake && resolve([getInstanceTemplate(ctx)]);\r\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\r\n // Special optimation if we could use IDBObjectStore.getAll() or\r\n // IDBKeyRange.getAll():\r\n var readingHook = ctx.table.hook.reading.fire;\r\n var idxOrStore = getIndexOrStore(ctx, idbstore);\r\n var req = ctx.limit < Infinity ?\r\n idxOrStore.getAll(ctx.range, ctx.limit) :\r\n idxOrStore.getAll(ctx.range);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = readingHook === mirror ?\r\n eventSuccessHandler(resolve) :\r\n eventSuccessHandler(res => {\r\n try {resolve (res.map(readingHook));} catch(e) {reject(e);}\r\n });\r\n } else {\r\n // Getting array through a cursor.\r\n var a = [];\r\n iter(ctx, function (item) { a.push(item); }, function arrayComplete() {\r\n resolve(a);\r\n }, reject, idbstore);\r\n }\r\n }, cb);\r\n },\r\n\r\n offset: function (offset) {\r\n var ctx = this._ctx;\r\n if (offset <= 0) return this;\r\n ctx.offset += offset; // For count()\r\n if (isPlainKeyRange(ctx)) {\r\n addReplayFilter(ctx, ()=> {\r\n var offsetLeft = offset;\r\n return (cursor, advance) => {\r\n if (offsetLeft === 0) return true;\r\n if (offsetLeft === 1) { --offsetLeft; return false; }\r\n advance(()=> {\r\n cursor.advance(offsetLeft);\r\n offsetLeft = 0;\r\n });\r\n return false;\r\n };\r\n });\r\n } else {\r\n addReplayFilter(ctx, ()=> {\r\n var offsetLeft = offset;\r\n return () => (--offsetLeft < 0);\r\n });\r\n }\r\n return this;\r\n },\r\n\r\n limit: function (numRows) {\r\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\r\n addReplayFilter(this._ctx, ()=> {\r\n var rowsLeft = numRows;\r\n return function (cursor, advance, resolve) {\r\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\r\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.\r\n };\r\n }, true);\r\n return this;\r\n },\r\n\r\n until: function (filterFunction, bIncludeStopEntry) {\r\n var ctx = this._ctx;\r\n fake && filterFunction(getInstanceTemplate(ctx));\r\n addFilter(this._ctx, function (cursor, advance, resolve) {\r\n if (filterFunction(cursor.value)) {\r\n advance(resolve);\r\n return bIncludeStopEntry;\r\n } else {\r\n return true;\r\n }\r\n });\r\n return this;\r\n },\r\n\r\n first: function (cb) {\r\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\r\n },\r\n\r\n last: function (cb) {\r\n return this.reverse().first(cb);\r\n },\r\n\r\n filter: function (filterFunction) {\r\n /// function(val){return true/false}\r\n fake && filterFunction(getInstanceTemplate(this._ctx));\r\n addFilter(this._ctx, function (cursor) {\r\n return filterFunction(cursor.value);\r\n });\r\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\r\n // collection for a match without querying DB. Used by Dexie.Observable.\r\n addMatchFilter(this._ctx, filterFunction); \r\n return this;\r\n },\r\n \r\n and: function (filterFunction) {\r\n return this.filter(filterFunction);\r\n },\r\n\r\n or: function (indexName) {\r\n return new WhereClause(this._ctx.table, indexName, this);\r\n },\r\n\r\n reverse: function () {\r\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\r\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\r\n return this;\r\n },\r\n\r\n desc: function () {\r\n return this.reverse();\r\n },\r\n\r\n eachKey: function (cb) {\r\n var ctx = this._ctx;\r\n ctx.keysOnly = !ctx.isMatch;\r\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\r\n },\r\n\r\n eachUniqueKey: function (cb) {\r\n this._ctx.unique = \"unique\";\r\n return this.eachKey(cb);\r\n },\r\n \r\n eachPrimaryKey: function (cb) {\r\n var ctx = this._ctx;\r\n ctx.keysOnly = !ctx.isMatch;\r\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\r\n },\r\n\r\n keys: function (cb) {\r\n var ctx = this._ctx;\r\n ctx.keysOnly = !ctx.isMatch;\r\n var a = [];\r\n return this.each(function (item, cursor) {\r\n a.push(cursor.key);\r\n }).then(function () {\r\n return a;\r\n }).then(cb);\r\n },\r\n \r\n primaryKeys: function (cb) {\r\n var ctx = this._ctx;\r\n if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\r\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\r\n // IDBKeyRange.getAllKeys():\r\n return this._read((resolve, reject, idbstore) =>{\r\n var idxOrStore = getIndexOrStore(ctx, idbstore);\r\n var req = ctx.limit < Infinity ?\r\n idxOrStore.getAllKeys(ctx.range, ctx.limit) :\r\n idxOrStore.getAllKeys(ctx.range);\r\n req.onerror = eventRejectHandler(reject);\r\n req.onsuccess = eventSuccessHandler(resolve);\r\n }).then(cb);\r\n }\r\n ctx.keysOnly = !ctx.isMatch;\r\n var a = [];\r\n return this.each(function (item, cursor) {\r\n a.push(cursor.primaryKey);\r\n }).then(function () {\r\n return a;\r\n }).then(cb);\r\n },\r\n\r\n uniqueKeys: function (cb) {\r\n this._ctx.unique = \"unique\";\r\n return this.keys(cb);\r\n },\r\n\r\n firstKey: function (cb) {\r\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\r\n },\r\n\r\n lastKey: function (cb) {\r\n return this.reverse().firstKey(cb);\r\n },\r\n\r\n distinct: function () {\r\n var ctx = this._ctx,\r\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\r\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\r\n var set = {};\r\n addFilter(this._ctx, function (cursor) {\r\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\r\n var found = hasOwn(set, strKey);\r\n set[strKey] = true;\r\n return !found;\r\n });\r\n return this;\r\n },\r\n\r\n //\r\n // Methods that mutate storage\r\n //\r\n\r\n modify: function (changes) {\r\n var self = this,\r\n ctx = this._ctx,\r\n hook = ctx.table.hook,\r\n updatingHook = hook.updating.fire,\r\n deletingHook = hook.deleting.fire;\r\n\r\n fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);\r\n\r\n return this._write(function (resolve, reject, idbstore, trans) {\r\n var modifyer;\r\n if (typeof changes === 'function') {\r\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\r\n if (updatingHook === nop && deletingHook === nop) {\r\n // Noone cares about what is being changed. Just let the modifier function be the given argument as is.\r\n modifyer = changes;\r\n } else {\r\n // People want to know exactly what is being modified or deleted.\r\n // Let modifyer be a proxy function that finds out what changes the caller is actually doing\r\n // and call the hooks accordingly!\r\n modifyer = function (item) {\r\n var origItem = deepClone(item); // Clone the item first so we can compare laters.\r\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)\r\n if (!hasOwn(this, \"value\")) {\r\n // The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.\r\n deletingHook.call(this, this.primKey, item, trans);\r\n } else {\r\n // No deletion. Check what was changed\r\n var objectDiff = getObjectDiff(origItem, this.value);\r\n var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);\r\n if (additionalChanges) {\r\n // Hook want to apply additional modifications. Make sure to fullfill the will of the hook.\r\n item = this.value;\r\n keys(additionalChanges).forEach(function (keyPath) {\r\n setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\r\n });\r\n }\r\n }\r\n };\r\n }\r\n } else if (updatingHook === nop) {\r\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\r\n var keyPaths = keys(changes);\r\n var numKeys = keyPaths.length;\r\n modifyer = function (item) {\r\n var anythingModified = false;\r\n for (var i = 0; i < numKeys; ++i) {\r\n var keyPath = keyPaths[i], val = changes[keyPath];\r\n if (getByKeyPath(item, keyPath) !== val) {\r\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\r\n anythingModified = true;\r\n }\r\n }\r\n return anythingModified;\r\n };\r\n } else {\r\n // changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and\r\n // allow it to add additional modifications to make.\r\n var origChanges = changes;\r\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.\r\n modifyer = function (item) {\r\n var anythingModified = false;\r\n var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);\r\n if (additionalChanges) extend(changes, additionalChanges);\r\n keys(changes).forEach(function (keyPath) {\r\n var val = changes[keyPath];\r\n if (getByKeyPath(item, keyPath) !== val) {\r\n setByKeyPath(item, keyPath, val);\r\n anythingModified = true;\r\n }\r\n });\r\n if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration\r\n return anythingModified;\r\n };\r\n }\r\n\r\n var count = 0;\r\n var successCount = 0;\r\n var iterationComplete = false;\r\n var failures = [];\r\n var failKeys = [];\r\n var currentKey = null;\r\n\r\n function modifyItem(item, cursor) {\r\n currentKey = cursor.primaryKey;\r\n var thisContext = {\r\n primKey: cursor.primaryKey,\r\n value: item,\r\n onsuccess: null,\r\n onerror: null\r\n };\r\n\r\n function onerror(e) {\r\n failures.push(e);\r\n failKeys.push(thisContext.primKey);\r\n checkFinished();\r\n return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction\r\n }\r\n\r\n if (modifyer.call(thisContext, item, thisContext) !== false) { // If a callback explicitely returns false, do not perform the update!\r\n var bDelete = !hasOwn(thisContext, \"value\");\r\n ++count;\r\n tryCatch(function () {\r\n var req = (bDelete ? cursor.delete() : cursor.update(thisContext.value));\r\n req._hookCtx = thisContext;\r\n req.onerror = hookedEventRejectHandler(onerror);\r\n req.onsuccess = hookedEventSuccessHandler(function () {\r\n ++successCount;\r\n checkFinished();\r\n });\r\n }, onerror);\r\n } else if (thisContext.onsuccess) {\r\n // Hook will expect either onerror or onsuccess to always be called!\r\n thisContext.onsuccess(thisContext.value);\r\n }\r\n }\r\n\r\n function doReject(e) {\r\n if (e) {\r\n failures.push(e);\r\n failKeys.push(currentKey);\r\n }\r\n return reject(new ModifyError(\"Error modifying one or more objects\", failures, successCount, failKeys));\r\n }\r\n\r\n function checkFinished() {\r\n if (iterationComplete && successCount + failures.length === count) {\r\n if (failures.length > 0)\r\n doReject();\r\n else\r\n resolve(successCount);\r\n }\r\n }\r\n self.clone().raw()._iterate(modifyItem, function () {\r\n iterationComplete = true;\r\n checkFinished();\r\n }, doReject, idbstore);\r\n });\r\n },\r\n\r\n 'delete': function () {\r\n var ctx = this._ctx,\r\n range = ctx.range,\r\n deletingHook = ctx.table.hook.deleting.fire,\r\n hasDeleteHook = deletingHook !== nop;\r\n if (!hasDeleteHook &&\r\n isPlainKeyRange(ctx) &&\r\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || !range)) // if no range, we'll use clear().\r\n {\r\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\r\n // For chromium, this is the way most optimized version.\r\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\r\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\r\n return this._write((resolve, reject, idbstore) => {\r\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\r\n var onerror = eventRejectHandler(reject),\r\n countReq = (range ? idbstore.count(range) : idbstore.count());\r\n countReq.onerror = onerror;\r\n countReq.onsuccess = () => {\r\n var count = countReq.result;\r\n tryCatch(()=> {\r\n var delReq = (range ? idbstore.delete(range) : idbstore.clear());\r\n delReq.onerror = onerror;\r\n delReq.onsuccess = () => resolve(count);\r\n }, err => reject(err));\r\n };\r\n });\r\n }\r\n\r\n // Default version to use when collection is not a vanilla IDBKeyRange on the primary key.\r\n // Divide into chunks to not starve RAM.\r\n // If has delete hook, we will have to collect not just keys but also objects, so it will use\r\n // more memory and need lower chunk size.\r\n const CHUNKSIZE = hasDeleteHook ? 2000 : 10000;\r\n\r\n return this._write((resolve, reject, idbstore, trans) => {\r\n var totalCount = 0;\r\n // Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.\r\n var collection = this\r\n .clone({\r\n keysOnly: !ctx.isMatch && !hasDeleteHook}) // load just keys (unless filter() or and() or deleteHook has subscribers)\r\n .distinct() // In case multiEntry is used, never delete same key twice because resulting count\r\n // would become larger than actual delete count.\r\n .limit(CHUNKSIZE)\r\n .raw(); // Don't filter through reading-hooks (like mapped classes etc)\r\n\r\n var keysOrTuples = [];\r\n\r\n // We're gonna do things on as many chunks that are needed.\r\n // Use recursion of nextChunk function:\r\n const nextChunk = () => collection.each(hasDeleteHook ? (val, cursor) => {\r\n // Somebody subscribes to hook('deleting'). Collect all primary keys and their values,\r\n // so that the hook can be called with its values in bulkDelete().\r\n keysOrTuples.push([cursor.primaryKey, cursor.value]);\r\n } : (val, cursor) => {\r\n // No one subscribes to hook('deleting'). Collect only primary keys:\r\n keysOrTuples.push(cursor.primaryKey);\r\n }).then(() => {\r\n // Chromium deletes faster when doing it in sort order.\r\n hasDeleteHook ?\r\n keysOrTuples.sort((a, b)=>ascending(a[0], b[0])) :\r\n keysOrTuples.sort(ascending);\r\n return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);\r\n\r\n }).then(()=> {\r\n var count = keysOrTuples.length;\r\n totalCount += count;\r\n keysOrTuples = [];\r\n return count < CHUNKSIZE ? totalCount : nextChunk();\r\n });\r\n\r\n resolve (nextChunk());\r\n });\r\n }\r\n };\r\n });\r\n\r\n\r\n //\r\n //\r\n //\r\n // ------------------------- Help functions ---------------------------\r\n //\r\n //\r\n //\r\n\r\n function lowerVersionFirst(a, b) {\r\n return a._cfg.version - b._cfg.version;\r\n }\r\n\r\n function setApiOnPlace(objs, tableNames, dbschema) {\r\n tableNames.forEach(function (tableName) {\r\n var schema = dbschema[tableName];\r\n objs.forEach(obj => {\r\n if (!(tableName in obj)) {\r\n if (obj === Transaction.prototype || obj instanceof Transaction) {\r\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\r\n // Make the API a getter that returns this.table(tableName)\r\n setProp(obj, tableName, {get() { return this.table(tableName); }});\r\n } else {\r\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\r\n obj[tableName] = new Table(tableName, schema);\r\n }\r\n }\r\n });\r\n });\r\n }\r\n\r\n function removeTablesApi(objs) {\r\n objs.forEach(function (obj) {\r\n for (var key in obj) {\r\n if (obj[key] instanceof Table) delete obj[key];\r\n }\r\n });\r\n }\r\n\r\n function iterate(req, filter, fn, resolve, reject, valueMapper) {\r\n \r\n // Apply valueMapper (hook('reading') or mappped class)\r\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\r\n // Wrap fn with PSD and microtick stuff from Promise.\r\n var wrappedFn = wrap(mappedFn, reject);\r\n \r\n if (!req.onerror) req.onerror = eventRejectHandler(reject);\r\n if (filter) {\r\n req.onsuccess = trycatcher(function filter_record() {\r\n var cursor = req.result;\r\n if (cursor) {\r\n var c = function () { cursor.continue(); };\r\n if (filter(cursor, function (advancer) { c = advancer; }, resolve, reject))\r\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\r\n c();\r\n } else {\r\n resolve();\r\n }\r\n }, reject);\r\n } else {\r\n req.onsuccess = trycatcher(function filter_record() {\r\n var cursor = req.result;\r\n if (cursor) {\r\n var c = function () { cursor.continue(); };\r\n wrappedFn(cursor.value, cursor, function (advancer) { c = advancer; });\r\n c();\r\n } else {\r\n resolve();\r\n }\r\n }, reject);\r\n }\r\n }\r\n\r\n function parseIndexSyntax(indexes) {\r\n /// \r\n /// \r\n var rv = [];\r\n indexes.split(',').forEach(function (index) {\r\n index = index.trim();\r\n var name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\r\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\r\n var keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\r\n\r\n rv.push(new IndexSpec(\r\n name,\r\n keyPath || null,\r\n /\\&/.test(index),\r\n /\\*/.test(index),\r\n /\\+\\+/.test(index),\r\n isArray(keyPath),\r\n /\\./.test(index)\r\n ));\r\n });\r\n return rv;\r\n }\r\n\r\n function cmp(key1, key2) {\r\n return indexedDB.cmp(key1, key2);\r\n }\r\n\r\n function min(a, b) {\r\n return cmp(a, b) < 0 ? a : b;\r\n }\r\n\r\n function max(a, b) {\r\n return cmp(a, b) > 0 ? a : b;\r\n }\r\n\r\n function ascending(a,b) {\r\n return indexedDB.cmp(a,b);\r\n }\r\n\r\n function descending(a, b) {\r\n return indexedDB.cmp(b,a);\r\n }\r\n\r\n function simpleCompare(a, b) {\r\n return a < b ? -1 : a === b ? 0 : 1;\r\n }\r\n\r\n function simpleCompareReverse(a, b) {\r\n return a > b ? -1 : a === b ? 0 : 1;\r\n }\r\n\r\n function combine(filter1, filter2) {\r\n return filter1 ?\r\n filter2 ?\r\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\r\n filter1 :\r\n filter2;\r\n }\r\n\r\n function readGlobalSchema() {\r\n db.verno = idbdb.version / 10;\r\n db._dbSchema = globalSchema = {};\r\n dbStoreNames = slice(idbdb.objectStoreNames, 0);\r\n if (dbStoreNames.length === 0) return; // Database contains no stores.\r\n var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');\r\n dbStoreNames.forEach(function (storeName) {\r\n var store = trans.objectStore(storeName),\r\n keyPath = store.keyPath,\r\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\r\n var primKey = new IndexSpec(keyPath, keyPath || \"\", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);\r\n var indexes = [];\r\n for (var j = 0; j < store.indexNames.length; ++j) {\r\n var idbindex = store.index(store.indexNames[j]);\r\n keyPath = idbindex.keyPath;\r\n dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;\r\n var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);\r\n indexes.push(index);\r\n }\r\n globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});\r\n });\r\n setApiOnPlace([allTables], keys(globalSchema), globalSchema);\r\n }\r\n\r\n function adjustToExistingIndexNames(schema, idbtrans) {\r\n /// \r\n /// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\r\n /// \r\n /// Map between name and TableSchema\r\n /// \r\n var storeNames = idbtrans.db.objectStoreNames;\r\n\r\n for (var i = 0; i < storeNames.length; ++i) {\r\n var storeName = storeNames[i];\r\n var store = idbtrans.objectStore(storeName);\r\n hasGetAll = 'getAll' in store;\r\n \r\n for (var j = 0; j < store.indexNames.length; ++j) {\r\n var indexName = store.indexNames[j];\r\n var keyPath = store.index(indexName).keyPath;\r\n var dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\r\n if (schema[storeName]) {\r\n var indexSpec = schema[storeName].idxByName[dexieName];\r\n if (indexSpec) indexSpec.name = indexName;\r\n }\r\n }\r\n }\r\n\r\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\r\n if (/Safari/.test(navigator.userAgent) &&\r\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\r\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\r\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\r\n {\r\n hasGetAll = false;\r\n } \r\n }\r\n\r\n function fireOnBlocked(ev) {\r\n db.on(\"blocked\").fire(ev);\r\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\r\n connections\r\n .filter(c=>c.name === db.name && c !== db && !c._vcFired)\r\n .map(c => c.on(\"versionchange\").fire(ev));\r\n }\r\n\r\n extend(this, {\r\n Collection: Collection,\r\n Table: Table,\r\n Transaction: Transaction,\r\n Version: Version,\r\n WhereClause: WhereClause\r\n });\r\n\r\n init();\r\n\r\n addons.forEach(function (fn) {\r\n fn(db);\r\n });\r\n}\r\n\r\nvar fakeAutoComplete = function () { };// Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\r\nvar fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())\r\n\r\nfunction parseType(type) {\r\n if (typeof type === 'function') {\r\n return new type();\r\n } else if (isArray(type)) {\r\n return [parseType(type[0])];\r\n } else if (type && typeof type === 'object') {\r\n var rv = {};\r\n applyStructure(rv, type);\r\n return rv;\r\n } else {\r\n return type;\r\n }\r\n}\r\n\r\nfunction applyStructure(obj, structure) {\r\n keys(structure).forEach(function (member) {\r\n var value = parseType(structure[member]);\r\n obj[member] = value;\r\n });\r\n return obj;\r\n}\r\n\r\nfunction hookedEventSuccessHandler(resolve) {\r\n // wrap() is needed when calling hooks because the rare scenario of:\r\n // * hook does a db operation that fails immediately (IDB throws exception)\r\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\r\n // wrap() will also execute in a virtual tick.\r\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\r\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\r\n // and the transaction will have committed already.\r\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\r\n // because it is always marked with _lib = true when created using Transaction._promise().\r\n return wrap(function(event) {\r\n var req = event.target,\r\n result = req.result,\r\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\r\n hookSuccessHandler = ctx && ctx.onsuccess;\r\n hookSuccessHandler && hookSuccessHandler(result);\r\n resolve && resolve(result);\r\n }, resolve);\r\n}\r\n\r\nfunction eventRejectHandler(reject) {\r\n return wrap(function (event) {\r\n preventDefault(event);\r\n reject (event.target.error);\r\n return false;\r\n });\r\n}\r\n\r\nfunction eventSuccessHandler (resolve) {\r\n return wrap(function (event){\r\n resolve(event.target.result);\r\n });\r\n}\r\n\r\nfunction hookedEventRejectHandler (reject) {\r\n return wrap(function (event) {\r\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\r\n \r\n var req = event.target,\r\n err = req.error,\r\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\r\n hookErrorHandler = ctx && ctx.onerror;\r\n hookErrorHandler && hookErrorHandler(err);\r\n preventDefault(event);\r\n reject (err);\r\n return false;\r\n });\r\n}\r\n\r\nfunction preventDefault(event) {\r\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\r\n event.stopPropagation();\r\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\r\n event.preventDefault();\r\n}\r\n\r\nfunction awaitIterator (iterator) {\r\n var callNext = result => iterator.next(result),\r\n doThrow = error => iterator.throw(error),\r\n onSuccess = step(callNext),\r\n onError = step(doThrow);\r\n\r\n function step(getNext) {\r\n return val => {\r\n var next = getNext(val),\r\n value = next.value;\r\n\r\n return next.done ? value :\r\n (!value || typeof value.then !== 'function' ?\r\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\r\n value.then(onSuccess, onError));\r\n };\r\n }\r\n\r\n return step(callNext)();\r\n}\r\n\r\n//\r\n// IndexSpec struct\r\n//\r\nfunction IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {\r\n /// \r\n /// \r\n /// \r\n /// \r\n /// \r\n /// \r\n /// \r\n this.name = name;\r\n this.keyPath = keyPath;\r\n this.unique = unique;\r\n this.multi = multi;\r\n this.auto = auto;\r\n this.compound = compound;\r\n this.dotted = dotted;\r\n var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && ('[' + [].join.call(keyPath, '+') + ']');\r\n this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + keyPathSrc;\r\n}\r\n\r\n//\r\n// TableSchema struct\r\n//\r\nfunction TableSchema(name, primKey, indexes, instanceTemplate) {\r\n /// \r\n /// \r\n /// \r\n /// \r\n this.name = name;\r\n this.primKey = primKey || new IndexSpec();\r\n this.indexes = indexes || [new IndexSpec()];\r\n this.instanceTemplate = instanceTemplate;\r\n this.mappedClass = null;\r\n this.idxByName = arrayToObject(indexes, index => [index.name, index]);\r\n}\r\n\r\nfunction safariMultiStoreFix(storeNames) {\r\n return storeNames.length === 1 ? storeNames[0] : storeNames;\r\n}\r\n\r\nfunction getNativeGetDatabaseNamesFn(indexedDB) {\r\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\r\n return fn && fn.bind(indexedDB);\r\n}\r\n\r\n// Export Error classes\r\nprops(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};\r\n\r\n//\r\n// Static methods and properties\r\n// \r\nprops(Dexie, {\r\n \r\n //\r\n // Static delete() method.\r\n //\r\n delete: function (databaseName) {\r\n var db = new Dexie(databaseName),\r\n promise = db.delete();\r\n promise.onblocked = function (fn) {\r\n db.on(\"blocked\", fn);\r\n return this;\r\n };\r\n return promise;\r\n },\r\n \r\n //\r\n // Static exists() method.\r\n //\r\n exists: function(name) {\r\n return new Dexie(name).open().then(db=>{\r\n db.close();\r\n return true;\r\n }).catch(Dexie.NoSuchDatabaseError, () => false);\r\n },\r\n \r\n //\r\n // Static method for retrieving a list of all existing databases at current host.\r\n //\r\n getDatabaseNames: function (cb) {\r\n var getDatabaseNames = getNativeGetDatabaseNamesFn(Dexie.dependencies.indexedDB);\r\n return getDatabaseNames ? new Promise((resolve, reject) => {\r\n var req = getDatabaseNames();\r\n req.onsuccess = function (event) {\r\n resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array\r\n };\r\n req.onerror = eventRejectHandler(reject);\r\n }).then(cb) : dbNamesDB.dbnames.toCollection().primaryKeys(cb);\r\n },\r\n \r\n defineClass: function (structure) {\r\n /// \r\n /// Create a javascript constructor based on given template for which properties to expect in the class.\r\n /// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.\r\n /// \r\n /// Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also\r\n /// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}\r\n\r\n // Default constructor able to copy given properties into this object.\r\n function Class(properties) {\r\n /// Properties to initialize object with.\r\n /// \r\n properties ? extend(this, properties) : fake && applyStructure(this, structure);\r\n }\r\n return Class;\r\n },\r\n \r\n applyStructure: applyStructure,\r\n \r\n ignoreTransaction: function (scopeFunc) {\r\n // In case caller is within a transaction but needs to create a separate transaction.\r\n // Example of usage:\r\n //\r\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\r\n // logger function and not need to include the 'logentries' table in all transaction it performs.\r\n // The logging should always be done in a separate transaction and not be dependant on the current\r\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\r\n //\r\n // Dexie.ignoreTransaction(function() {\r\n // db.logentries.add(newLogEntry);\r\n // });\r\n //\r\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\r\n // in current Promise-scope.\r\n //\r\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\r\n // API for this because\r\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\r\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\r\n // 3) setImmediate() is not supported in the ES standard.\r\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\r\n return PSD.trans ?\r\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\r\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\r\n },\r\n \r\n vip: function (fn) {\r\n // To be used by subscribers to the on('ready') event.\r\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\r\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\r\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\r\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\r\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\r\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\r\n // the caller will not resolve until database is opened.\r\n return newScope(function () {\r\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\r\n return fn();\r\n });\r\n },\r\n\r\n async: function (generatorFn) {\r\n return function () {\r\n try {\r\n var rv = awaitIterator(generatorFn.apply(this, arguments));\r\n if (!rv || typeof rv.then !== 'function')\r\n return Promise.resolve(rv);\r\n return rv;\r\n } catch (e) {\r\n return rejection (e);\r\n }\r\n };\r\n },\r\n\r\n spawn: function (generatorFn, args, thiz) {\r\n try {\r\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\r\n if (!rv || typeof rv.then !== 'function')\r\n return Promise.resolve(rv);\r\n return rv;\r\n } catch (e) {\r\n return rejection(e);\r\n }\r\n },\r\n \r\n // Dexie.currentTransaction property\r\n currentTransaction: {\r\n get: () => PSD.trans || null\r\n },\r\n\r\n waitFor: function (promiseOrFunction, optionalTimeout) {\r\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\r\n var promise = Promise.resolve(\r\n typeof promiseOrFunction === 'function' ? Dexie.ignoreTransaction(promiseOrFunction) : promiseOrFunction)\r\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \r\n\r\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\r\n // on given value.\r\n return PSD.trans ? PSD.trans.waitFor(promise) : promise;\r\n },\r\n \r\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\r\n Promise: Promise,\r\n \r\n // Dexie.debug proptery:\r\n // Dexie.debug = false\r\n // Dexie.debug = true\r\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\r\n debug: {\r\n get: () => Debug.debug,\r\n set: value => {\r\n Debug.setDebug(value, value === 'dexie' ? ()=>true : dexieStackFrameFilter);\r\n }\r\n },\r\n \r\n // Export our derive/extend/override methodology\r\n derive: derive,\r\n extend: extend,\r\n props: props,\r\n override: override,\r\n // Export our Events() function - can be handy as a toolkit\r\n Events: Events,\r\n // Utilities\r\n getByKeyPath: getByKeyPath,\r\n setByKeyPath: setByKeyPath,\r\n delByKeyPath: delByKeyPath,\r\n shallowClone: shallowClone,\r\n deepClone: deepClone,\r\n getObjectDiff: getObjectDiff,\r\n asap: asap,\r\n maxKey: maxKey,\r\n minKey: minKey,\r\n // Addon registry\r\n addons: [],\r\n // Global DB connection list\r\n connections: connections,\r\n \r\n MultiModifyError: exceptions.Modify, // Backward compatibility 0.9.8. Deprecate.\r\n errnames: errnames,\r\n \r\n // Export other static classes\r\n IndexSpec: IndexSpec,\r\n TableSchema: TableSchema,\r\n \r\n //\r\n // Dependencies\r\n //\r\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\r\n //\r\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\r\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\r\n //\r\n dependencies: {\r\n // Required:\r\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\r\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\r\n },\r\n \r\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.\r\n semVer: DEXIE_VERSION,\r\n version: DEXIE_VERSION.split('.')\r\n .map(n => parseInt(n))\r\n .reduce((p,c,i) => p + (c/Math.pow(10,i*2))),\r\n fakeAutoComplete: fakeAutoComplete,\r\n \r\n // https://github.com/dfahlander/Dexie.js/issues/186\r\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\r\n // x.default. Workaround: Set Dexie.default = Dexie.\r\n default: Dexie,\r\n // Make it possible to import {Dexie} (non-default import)\r\n // Reason 1: May switch to that in future.\r\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\r\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\r\n // exporting the symbol, not just default exporting)\r\n Dexie: Dexie\r\n});\r\n\r\n// Map DOMErrors and DOMExceptions to corresponding Dexie errors. May change in Dexie v2.0.\r\nPromise.rejectionMapper = mapError;\r\n\r\n// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015.\r\ndoFakeAutoComplete(function() {\r\n Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete;\r\n Dexie.fake = fake = true;\r\n});\r\n\r\n// Initialize dbNamesDB (won't ever be opened on chromium browsers')\r\ndbNamesDB = new Dexie('__dbnames'); \r\ndbNamesDB.version(1).stores({dbnames: 'name'});\r\n\r\n(()=>{\r\n // Migrate from Dexie 1.x database names stored in localStorage:\r\n var DBNAMES = 'Dexie.DatabaseNames';\r\n if (typeof localStorage !== undefined && _global.document !== undefined) try {\r\n // Have localStorage and is not executing in a worker. Lets migrate from Dexie 1.x.\r\n JSON.parse(localStorage.getItem(DBNAMES) || \"[]\")\r\n .forEach(name => dbNamesDB.dbnames.put({name: name}).catch(nop));\r\n localStorage.removeItem(DBNAMES);\r\n } catch (_e) {}\r\n})();\r\n"]} \ No newline at end of file diff --git a/test/bundle.js b/test/bundle.js new file mode 100644 index 000000000..2bbb604d5 --- /dev/null +++ b/test/bundle.js @@ -0,0 +1,10376 @@ +(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 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", regeneratorRuntime.mark(function _callee() { + var highestKey, result; + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return db.users.add({ username: "fsdkljfd", email: ["fjkljslk"] }); + + case 2: + highestKey = _context.sent; + + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + _context.next = 6; + return db.users.delete(highestKey); + + case 6: + QUnit.ok(true, "Deleted test item"); + _context.next = 9; + return db.users.bulkAdd([{ first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }]); + + case 9: + result = _context.sent; + + QUnit.equal(result, highestKey + 2, "Result of bulkAdd() operation was equal to highestKey + 2"); + + case 11: + case 'end': + return _context.stop(); + } + }, _callee, this); + })); + spawnedTest("bulkAdd-catching errors", regeneratorRuntime.mark(function _callee3() { + var newUsersX, newUsersY, newUsersZ; + return regeneratorRuntime.wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return 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 2: + _context3.t0 = QUnit; + _context3.next = 5; + return db.users.where("username").startsWith('aper').count(); + + case 5: + _context3.t1 = _context3.sent; + + _context3.t0.equal.call(_context3.t0, _context3.t1, 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"] }]; + _context3.prev = 8; + _context3.next = 11; + return db.transaction("rw", db.users, function () { + db.users.bulkAdd(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + }); + + case 11: + QUnit.ok(false, "Should not come here"); + _context3.next = 17; + break; + + case 14: + _context3.prev = 14; + _context3.t2 = _context3['catch'](8); + + QUnit.ok(true, "Got: " + _context3.t2); + + case 17: + _context3.t3 = QUnit; + _context3.next = 20; + return db.users.where('username').startsWith('xper').count(); + + case 20: + _context3.t4 = _context3.sent; + + _context3.t3.equal.call(_context3.t3, _context3.t4, 0, "0 users! Good, means that previous transaction did not commit"); + + _context3.next = 24; + return db.users.bulkAdd(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + }); + + case 24: + _context3.t5 = QUnit; + _context3.next = 27; + return db.users.where('username').startsWith('xper').count(); + + case 27: + _context3.t6 = _context3.sent; + + _context3.t5.equal.call(_context3.t5, _context3.t6, 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"] }]; + // Now check that catching the operation via try..catch should also make it succeed. + + _context3.prev = 30; + _context3.next = 33; + return db.users.bulkAdd(newUsersY); + + case 33: + _context3.next = 38; + break; + + case 35: + _context3.prev = 35; + _context3.t7 = _context3['catch'](30); + + QUnit.ok(true, "Got: " + _context3.t7); + + case 38: + _context3.t8 = QUnit; + _context3.next = 41; + return db.users.where('username').startsWith('yper').count(); + + case 41: + _context3.t9 = _context3.sent; + + _context3.t8.equal.call(_context3.t8, _context3.t9, 3, "3 users! Good - means that previous operation catched (via try..yield..catch this time, and therefore committed"); + + // Now check that catching and rethrowing should indeed make it fail + 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"] }]; + _context3.next = 46; + return db.transaction('rw', db.users, regeneratorRuntime.mark(function _callee2() { + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.prev = 0; + _context2.next = 3; + return db.users.bulkAdd(newUsersZ); + + case 3: + _context2.next = 8; + break; + + case 5: + _context2.prev = 5; + _context2.t0 = _context2['catch'](0); + throw _context2.t0; + + case 8: + case 'end': + return _context2.stop(); + } + }, _callee2, this, [[0, 5]]); + })).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + }); + + case 46: + _context3.t10 = QUnit; + _context3.next = 49; + return db.users.where('username').startsWith('zper').count(); + + case 49: + _context3.t11 = _context3.sent; + + _context3.t10.equal.call(_context3.t10, _context3.t11, 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"); + + case 51: + case 'end': + return _context3.stop(); + } + }, _callee3, this, [[8, 14], [30, 35]]); + })); + spawnedTest("bulkAdd-non-inbound-autoincrement", regeneratorRuntime.mark(function _callee4() { + return regeneratorRuntime.wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return db.folks.bulkAdd([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }]); + + case 2: + _context4.t0 = QUnit; + _context4.next = 5; + return db.folks.where('first').equals('Foo').count(); + + case 5: + _context4.t1 = _context4.sent; + + _context4.t0.equal.call(_context4.t0, _context4.t1, 4, "Should be 4 Foos"); + + _context4.t2 = QUnit; + _context4.next = 10; + return db.folks.where('last').equals('Bar').count(); + + case 10: + _context4.t3 = _context4.sent; + + _context4.t2.equal.call(_context4.t2, _context4.t3, 1, "Shoudl be 1 Bar"); + + case 12: + case 'end': + return _context4.stop(); + } + }, _callee4, this); + })); + spawnedTest("bulkAdd-catch sub transaction", regeneratorRuntime.mark(function _callee5() { + return regeneratorRuntime.wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return 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 2: + _context5.t0 = QUnit; + _context5.next = 5; + return db.users.where('username').startsWith('aper').count(); + + case 5: + _context5.t1 = _context5.sent; + + _context5.t0.equal.call(_context5.t0, _context5.t1, 0, "0 users! Good, means that inner transaction did not commit"); + + case 7: + case 'end': + return _context5.stop(); + } + }, _callee5, this); + })); + spawnedTest("bulkPut", regeneratorRuntime.mark(function _callee6() { + var highestKey, existingFirstUserToReplace, result, ourAddedUsers, replacedDfahlander; + return regeneratorRuntime.wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return db.users.add({ username: "fsdkljfd", email: ["fjkljslk"] }); + + case 2: + highestKey = _context6.sent; + + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + _context6.next = 6; + return db.users.delete(highestKey); + + case 6: + QUnit.ok(true, "Deleted test item"); + _context6.next = 9; + return db.users.get(idOfFirstUser); + + case 9: + existingFirstUserToReplace = _context6.sent; + + QUnit.equal(existingFirstUserToReplace.username, "dfahlander", "Existing user should be dfahlander"); + _context6.next = 13; + return 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 13: + result = _context6.sent; + + QUnit.equal(result, highestKey + 2, "Result of bulkPut() operation was equal to highestKey + 2"); + _context6.next = 17; + return db.users.where('username').startsWith("aper").toArray(); + + case 17: + ourAddedUsers = _context6.sent; + + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + _context6.next = 21; + return db.users.get(idOfFirstUser); + + case 21: + replacedDfahlander = _context6.sent; + + QUnit.equal(replacedDfahlander.username, "aper2", "dfahlander Should now be aper2 instead"); + + case 23: + case 'end': + return _context6.stop(); + } + }, _callee6, this); + })); + spawnedTest("bulkPut with overlapping objects", regeneratorRuntime.mark(function _callee7() { + var theOne; + return regeneratorRuntime.wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return db.users.bulkPut([{ + id: "sdjls83", + first: "Daveious" + }, { + id: "sdjls83", + last: "Olvono" + }]); + + case 2: + _context7.next = 4; + return db.users.get("sdjls83"); + + case 4: + theOne = _context7.sent; + + QUnit.equal(theOne.last, "Olvono", "Last item is the one inserted"); + QUnit.ok(theOne.first === undefined, "Object doesnt have a first property"); + + case 7: + case 'end': + return _context7.stop(); + } + }, _callee7, this); + })); + spawnedTest("bulkPut-catching errors", regeneratorRuntime.mark(function _callee9() { + var newUsersX, newUsersY, newUsersZ; + return regeneratorRuntime.wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return 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 2: + _context9.t0 = QUnit; + _context9.next = 5; + return db.users.where("username").startsWith('aper').count(); + + case 5: + _context9.t1 = _context9.sent; + + _context9.t0.equal.call(_context9.t0, _context9.t1, 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"] }]; + _context9.prev = 8; + _context9.next = 11; + return db.transaction("rw", db.users, function () { + db.users.bulkPut(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + }); + + case 11: + QUnit.ok(false, "Should not come here"); + _context9.next = 17; + break; + + case 14: + _context9.prev = 14; + _context9.t2 = _context9['catch'](8); + + QUnit.ok(true, "Got: " + _context9.t2); + + case 17: + _context9.t3 = QUnit; + _context9.next = 20; + return db.users.where('username').startsWith('xper').count(); + + case 20: + _context9.t4 = _context9.sent; + + _context9.t3.equal.call(_context9.t3, _context9.t4, 0, "0 users! Good, means that previous transaction did not commit"); + + _context9.next = 24; + return db.users.bulkPut(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + }); + + case 24: + _context9.t5 = QUnit; + _context9.next = 27; + return db.users.where('username').startsWith('xper').count(); + + case 27: + _context9.t6 = _context9.sent; + + _context9.t5.equal.call(_context9.t5, _context9.t6, 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"] }]; + // Now check that catching the operation via try..catch should also make it succeed. + + _context9.prev = 30; + _context9.next = 33; + return db.users.bulkPut(newUsersY); + + case 33: + _context9.next = 38; + break; + + case 35: + _context9.prev = 35; + _context9.t7 = _context9['catch'](30); + + QUnit.ok(true, "Got: " + _context9.t7); + + case 38: + _context9.t8 = QUnit; + _context9.next = 41; + return db.users.where('username').startsWith('yper').count(); + + case 41: + _context9.t9 = _context9.sent; + + _context9.t8.equal.call(_context9.t8, _context9.t9, 3, "Should count to 3 users because previous previous operation catched (via try..yield..catch this time, and therefore should have been committed"); + + // Now check that catching and rethrowing should indeed make it fail + 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"] }]; + _context9.next = 46; + return db.transaction('rw', db.users, regeneratorRuntime.mark(function _callee8() { + return regeneratorRuntime.wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.prev = 0; + _context8.next = 3; + return db.users.bulkPut(newUsersZ); + + case 3: + _context8.next = 8; + break; + + case 5: + _context8.prev = 5; + _context8.t0 = _context8['catch'](0); + throw _context8.t0; + + case 8: + case 'end': + return _context8.stop(); + } + }, _callee8, this, [[0, 5]]); + })).catch(Dexie.BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + }); + + case 46: + _context9.t10 = QUnit; + _context9.next = 49; + return db.users.where('username').startsWith('zper').count(); + + case 49: + _context9.t11 = _context9.sent; + + _context9.t10.equal.call(_context9.t10, _context9.t11, 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"); + + case 51: + case 'end': + return _context9.stop(); + } + }, _callee9, this, [[8, 14], [30, 35]]); + })); + spawnedTest("bulkPut-non-inbound-autoincrement", regeneratorRuntime.mark(function _callee10() { + return regeneratorRuntime.wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return db.folks.bulkPut([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }]); + + case 2: + _context10.t0 = QUnit; + _context10.next = 5; + return db.folks.where('first').equals('Foo').count(); + + case 5: + _context10.t1 = _context10.sent; + + _context10.t0.equal.call(_context10.t0, _context10.t1, 4, "Should be 4 Foos"); + + _context10.t2 = QUnit; + _context10.next = 10; + return db.folks.where('last').equals('Bar').count(); + + case 10: + _context10.t3 = _context10.sent; + + _context10.t2.equal.call(_context10.t2, _context10.t3, 1, "Should be 1 Bar"); + + case 12: + case 'end': + return _context10.stop(); + } + }, _callee10, this); + })); + spawnedTest("bulkPut - mixed inbound autoIncrement", regeneratorRuntime.mark(function _callee11() { + var lastId, newLastId, foo2s; + return regeneratorRuntime.wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + _context11.next = 2; + return db.users.bulkPut([{ first: "Foo", last: "Bar" }, { first: "Foo", last: "Bar2" }, { first: "Foo", last: "Bar3" }, { first: "Foo", last: "Bar4" }]); + + case 2: + lastId = _context11.sent; + _context11.t0 = QUnit; + _context11.next = 6; + return db.users.where('first').equals('Foo').count(); + + case 6: + _context11.t1 = _context11.sent; + + _context11.t0.equal.call(_context11.t0, _context11.t1, 4, "Should be 4 Foos"); + + _context11.t2 = QUnit; + _context11.next = 11; + return db.users.where('last').equals('Bar').count(); + + case 11: + _context11.t3 = _context11.sent; + + _context11.t2.equal.call(_context11.t2, _context11.t3, 1, "Should be 1 Bar"); + + _context11.next = 15; + return 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 15: + newLastId = _context11.sent; + + QUnit.equal(newLastId, lastId + 2, "Should have incremented last ID twice now"); + _context11.t4 = QUnit; + _context11.next = 20; + return db.users.where('first').equals('Foo').count(); + + case 20: + _context11.t5 = _context11.sent; + + _context11.t4.equal.call(_context11.t4, _context11.t5, 2, "Should be 2 Foos now"); + + _context11.t6 = QUnit; + _context11.next = 25; + return db.users.where('first').equals('Foo2').count(); + + case 25: + _context11.t7 = _context11.sent; + + _context11.t6.equal.call(_context11.t6, _context11.t7, 4, "Should be 4 Foo2s now"); + + _context11.next = 29; + return db.users.where('first').equals('Foo2').toArray(); + + case 29: + foo2s = _context11.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)"); + + case 34: + case 'end': + return _context11.stop(); + } + }, _callee11, this); + })); + spawnedTest("bulkPut-catch sub transaction", regeneratorRuntime.mark(function _callee12() { + return regeneratorRuntime.wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return 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 2: + _context12.t0 = QUnit; + _context12.next = 5; + return db.users.where('username').startsWith('aper').count(); + + case 5: + _context12.t1 = _context12.sent; + + _context12.t0.equal.call(_context12.t0, _context12.t1, 0, "0 users! Good, means that inner transaction did not commit"); + + case 7: + case 'end': + return _context12.stop(); + } + }, _callee12, this); + })); + spawnedTest("bulkDelete", regeneratorRuntime.mark(function _callee13() { + var userKeys, userCount; + return regeneratorRuntime.wrap(function _callee13$(_context13) { + while (1) switch (_context13.prev = _context13.next) { + case 0: + _context13.next = 2; + return db.users.orderBy('id').keys(); + + case 2: + userKeys = _context13.sent; + + QUnit.ok(userKeys.length > 0, "User keys found: " + userKeys.join(',')); + _context13.next = 6; + return db.users.bulkDelete(userKeys); + + case 6: + _context13.next = 8; + return db.users.count(); + + case 8: + userCount = _context13.sent; + + QUnit.equal(userCount, 0, "Should be no users there now"); + + case 10: + case 'end': + return _context13.stop(); + } + }, _callee13, this); + })); + spawnedTest("bulkDelete - nonexisting keys", regeneratorRuntime.mark(function _callee14() { + var userKeys, userCount; + return regeneratorRuntime.wrap(function _callee14$(_context14) { + while (1) switch (_context14.prev = _context14.next) { + case 0: + _context14.next = 2; + return db.users.orderBy(':id').lastKey(); + + case 2: + _context14.t0 = _context14.sent; + userKeys = ["nonexisting1", "nonexisting2", _context14.t0]; + _context14.next = 6; + return db.users.bulkDelete(userKeys); + + case 6: + _context14.next = 8; + return db.users.count(); + + case 8: + userCount = _context14.sent; + + QUnit.equal(userCount, 1, "Should be one user there now. (the other should have been deleted)"); + + case 10: + case 'end': + return _context14.stop(); + } + }, _callee14, this); + })); + spawnedTest("bulkDelete-faulty-key", regeneratorRuntime.mark(function _callee15() { + var userKeys; + return regeneratorRuntime.wrap(function _callee15$(_context15) { + while (1) switch (_context15.prev = _context15.next) { + case 0: + userKeys = [{ faulty: "ohyes" }]; + _context15.next = 3; + return db.users.bulkDelete(userKeys).then(function () { + QUnit.ok(false, "Should not succeed"); + }).catch('DataError', function (e) { + QUnit.ok(true, "Should get error: " + e); + }); + + case 3: + case 'end': + return _context15.stop(); + } + }, _callee15, this); + })); + 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", regeneratorRuntime.mark(function _callee17() { + return regeneratorRuntime.wrap(function _callee17$(_context17) { + while (1) switch (_context17.prev = _context17.next) { + case 0: + _context17.next = 2; + return db.transaction('r', 'users', regeneratorRuntime.mark(function _callee16() { + return regeneratorRuntime.wrap(function _callee16$(_context16) { + while (1) switch (_context16.prev = _context16.next) { + case 0: + _context16.next = 2; + return db.users.bulkAdd([{ first: "Foo", last: "Bar" }]); + + case 2: + case 'end': + return _context16.stop(); + } + }, _callee16, this); + })).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('ReadOnlyError', function (e) { + QUnit.ok(true, "Got ReadOnlyError: " + e.stack); + }); + + case 2: + case 'end': + return _context17.stop(); + } + }, _callee17, this); + })); + spawnedTest("failNotIncludedStore", regeneratorRuntime.mark(function _callee19() { + return regeneratorRuntime.wrap(function _callee19$(_context19) { + while (1) switch (_context19.prev = _context19.next) { + case 0: + _context19.next = 2; + return db.transaction('rw', 'folks', regeneratorRuntime.mark(function _callee18() { + return regeneratorRuntime.wrap(function _callee18$(_context18) { + while (1) switch (_context18.prev = _context18.next) { + case 0: + _context18.next = 2; + return db.users.bulkAdd([{ first: "Foo", last: "Bar" }]); + + case 2: + case 'end': + return _context18.stop(); + } + }, _callee18, this); + })).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + }); + + case 2: + case 'end': + return _context19.stop(); + } + }, _callee19, this); + })); + 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 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", regeneratorRuntime.mark(function _callee20() { + var array; + return regeneratorRuntime.wrap(function _callee20$(_context20) { + while (1) switch (_context20.prev = _context20.next) { + case 0: + _context20.next = 2; + return db$1.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]).and(function (user) { + return user.username === "dfahlander"; + }).toArray(); + + case 2: + array = _context20.sent; + + QUnit.equal(array.length, 1, "Should find one user with given criteria"); + + case 4: + case 'end': + return _context20.stop(); + } + }, _callee20, this); + })); + spawnedTest("and with keys", regeneratorRuntime.mark(function _callee21() { + var keys; + return regeneratorRuntime.wrap(function _callee21$(_context21) { + while (1) switch (_context21.prev = _context21.next) { + case 0: + _context21.next = 2; + return db$1.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]).and(function (user) { + return user.username === "dfahlander"; + }).keys(); + + case 2: + keys = _context21.sent; + + QUnit.equal(keys.length, 1, "Should find one user with given criteria"); + + case 4: + case 'end': + return _context21.stop(); + } + }, _callee21, this); + })); + spawnedTest("and with delete", regeneratorRuntime.mark(function _callee22() { + return regeneratorRuntime.wrap(function _callee22$(_context22) { + while (1) switch (_context22.prev = _context22.next) { + case 0: + _context22.next = 2; + return db$1.users.orderBy('username').and(function (u) { + return QUnit.ok(!!u, "User should exist here"); + }).delete(); + + case 2: + case 'end': + return _context22.stop(); + } + }, _callee22, this); + })); + 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); + }); + 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 = 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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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', regeneratorRuntime.mark(function _callee23() { + var items; + return regeneratorRuntime.wrap(function _callee23$(_context23) { + while (1) switch (_context23.prev = _context23.next) { + case 0: + if (supports('compound')) { + _context23.next = 2; + break; + } + + return _context23.abrupt('return', QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")); + + case 2: + _context23.next = 4; + return 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 4: + _context23.next = 6; + return db$2.people.where('[name+number]').anyOf([[-2, 0], [-3, 0]]) // https://github.com/dfahlander/Dexie.js/issues/31 + .toArray(); + + case 6: + items = _context23.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"); + + case 10: + case 'end': + return _context23.stop(); + } + }, _callee23, this); + })); + 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(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(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$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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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$1(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$1(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$1(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$1(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$1(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, regeneratorRuntime.mark(function _callee24(subTrans) { + var count; + return regeneratorRuntime.wrap(function _callee24$(_context24) { + while (1) switch (_context24.prev = _context24.next) { + case 0: + QUnit.ok(subTrans !== trans, "Should be in a sub transaction"); + QUnit.ok(Dexie.currentTransaction === subTrans, "Should be in a sub transaction"); + _context24.next = 4; + return trans.users.count(); + + case 4: + count = _context24.sent; + + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + _context24.next = 8; + return subTrans.waitFor(sleep(10)); + + case 8: + QUnit.ok(true, "Should be able to call waitFor() on sub transaction"); + _context24.next = 11; + return trans.users.count(); + + case 11: + count = _context24.sent; + + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + + case 13: + case 'end': + return _context24.stop(); + } + }, _callee24, this); + }))]; + 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$1(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$1(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$1(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$1(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$1(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$1(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$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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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(regeneratorRuntime.mark(function _callee25(promise, ms) { + return regeneratorRuntime.wrap(function _callee25$(_context25) { + while (1) switch (_context25.prev = _context25.next) { + case 0: + _context25.next = 2; + return Promise.race([promise, new Promise(function (resolve, reject) { + return setTimeout(function () { + return reject("timeout"); + }, ms); + })]); + + case 2: + case 'end': + return _context25.stop(); + } + }, _callee25, this); + })); + spawnedTest("multiple db should not block each other", regeneratorRuntime.mark(function _callee26() { + var db1, db2; + return regeneratorRuntime.wrap(function _callee26$(_context26) { + while (1) switch (_context26.prev = _context26.next) { + case 0: + if (supports("versionchange")) { + _context26.next = 3; + break; + } + + QUnit.ok(true, "SKIPPED - versionchange UNSUPPORTED"); + return _context26.abrupt('return'); + + case 3: + db1 = new Dexie("TestDB"), db2 = new Dexie("TestDB"); + + db1.version(1).stores({ + foo: 'bar' + }); + db2.version(1).stores({ + foo: 'bar' + }); + _context26.next = 8; + return db1.open(); + + case 8: + QUnit.ok(true, "db1 should open"); + _context26.next = 11; + return db2.open(); + + case 11: + QUnit.ok(true, "db2 should open"); + _context26.prev = 12; + _context26.next = 15; + return timeout(db1.delete(), 1500); + + case 15: + QUnit.ok(true, "Succeeded to delete db1 while db2 was open"); + _context26.next = 23; + break; + + case 18: + _context26.prev = 18; + _context26.t0 = _context26['catch'](12); + + db1.close(); + db2.close(); + QUnit.ok(false, "Could not delete db1 - " + _context26.t0); + + case 23: + case 'end': + return _context26.stop(); + } + }, _callee26, this, [[12, 18]]); + })); + spawnedTest("Using db on node should be rejected with MissingAPIError", regeneratorRuntime.mark(function _callee27() { + var db; + return regeneratorRuntime.wrap(function _callee27$(_context27) { + while (1) switch (_context27.prev = _context27.next) { + case 0: + db = new Dexie('TestDB', { + indexedDB: undefined, + IDBKeyRange: undefined + }); + + db.version(1).stores({ foo: 'bar' }); + _context27.prev = 2; + _context27.next = 5; + return db.foo.toArray(); + + case 5: + QUnit.ok(false, "Should not get any result because API is missing."); + _context27.next = 11; + break; + + case 8: + _context27.prev = 8; + _context27.t0 = _context27['catch'](2); + + QUnit.ok(_context27.t0 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + _context27.t0.name); + + case 11: + _context27.prev = 11; + _context27.next = 14; + return db.open(); + + case 14: + _context27.next = 19; + break; + + case 16: + _context27.prev = 16; + _context27.t1 = _context27['catch'](11); + + QUnit.ok(_context27.t1 instanceof Dexie.MissingAPIError, "Should get MissingAPIError. Got: " + _context27.t1.name); + + case 19: + case 'end': + return _context27.stop(); + } + }, _callee27, this, [[2, 8], [11, 16]]); + })); + 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, regeneratorRuntime.mark(function _callee28() { + var db; + return regeneratorRuntime.wrap(function _callee28$(_context28) { + while (1) switch (_context28.prev = _context28.next) { + 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)); + }); + _context28.next = 6; + return db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + }); + + case 6: + case 'end': + return _context28.stop(); + } + }, _callee28, this); + })); + 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$2(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$2(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 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(regeneratorRuntime.mark(function _callee30() { + var finallyWasReached; + return regeneratorRuntime.wrap(function _callee30$(_context30) { + while (1) switch (_context30.prev = _context30.next) { + case 0: + finallyWasReached = false; + _context30.prev = 1; + _context30.next = 4; + return db$4.transaction('rw', 'friends', 'pets', regeneratorRuntime.mark(function _callee29() { + var catId, dogId, gurra, gurrasPets; + return regeneratorRuntime.wrap(function _callee29$(_context29) { + while (1) switch (_context29.prev = _context29.next) { + case 0: + _context29.next = 2; + return db$4.pets.add({ name: "Tito", kind: "cat" }); + + case 2: + catId = _context29.sent; + _context29.next = 5; + return db$4.pets.add({ name: "Josephina", kind: "dog" }); + + case 5: + dogId = _context29.sent; + + // Add a friend who owns the pets + db$4.friends.add({ name: "Gurra G", pets: [catId, dogId] }); + _context29.next = 9; + return db$4.friends.where('name').equals("Gurra G").first(); + + case 9: + gurra = _context29.sent; + + QUnit.ok(!!gurra, "Gurra could be found with yield"); + // Now retrieve the pet objects that Gurra is referring to: + _context29.next = 13; + return db$4.pets.where('id').anyOf(gurra.pets).toArray(); + + case 13: + gurrasPets = _context29.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"); + + case 17: + case 'end': + return _context29.stop(); + } + }, _callee29, this); + })); + + case 4: + _context30.next = 9; + break; + + case 6: + _context30.prev = 6; + _context30.t0 = _context30['catch'](1); + + QUnit.ok(false, "Caught error: " + _context30.t0); + + case 9: + _context30.prev = 9; + + finallyWasReached = true; + return _context30.finish(9); + + case 12: + QUnit.ok(finallyWasReached, "finally was reached"); + QUnit.start(); + + case 14: + case 'end': + return _context30.stop(); + } + }, _callee30, this, [[1, 6, 9, 12]]); + }))); + QUnit.asyncTest("Catching indexedDB error event", 2, async$2(regeneratorRuntime.mark(function _callee31() { + return regeneratorRuntime.wrap(function _callee31$(_context31) { + while (1) switch (_context31.prev = _context31.next) { + case 0: + _context31.prev = 0; + _context31.next = 3; + return db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" }); + + case 3: + QUnit.ok(true, "Should come so far"); + _context31.next = 6; + return db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" }); + + case 6: + // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + _context31.next = 12; + break; + + case 9: + _context31.prev = 9; + _context31.t0 = _context31['catch'](0); + + QUnit.equal(_context31.t0.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + + case 12: + QUnit.start(); + + case 13: + case 'end': + return _context31.stop(); + } + }, _callee31, this, [[0, 9]]); + }))); + QUnit.asyncTest("Catching error prevents transaction from aborting", 5, async$2(regeneratorRuntime.mark(function _callee33() { + return regeneratorRuntime.wrap(function _callee33$(_context33) { + while (1) switch (_context33.prev = _context33.next) { + case 0: + _context33.prev = 0; + _context33.next = 3; + return db$4.transaction('rw', 'pets', regeneratorRuntime.mark(function _callee32() { + return regeneratorRuntime.wrap(function _callee32$(_context32) { + while (1) switch (_context32.prev = _context32.next) { + case 0: + _context32.prev = 0; + _context32.next = 3; + return db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" }); + + case 3: + QUnit.ok(true, "Should come so far"); + _context32.next = 6; + return db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" }); + + case 6: + // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + _context32.next = 12; + break; + + case 9: + _context32.prev = 9; + _context32.t0 = _context32['catch'](0); + + QUnit.equal(_context32.t0.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + + case 12: + case 'end': + return _context32.stop(); + } + }, _callee32, this, [[0, 9]]); + })); + + case 3: + QUnit.ok(true, "Should come here - transaction committed because we caught the error"); + _context33.t0 = QUnit; + _context33.next = 7; + return db$4.pets.get(1); + + case 7: + _context33.t1 = _context33.sent; + + _context33.t0.ok.call(_context33.t0, _context33.t1, "A pet with ID 1 exists in DB"); + + _context33.t2 = QUnit; + _context33.next = 12; + return db$4.pets.get(1); + + case 12: + _context33.t3 = _context33.sent.name; + + _context33.t2.equal.call(_context33.t2, _context33.t3, "Tidi", "It was Tidi in the first position"); + + case 14: + _context33.prev = 14; + + QUnit.start(); + return _context33.finish(14); + + case 17: + case 'end': + return _context33.stop(); + } + }, _callee33, this, [[0,, 14, 17]]); + }))); + QUnit.asyncTest("Transaction not committing when not catching error event", 4, async$2(regeneratorRuntime.mark(function _callee35() { + return regeneratorRuntime.wrap(function _callee35$(_context35) { + while (1) switch (_context35.prev = _context35.next) { + case 0: + _context35.prev = 0; + _context35.next = 3; + return db$4.transaction('rw', 'pets', regeneratorRuntime.mark(function _callee34() { + return regeneratorRuntime.wrap(function _callee34$(_context34) { + while (1) switch (_context34.prev = _context34.next) { + case 0: + _context34.next = 2; + return db$4.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" }); + + case 2: + QUnit.ok(true, "Should come so far"); + _context34.next = 5; + return db$4.pets.add({ id: 1, name: "Todoo", kind: "Snake" }); + + case 5: + // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + + case 6: + case 'end': + return _context34.stop(); + } + }, _callee34, this); + })); + + case 3: + QUnit.ok(false, "Should not come here"); + _context35.next = 15; + break; + + case 6: + _context35.prev = 6; + _context35.t0 = _context35['catch'](0); + + QUnit.ok(true, "Transaction should fail"); + QUnit.equal(_context35.t0.name, "ConstraintError", "Error caught was a ConstraintError!"); + _context35.t1 = QUnit; + _context35.next = 13; + return db$4.pets.count(); + + case 13: + _context35.t2 = _context35.sent; + + _context35.t1.equal.call(_context35.t1, _context35.t2, 0, "Pets table should still be empty because transaction failed"); + + case 15: + _context35.prev = 15; + + QUnit.start(); + return _context35.finish(15); + + case 18: + case 'end': + return _context35.stop(); + } + }, _callee35, this, [[0, 6, 15, 18]]); + }))); + QUnit.asyncTest("Should allow yielding a non-promise", async$2(regeneratorRuntime.mark(function _callee36() { + var x; + return regeneratorRuntime.wrap(function _callee36$(_context36) { + while (1) switch (_context36.prev = _context36.next) { + case 0: + _context36.prev = 0; + _context36.next = 3; + return 3; + + case 3: + x = _context36.sent; + + QUnit.equal(x, 3, "Could yield a non-promise"); + _context36.next = 10; + break; + + case 7: + _context36.prev = 7; + _context36.t0 = _context36['catch'](0); + + QUnit.ok(false, "Yielding a non-Thenable wasn't be allowed"); + + case 10: + _context36.prev = 10; + + QUnit.start(); + return _context36.finish(10); + + case 13: + case 'end': + return _context36.stop(); + } + }, _callee36, this, [[0, 7, 10, 13]]); + }))); + QUnit.asyncTest("Should allow yielding an array with a mix of values and thenables", async$2(regeneratorRuntime.mark(function _callee37() { + var results; + return regeneratorRuntime.wrap(function _callee37$(_context37) { + while (1) switch (_context37.prev = _context37.next) { + case 0: + _context37.prev = 0; + _context37.next = 3; + return [1, 2, Dexie.Promise.resolve(3)]; + + case 3: + results = _context37.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"); + _context37.next = 13; + break; + + case 10: + _context37.prev = 10; + _context37.t0 = _context37['catch'](0); + + QUnit.ok(false, "Got exception when trying to do yield an array of mixed values/promises"); + + case 13: + _context37.prev = 13; + + QUnit.start(); + return _context37.finish(13); + + case 16: + case 'end': + return _context37.stop(); + } + }, _callee37, this, [[0, 10, 13, 16]]); + }))); + QUnit.asyncTest("Should allow yielding an array of non-promises only", async$2(regeneratorRuntime.mark(function _callee38() { + var results; + return regeneratorRuntime.wrap(function _callee38$(_context38) { + while (1) switch (_context38.prev = _context38.next) { + case 0: + _context38.prev = 0; + _context38.next = 3; + return [1, 2, 3]; + + case 3: + results = _context38.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"); + _context38.next = 13; + break; + + case 10: + _context38.prev = 10; + _context38.t0 = _context38['catch'](0); + + QUnit.ok(false, _context38.t0); + + case 13: + _context38.prev = 13; + + QUnit.start(); + return _context38.finish(13); + + case 16: + case 'end': + return _context38.stop(); + } + }, _callee38, this, [[0, 10, 13, 16]]); + }))); + QUnit.asyncTest("Should allow yielding an empty array", async$2(regeneratorRuntime.mark(function _callee39() { + var results; + return regeneratorRuntime.wrap(function _callee39$(_context39) { + while (1) switch (_context39.prev = _context39.next) { + case 0: + _context39.prev = 0; + _context39.next = 3; + return []; + + case 3: + results = _context39.sent; + + QUnit.equal(results.length, 0, "Yielded array is of size 0"); + _context39.next = 10; + break; + + case 7: + _context39.prev = 7; + _context39.t0 = _context39['catch'](0); + + QUnit.ok(false, _context39.t0); + + case 10: + _context39.prev = 10; + + QUnit.start(); + return _context39.finish(10); + + case 13: + case 'end': + return _context39.stop(); + } + }, _callee39, this, [[0, 7, 10, 13]]); + }))); + QUnit.asyncTest("Should allow yielding an array of different kind of any kind of promise", function () { + spawn(regeneratorRuntime.mark(function _callee40() { + var results; + return regeneratorRuntime.wrap(function _callee40$(_context40) { + while (1) switch (_context40.prev = _context40.next) { + case 0: + _context40.next = 2; + return [Promise.resolve(1), Dexie.Promise.resolve(2), Promise.resolve(3)]; + + case 2: + results = _context40.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 _context40.abrupt('return', 4); + + case 8: + case 'end': + return _context40.stop(); + } + }, _callee40, this); + })).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(regeneratorRuntime.mark(function _callee41() { + return regeneratorRuntime.wrap(function _callee41$(_context41) { + while (1) switch (_context41.prev = _context41.next) { + case 0: + _context41.prev = 0; + _context41.next = 3; + return Promise.resolve(3); + + case 3: + QUnit.ok(true, "yielded a value"); + throw "error"; + + case 7: + _context41.prev = 7; + _context41.t0 = _context41['catch'](0); + + QUnit.ok(_context41.t0 === "error", "Catched exception: " + _context41.t0); + + case 10: + return _context41.abrupt('return', 4); + + case 11: + case 'end': + return _context41.stop(); + } + }, _callee41, this, [[0, 7]]); + })).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(regeneratorRuntime.mark(function _callee42() { + return regeneratorRuntime.wrap(function _callee42$(_context42) { + while (1) switch (_context42.prev = _context42.next) { + case 0: + _context42.prev = 0; + _context42.next = 3; + return 3; + + case 3: + QUnit.ok(true, "yielded a value"); + throw "error"; + + case 7: + _context42.prev = 7; + _context42.t0 = _context42['catch'](0); + + QUnit.ok(_context42.t0 === "error", "Catched exception: " + _context42.t0); + + case 10: + return _context42.abrupt('return', 4); + + case 11: + case 'end': + return _context42.stop(); + } + }, _callee42, this, [[0, 7]]); + }))).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(regeneratorRuntime.mark(function _callee43() { + return regeneratorRuntime.wrap(function _callee43$(_context43) { + while (1) switch (_context43.prev = _context43.next) { + case 0: + _context43.prev = 0; + throw "error"; + + case 4: + _context43.prev = 4; + _context43.t0 = _context43['catch'](0); + + QUnit.ok(_context43.t0 === "error", "Catched exception: " + _context43.t0); + + case 7: + return _context43.abrupt('return', 4); + + case 8: + case 'end': + return _context43.stop(); + } + }, _callee43, this, [[0, 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(regeneratorRuntime.mark(function _callee44() { + return regeneratorRuntime.wrap(function _callee44$(_context44) { + while (1) switch (_context44.prev = _context44.next) { + case 0: + _context44.prev = 0; + _context44.next = 3; + return new Promise(function (resolve, reject) { + reject("fault fault!"); + }); + + case 3: + QUnit.ok(false, "Shouldn't come here"); + _context44.next = 9; + break; + + case 6: + _context44.prev = 6; + _context44.t0 = _context44['catch'](0); + + QUnit.ok(_context44.t0 === "fault fault!", "Catched exception: " + _context44.t0); + + case 9: + return _context44.abrupt('return', 4); + + case 10: + case 'end': + return _context44.stop(); + } + }, _callee44, this, [[0, 6]]); + })).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(regeneratorRuntime.mark(function _callee45() { + return regeneratorRuntime.wrap(function _callee45$(_context45) { + while (1) switch (_context45.prev = _context45.next) { + case 0: + _context45.prev = 0; + _context45.next = 3; + return [1, 2, new Promise(function (resolve, reject) { + reject("fault fault!"); + }), 4]; + + case 3: + QUnit.ok(false, "Shouldn't come here"); + _context45.next = 9; + break; + + case 6: + _context45.prev = 6; + _context45.t0 = _context45['catch'](0); + + QUnit.ok(_context45.t0 === "fault fault!", "Catched exception: " + _context45.t0); + + case 9: + return _context45.abrupt('return', 4); + + case 10: + case 'end': + return _context45.stop(); + } + }, _callee45, this, [[0, 6]]); + })).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(regeneratorRuntime.mark(function _callee46() { + return regeneratorRuntime.wrap(function _callee46$(_context46) { + while (1) switch (_context46.prev = _context46.next) { + case 0: + return _context46.abrupt('return', Promise.resolve(3)); + + case 1: + case 'end': + return _context46.stop(); + } + }, _callee46, this); + })).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(regeneratorRuntime.mark(function _callee47() { + return regeneratorRuntime.wrap(function _callee47$(_context47) { + while (1) switch (_context47.prev = _context47.next) { + case 0: + _context47.next = 2; + return Promise.resolve(3); + + case 2: + return _context47.abrupt('return', _context47.sent); + + case 3: + case 'end': + return _context47.stop(); + } + }, _callee47, this); + })).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(regeneratorRuntime.mark(function _callee48() { + var x, y; + return regeneratorRuntime.wrap(function _callee48$(_context48) { + while (1) switch (_context48.prev = _context48.next) { + case 0: + _context48.next = 2; + return [1, 2, Promise.resolve(3)]; + + case 2: + x = _context48.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(); + + case 8: + case 'end': + return _context48.stop(); + } + }, _callee48, this); + }))); + QUnit.asyncTest("Calling sub async function", async$2(regeneratorRuntime.mark(function _callee49() { + var addFriend, deleteFriends, foo, bar, numDeleted; + return regeneratorRuntime.wrap(function _callee49$(_context51) { + while (1) switch (_context51.prev = _context51.next) { + case 0: + addFriend = async$2(regeneratorRuntime.mark(function addFriend(friend) { + var friendId; + return regeneratorRuntime.wrap(function addFriend$(_context49) { + while (1) switch (_context49.prev = _context49.next) { + case 0: + _context49.next = 2; + return db$4.friends.add(friend); + + case 2: + friendId = _context49.sent; + _context49.next = 5; + return db$4.friends.get(friendId); + + case 5: + return _context49.abrupt('return', _context49.sent); + + case 6: + case 'end': + return _context49.stop(); + } + }, addFriend, this); + })); + deleteFriends = async$2(regeneratorRuntime.mark(function deleteFriends() { + return regeneratorRuntime.wrap(function deleteFriends$(_context50) { + while (1) switch (_context50.prev = _context50.next) { + case 0: + _context50.next = 2; + return db$4.friends.where('name').anyOf("Foo", "Bar").delete(); + + case 2: + return _context50.abrupt('return', _context50.sent); + + case 3: + case 'end': + return _context50.stop(); + } + }, deleteFriends, this); + })); + _context51.prev = 2; + _context51.next = 5; + return addFriend({ name: "Foo" }); + + case 5: + foo = _context51.sent; + _context51.next = 8; + return addFriend({ name: "Bar" }); + + case 8: + bar = _context51.sent; + + QUnit.ok(foo.name == "Foo", "Foo got its name"); + QUnit.ok(bar.name == "Bar", "Bar got its name"); + _context51.next = 13; + return deleteFriends(); + + case 13: + numDeleted = _context51.sent; + + QUnit.ok(true, numDeleted + " friends successfully deleted"); + _context51.next = 20; + break; + + case 17: + _context51.prev = 17; + _context51.t0 = _context51['catch'](2); + + QUnit.ok(false, _context51.t0); + + case 20: + _context51.prev = 20; + + QUnit.start(); + return _context51.finish(20); + + case 23: + case 'end': + return _context51.stop(); + } + }, _callee49, this, [[2, 17, 20, 23]]); + }))); + + 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); + } + + function doFakeAutoComplete(fn) { + var to = setTimeout(fn, 1000); + clearTimeout(to); + } + + /** 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. + // By default, debug will be true only if platform is a web platform and its page is served from localhost. + 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; + + // + // 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 + // 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. + // Callbacks to call in this or next physical tick. + var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. + // 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. + // 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 : { + 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) {} + } + doFakeAutoComplete(function () { + // Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie. + asap$$1 = function (fn, args) { + setTimeout(function () { + fn.apply(null, args); + }, 0); + }; + }); + var rejection = Promise$1.reject; + + var __extends = undefined && undefined.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + 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$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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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 = 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$4(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$4(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$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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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$3(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$3(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$3(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", regeneratorRuntime.mark(function _callee51() { + return regeneratorRuntime.wrap(function _callee51$(_context53) { + while (1) switch (_context53.prev = _context53.next) { + case 0: + _context53.next = 2; + return db$5.transaction('rw', db$5.items, regeneratorRuntime.mark(function _callee50() { + var x, all; + return regeneratorRuntime.wrap(function _callee50$(_context52) { + while (1) switch (_context52.prev = _context52.next) { + case 0: + _context52.next = 2; + return Promise.resolve(3); + + case 2: + x = _context52.sent; + _context52.next = 5; + return db$5.items.bulkAdd([{ id: 'a' }, { id: 'b' }]); + + case 5: + _context52.next = 7; + return Promise.all([db$5.items.get('a'), db$5.items.get('b')]); + + case 7: + all = _context52.sent; + + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + _context52.next = 13; + return Promise.all([db$5.items.get('a'), db$5.items.get('b')]); + + case 13: + all = _context52.sent; + + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + + case 17: + case 'end': + return _context52.stop(); + } + }, _callee50, this); + })); + + case 2: + case 'end': + return _context53.stop(); + } + }, _callee51, this); + })); + spawnedTest("Even when keeping a reference to global Promise, still maintain PSD zone states", regeneratorRuntime.mark(function _callee52() { + var Promise; + return regeneratorRuntime.wrap(function _callee52$(_context54) { + while (1) switch (_context54.prev = _context54.next) { + case 0: + Promise = window.Promise; + _context54.next = 3; + return 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 3: + case 'end': + return _context54.stop(); + } + }, _callee52, this); + })); + spawnedTest("Sub Transactions with async await", regeneratorRuntime.mark(function _callee53() { + var compatible; + return regeneratorRuntime.wrap(function _callee53$(_context55) { + while (1) switch (_context55.prev = _context55.next) { + case 0: + _context55.prev = 0; + _context55.next = 3; + return idbAndPromiseCompatible.catch(function () { + return false; + }); + + case 3: + compatible = _context55.sent; + + if (compatible) { + _context55.next = 7; + break; + } + + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return _context55.abrupt('return'); + + case 7: + _context55.next = 9; + return 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 9: + _context55.next = 14; + break; + + case 11: + _context55.prev = 11; + _context55.t0 = _context55['catch'](0); + + QUnit.ok(_context55.t0.name === 'SyntaxError', "No support for native async functions in this browser"); + + case 14: + case 'end': + return _context55.stop(); + } + }, _callee53, this, [[0, 11]]); + })); + 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$3(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$3(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$3(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$3(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$3(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$3(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$3(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$3(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$3(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$3(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$3(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$3(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$3(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 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", regeneratorRuntime.mark(function _callee55() { + return regeneratorRuntime.wrap(function _callee55$(_context57) { + while (1) switch (_context57.prev = _context57.next) { + case 0: + _context57.next = 2; + return db$6.transaction("rw", db$6.users, regeneratorRuntime.mark(function _callee54() { + var id; + return regeneratorRuntime.wrap(function _callee54$(_context56) { + while (1) switch (_context56.prev = _context56.next) { + case 0: + _context56.next = 2; + return db$6.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + + case 2: + id = _context56.sent; + + QUnit.equal(id, 3); + _context56.next = 6; + return db$6.users.where('id').equals(null).toArray(); + + case 6: + QUnit.ok(false, "Should not come here"); + + case 7: + case 'end': + return _context56.stop(); + } + }, _callee54, this); + })).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e); + }); + + case 2: + _context57.t0 = QUnit; + _context57.next = 5; + return db$6.users.where('first').equals("Foo").count(); + + case 5: + _context57.t1 = _context57.sent; + + _context57.t0.equal.call(_context57.t0, _context57.t1, 0, "Should not have succeeded to add when transaction was aborted"); + + _context57.next = 9; + return 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 9: + _context57.t2 = QUnit; + _context57.next = 12; + return db$6.users.where('first').equals("Foo").count(); + + case 12: + _context57.t3 = _context57.sent; + + _context57.t2.equal.call(_context57.t2, _context57.t3, 0, "Should not have succeeded to add when transaction was aborted"); + + case 14: + case 'end': + return _context57.stop(); + } + }, _callee55, this); + })); + 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 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" + }); + 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(regeneratorRuntime.mark(function _callee56() { + var count; + return regeneratorRuntime.wrap(function _callee56$(_context58) { + while (1) switch (_context58.prev = _context58.next) { + case 0: + _context58.prev = 0; + _context58.next = 3; + return db$7.users.where("username").anyOf([]).count(); + + case 3: + count = _context58.sent; + + QUnit.equal(count, 0, "Zarro items matched the query anyOf([])"); + _context58.next = 10; + break; + + case 7: + _context58.prev = 7; + _context58.t0 = _context58['catch'](0); + + QUnit.ok(false, "Error when calling anyOf([]): " + _context58.t0); + + case 10: + _context58.prev = 10; + + QUnit.start(); + return _context58.finish(10); + + case 13: + case 'end': + return _context58.stop(); + } + }, _callee56, this, [[0, 7, 10, 13]]); + }))); + spawnedTest("#248 'modifications' object in 'updating' hook can be bizarre", regeneratorRuntime.mark(function _callee57() { + var numCreating, numUpdating, CustomDate, creatingHook, updatingHook, isDate, readingHook, testDate, testDate2, retrieved; + return regeneratorRuntime.wrap(function _callee57$(_context59) { + while (1) switch (_context59.prev = _context59.next) { + case 0: + readingHook = function readingHook(obj) { + if (obj.date && isDate(obj.date)) { + obj.date = new CustomDate(obj.date); + } + return obj; + }; + + isDate = function isDate(obj) { + // obj instanceof Date does NOT work with Safari when Date are retrieved from IDB. + return obj.getTime && obj.getDate && obj.getFullYear; + }; + + updatingHook = 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) }; + } + }; + + creatingHook = function creatingHook(primKey, obj) { + ++numCreating; + var date = obj.date; + if (date && date instanceof CustomDate) { + obj.date = new Date(date._year, date._month, date._day); + } + }; + + CustomDate = 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(); + //... + }; + + 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)); + _context59.prev = 14; + + db$7.foo.add({ id: 1, date: testDate }); + _context59.next = 18; + return db$7.foo.get(1); + + case 18: + retrieved = _context59.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 }); + _context59.next = 24; + return db$7.foo.get(1); + + case 24: + retrieved = _context59.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"); + + case 29: + _context59.prev = 29; + + db$7.foo.hook('creating').unsubscribe(creatingHook); + db$7.foo.hook('reading').unsubscribe(readingHook); + db$7.foo.hook('updating').unsubscribe(updatingHook); + return _context59.finish(29); + + case 34: + case 'end': + return _context59.stop(); + } + }, _callee57, this, [[14,, 29, 34]]); + })); + 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 = 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()", regeneratorRuntime.mark(function _callee59() { + var NUM_UPDATES, result; + return regeneratorRuntime.wrap(function _callee59$(_context61) { + while (1) switch (_context61.prev = _context61.next) { + case 0: + NUM_UPDATES = 2000; + _context61.next = 3; + return db$7.transaction('rw', db$7.foo, regeneratorRuntime.mark(function _callee58() { + var i; + return regeneratorRuntime.wrap(function _callee58$(_context60) { + while (1) switch (_context60.prev = _context60.next) { + case 0: + _context60.next = 2; + return db$7.foo.put({ id: 1, value: 0 }); + + case 2: + for (i = 0; i < NUM_UPDATES; ++i) { + db$7.foo.where('id').equals(1).modify(function (item) { + return ++item.value; + }); + } + _context60.next = 5; + return db$7.foo.get(1); + + case 5: + return _context60.abrupt('return', _context60.sent); + + case 6: + case 'end': + return _context60.stop(); + } + }, _callee58, this); + })); + + case 3: + result = _context61.sent; + + QUnit.equal(result.value, NUM_UPDATES, "Should have updated id 1 a " + NUM_UPDATES + " times"); + + case 5: + case 'end': + return _context61.stop(); + } + }, _callee59, this); + })); + + 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)"); + }); + + /** + * 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(regeneratorRuntime.mark(function reset() { + return regeneratorRuntime.wrap(function reset$(_context62) { + while (1) switch (_context62.prev = _context62.next) { + case 0: + unsubscribeHooks(); + _context62.next = 3; + return all(ourTables.map(function (table) { + return table.clear(); + })); + + case 3: + subscrubeHooks(); + opLog = []; + successLog = []; + errorLog = []; + watchSuccess = false; + watchError = false; + deliverKeys = []; + deliverModifications = null; + deliverKeys2 = []; + deliverModifications2 = null; + opLog2 = []; + successLog2 = []; + errorLog2 = []; + transLog = []; + + case 17: + case 'end': + return _context62.stop(); + } + }, reset, this); + })); + /*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(regeneratorRuntime.mark(function _callee60(expected, modifyer) { + return regeneratorRuntime.wrap(function _callee60$(_context63) { + while (1) switch (_context63.prev = _context63.next) { + case 0: + _context63.next = 2; + return reset(); + + case 2: + _context63.next = 4; + return modifyer(); + + case 4: + 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"); + _context63.next = 8; + return reset(); + + case 8: + watchSuccess = true; + watchError = true; + _context63.next = 12; + return modifyer(); + + case 12: + 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; + })) { + _context63.next = 27; + break; + } + + _context63.next = 19; + return reset(); + + case 19: + deliverKeys = expected.map(function (x, i) { + return "Hook1Key" + i; + }); + deliverKeys2 = expected.map(function (x, i) { + return "Hook2Key" + i; + }); + watchSuccess = true; + watchError = true; + _context63.next = 25; + return modifyer(); + + case 25: + 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)"); + } + }); + + case 27: + if (!expected.some(function (x) { + return x.op === "update"; + })) { + _context63.next = 34; + break; + } + + _context63.next = 30; + return reset(); + + case 30: + deliverModifications = { "someProp.someSubProp": "someValue" }; + _context63.next = 33; + return modifyer(); + + case 33: + 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"); + } + }); + + case 34: + case 'end': + return _context63.stop(); + } + }, _callee60, this); + })); + var verifyErrorFlows = async$4(regeneratorRuntime.mark(function _callee61(modifyer) { + return regeneratorRuntime.wrap(function _callee61$(_context64) { + while (1) switch (_context64.prev = _context64.next) { + case 0: + _context64.next = 2; + return reset(); + + case 2: + QUnit.ok(true, "Verifying ERROR flows"); + watchSuccess = true; + watchError = true; + _context64.next = 7; + return modifyer(); + + case 7: + 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)); + + case 10: + case 'end': + return _context64.stop(); + } + }, _callee61, this); + })); + // + // + // Tests goes here... + // + // + // + // CREATING hook tests... + // + // Ways to produce CREATEs: + // Table.add() + // Table.put() + // Table.bulkAdd() + // Table.bulkPut() + spawnedTest("creating using Table.add()", regeneratorRuntime.mark(function _callee63() { + return regeneratorRuntime.wrap(function _callee63$(_context66) { + while (1) switch (_context66.prev = _context66.next) { + case 0: + _context66.next = 2; + return 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 2: + _context66.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee62() { + return regeneratorRuntime.wrap(function _callee62$(_context65) { + while (1) switch (_context65.prev = _context65.next) { + case 0: + _context65.next = 2; + return db$8.table1.add({ id: 1 }); + + case 2: + _context65.next = 4; + return db$8.table1.add({ id: 1 }).catch(nop$1); + + case 4: + _context65.next = 6; + return db$8.table2.add({}, 1); + + case 6: + _context65.next = 8; + return db$8.table2.add({}, 1).catch(nop$1); + + case 8: + _context65.next = 10; + return db$8.table1.add({ id: {} }).catch(nop$1); + + case 10: + case 'end': + return _context65.stop(); + } + }, _callee62, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context66.stop(); + } + }, _callee63, this); + })); + spawnedTest("creating using Table.put()", regeneratorRuntime.mark(function _callee65() { + return regeneratorRuntime.wrap(function _callee65$(_context68) { + while (1) switch (_context68.prev = _context68.next) { + case 0: + _context68.next = 2; + return 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 2: + _context68.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee64() { + return regeneratorRuntime.wrap(function _callee64$(_context67) { + while (1) switch (_context67.prev = _context67.next) { + case 0: + _context67.next = 2; + return db$8.table3.put({ idx: 1 }); + + case 2: + _context67.next = 4; + return db$8.table3.put({ idx: 1 }).catch(nop$1); + + case 4: + _context67.next = 6; + return db$8.table2.put({}, 1); + + case 6: + _context67.next = 8; + return db$8.table2.put({}, 1).catch(nop$1); + + case 8: + _context67.next = 10; + return db$8.table3.put({ id: {} }).catch(nop$1); + + case 10: + case 'end': + return _context67.stop(); + } + }, _callee64, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context68.stop(); + } + }, _callee65, this); + })); + spawnedTest("creating using Table.bulkAdd()", regeneratorRuntime.mark(function _callee68() { + return regeneratorRuntime.wrap(function _callee68$(_context71) { + while (1) switch (_context71.prev = _context71.next) { + case 0: + _context71.next = 2; + return 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, regeneratorRuntime.mark(function _callee66() { + return regeneratorRuntime.wrap(function _callee66$(_context69) { + while (1) switch (_context69.prev = _context69.next) { + case 0: + 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 }]); + + case 4: + case 'end': + return _context69.stop(); + } + }, _callee66, this); + })); + }); + + case 2: + _context71.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee67() { + return regeneratorRuntime.wrap(function _callee67$(_context70) { + while (1) switch (_context70.prev = _context70.next) { + case 0: + _context70.next = 2; + return db$8.table1.bulkAdd([{ id: 1 }, { id: 1 }]).catch(nop$1); + + case 2: + _context70.next = 4; + return db$8.table1.bulkAdd([{ id: 2 }, { id: 2 }, { id: 3 }]).catch(nop$1); + + case 4: + _context70.next = 6; + return db$8.table2.bulkAdd([{}, {}], [1, 1]).catch(nop$1); + + case 6: + _context70.next = 8; + return db$8.table2.bulkAdd([{}, {}, {}], [2, 2, 3]).catch(nop$1); + + case 8: + _context70.next = 10; + return db$8.table1.bulkAdd([{ id: {} }]).catch(nop$1); + + case 10: + case 'end': + return _context70.stop(); + } + }, _callee67, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context71.stop(); + } + }, _callee68, this); + })); + spawnedTest("creating using Table.bulkPut()", regeneratorRuntime.mark(function _callee71() { + return regeneratorRuntime.wrap(function _callee71$(_context74) { + while (1) switch (_context74.prev = _context74.next) { + case 0: + _context74.next = 2; + return 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, regeneratorRuntime.mark(function _callee69() { + return regeneratorRuntime.wrap(function _callee69$(_context72) { + while (1) switch (_context72.prev = _context72.next) { + case 0: + _context72.next = 2; + return db$8.table1.bulkPut([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + + case 2: + _context72.next = 4; + return db$8.table2.bulkPut([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + + case 4: + _context72.next = 6; + return db$8.table3.bulkPut([{ idx: 13 }, { idx: 13.2 }]); + + case 6: + _context72.next = 8; + return db$8.table4.bulkPut([{ idx: 14 }, { idx: 14.2 }]); + + case 8: + case 'end': + return _context72.stop(); + } + }, _callee69, this); + })); + }); + + case 2: + _context74.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee70() { + return regeneratorRuntime.wrap(function _callee70$(_context73) { + while (1) switch (_context73.prev = _context73.next) { + case 0: + _context73.next = 2; + return db$8.table3.bulkPut([{ idx: 1 }, { idx: 1 }]).catch(nop$1); + + case 2: + _context73.next = 4; + return db$8.table3.bulkPut([{ idx: 2 }, { idx: 2 }, { idx: 3 }]).catch(nop$1); + + case 4: + _context73.next = 6; + return db$8.table1.bulkPut([{ id: {} }]).catch(nop$1); + + case 6: + case 'end': + return _context73.stop(); + } + }, _callee70, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context74.stop(); + } + }, _callee71, this); + })); + // + // 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", regeneratorRuntime.mark(function _callee73() { + var readOps, readOps2; + return regeneratorRuntime.wrap(function _callee73$(_context76) { + while (1) switch (_context76.prev = _context76.next) { + case 0: + _context76.next = 2; + return 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', regeneratorRuntime.mark(function _callee72() { + return regeneratorRuntime.wrap(function _callee72$(_context75) { + while (1) switch (_context75.prev = _context75.next) { + case 0: + _context75.next = 2; + return db$8.table5.bulkAdd([{ foo: "bar" }, { fee: "bore" }], [1, 2]); + + case 2: + _context75.next = 4; + return db$8.table5.toArray(); + + case 4: + _context75.next = 6; + return db$8.table5.reverse().each(function (x) {}); + + case 6: + _context75.next = 8; + return db$8.table5.orderBy(':id').first(); + + case 8: + _context75.next = 10; + return db$8.table5.orderBy(':id').last(); + + case 10: + _context75.next = 12; + return db$8.table5.filter(function (x) { + return false; + }).toArray(); + + case 12: + case 'end': + return _context75.stop(); + } + }, _callee72, this); + })); + }); + + case 2: + 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"); + + case 4: + case 'end': + return _context76.stop(); + } + }, _callee73, this); + })); + // + // UPDATING hooks test + // Ways to produce UPDATEs: + // Table.put() + // Table.bulkPut() + // Table.update() + // Collection.modify() + spawnedTest("updating using Table.put()", regeneratorRuntime.mark(function _callee76() { + return regeneratorRuntime.wrap(function _callee76$(_context79) { + while (1) switch (_context79.prev = _context79.next) { + case 0: + _context79.next = 2; + return 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, regeneratorRuntime.mark(function _callee74() { + return regeneratorRuntime.wrap(function _callee74$(_context77) { + while (1) switch (_context77.prev = _context77.next) { + case 0: + db$8.table1.put({ id: 1, address: { city: 'A' } }); // create + db$8.table1.put({ id: 1, address: { city: 'B' } }); // update + + case 2: + case 'end': + return _context77.stop(); + } + }, _callee74, this); + })); + }); + + case 2: + _context79.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee75() { + return regeneratorRuntime.wrap(function _callee75$(_context78) { + while (1) switch (_context78.prev = _context78.next) { + case 0: + _context78.next = 2; + return db$8.table3.add({ id: 1, idx: 1 }); + + case 2: + _context78.next = 4; + return db$8.table3.put({ id: 2, idx: 1 }).catch(nop$1); + + case 4: + _context78.next = 6; + return db$8.table3.put({ id: {} }).catch(nop$1); + + case 6: + case 'end': + return _context78.stop(); + } + }, _callee75, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context79.stop(); + } + }, _callee76, this); + })); + spawnedTest("updating using Table.bulkPut()", regeneratorRuntime.mark(function _callee79() { + return regeneratorRuntime.wrap(function _callee79$(_context82) { + while (1) switch (_context82.prev = _context82.next) { + case 0: + _context82.next = 2; + return 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, regeneratorRuntime.mark(function _callee77() { + return regeneratorRuntime.wrap(function _callee77$(_context80) { + while (1) switch (_context80.prev = _context80.next) { + case 0: + db$8.table1.put({ id: 1, address: { city: 'A' } }); // create + db$8.table1.put({ id: 1, address: { city: 'B' } }); // update + + case 2: + case 'end': + return _context80.stop(); + } + }, _callee77, this); + })); + }); + + case 2: + _context82.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee78() { + return regeneratorRuntime.wrap(function _callee78$(_context81) { + while (1) switch (_context81.prev = _context81.next) { + case 0: + _context81.next = 2; + return db$8.table4.add({ idx: 1 }, 1); + + case 2: + _context81.next = 4; + return db$8.table4.bulkPut([{ idx: 1 }], [2]).catch(nop$1); + + case 4: + _context81.next = 6; + return db$8.table3.bulkPut([{}], [{}]).catch(nop$1); + + case 6: + case 'end': + return _context81.stop(); + } + }, _callee78, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context82.stop(); + } + }, _callee79, this); + })); + spawnedTest("updating using Table.update()", regeneratorRuntime.mark(function _callee82() { + return regeneratorRuntime.wrap(function _callee82$(_context85) { + while (1) switch (_context85.prev = _context85.next) { + case 0: + _context85.next = 2; + return 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, regeneratorRuntime.mark(function _callee80() { + return regeneratorRuntime.wrap(function _callee80$(_context83) { + while (1) switch (_context83.prev = _context83.next) { + case 0: + _context83.next = 2; + return db$8.table1.add({ id: 1, address: { city: 'A' } }); + + case 2: + _context83.next = 4; + return db$8.table1.update(1, { "address.city": "B" }); + + case 4: + case 'end': + return _context83.stop(); + } + }, _callee80, this); + })); + }); + + case 2: + _context85.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee81() { + return regeneratorRuntime.wrap(function _callee81$(_context84) { + while (1) switch (_context84.prev = _context84.next) { + case 0: + _context84.next = 2; + return db$8.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }]); + + case 2: + _context84.next = 4; + return db$8.table3.update(1, { idx: 2 }).catch(nop$1); + + case 4: + _context84.next = 6; + return db$8.table3.update(1, 3).catch(nop$1); + + case 6: + case 'end': + return _context84.stop(); + } + }, _callee81, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context85.stop(); + } + }, _callee82, this); + })); + spawnedTest("updating using Collection.modify()", regeneratorRuntime.mark(function _callee85() { + return regeneratorRuntime.wrap(function _callee85$(_context88) { + while (1) switch (_context88.prev = _context88.next) { + case 0: + _context88.next = 2; + return 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, regeneratorRuntime.mark(function _callee83() { + return regeneratorRuntime.wrap(function _callee83$(_context86) { + while (1) switch (_context86.prev = _context86.next) { + case 0: + _context86.next = 2; + return db$8.table1.add({ id: 1, address: { city: 'A' } }); + + case 2: + _context86.next = 4; + return db$8.table1.where('id').equals(1).modify({ "address.city": "B" }); + + case 4: + case 'end': + return _context86.stop(); + } + }, _callee83, this); + })); + }); + + case 2: + _context88.next = 4; + return verifyErrorFlows(function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee84() { + return regeneratorRuntime.wrap(function _callee84$(_context87) { + while (1) switch (_context87.prev = _context87.next) { + case 0: + _context87.next = 2; + return db$8.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }]); + + case 2: + _context87.next = 4; + return db$8.table3.where('id').equals(1).modify({ idx: 2 }).catch(nop$1); + + case 4: + _context87.next = 6; + return db$8.table3.where('id').equals(1).modify(function () { + throw "apa"; + }).catch(nop$1); + + case 6: + case 'end': + return _context87.stop(); + } + }, _callee84, this); + })).catch(nop$1); + }); + + case 4: + case 'end': + return _context88.stop(); + } + }, _callee85, this); + })); + // + // 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)", regeneratorRuntime.mark(function _callee87() { + return regeneratorRuntime.wrap(function _callee87$(_context90) { + while (1) switch (_context90.prev = _context90.next) { + case 0: + _context90.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee86() { + return regeneratorRuntime.wrap(function _callee86$(_context89) { + while (1) switch (_context89.prev = _context89.next) { + case 0: + _context89.next = 2; + return db$8.table1.add({ id: 1 }); + + case 2: + _context89.next = 4; + return db$8.table1.delete(1); + + case 4: + case 'end': + return _context89.stop(); + } + }, _callee86, this); + })); + }); + + case 2: + case 'end': + return _context90.stop(); + } + }, _callee87, this); + })); + spawnedTest("deleting using Table.bulkDelete(key)", regeneratorRuntime.mark(function _callee89() { + return regeneratorRuntime.wrap(function _callee89$(_context92) { + while (1) switch (_context92.prev = _context92.next) { + case 0: + _context92.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee88() { + return regeneratorRuntime.wrap(function _callee88$(_context91) { + while (1) switch (_context91.prev = _context91.next) { + case 0: + _context91.next = 2; + return db$8.table1.add({ id: 1 }); + + case 2: + _context91.next = 4; + return db$8.table1.bulkDelete([1]); + + case 4: + case 'end': + return _context91.stop(); + } + }, _callee88, this); + })); + }); + + case 2: + case 'end': + return _context92.stop(); + } + }, _callee89, this); + })); + spawnedTest("deleting using Table.clear()", regeneratorRuntime.mark(function _callee91() { + return regeneratorRuntime.wrap(function _callee91$(_context94) { + while (1) switch (_context94.prev = _context94.next) { + case 0: + _context94.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee90() { + return regeneratorRuntime.wrap(function _callee90$(_context93) { + while (1) switch (_context93.prev = _context93.next) { + case 0: + _context93.next = 2; + return db$8.table1.add({ id: 1 }); + + case 2: + _context93.next = 4; + return db$8.table1.clear(); + + case 4: + case 'end': + return _context93.stop(); + } + }, _callee90, this); + })); + }); + + case 2: + case 'end': + return _context94.stop(); + } + }, _callee91, this); + })); + spawnedTest("deleting using Table.modify()", regeneratorRuntime.mark(function _callee93() { + return regeneratorRuntime.wrap(function _callee93$(_context96) { + while (1) switch (_context96.prev = _context96.next) { + case 0: + _context96.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee92() { + return regeneratorRuntime.wrap(function _callee92$(_context95) { + while (1) switch (_context95.prev = _context95.next) { + case 0: + _context95.next = 2; + return db$8.table1.add({ id: 1 }); + + case 2: + _context95.next = 4; + return db$8.table1.where('id').between(0, 2).modify(function () { + delete this.value; + }); + + case 4: + case 'end': + return _context95.stop(); + } + }, _callee92, this); + })); + }); + + case 2: + case 'end': + return _context96.stop(); + } + }, _callee93, this); + })); + spawnedTest("deleting using Collection.delete()", regeneratorRuntime.mark(function _callee95() { + return regeneratorRuntime.wrap(function _callee95$(_context98) { + while (1) switch (_context98.prev = _context98.next) { + case 0: + _context98.next = 2; + return expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { + return db$8.transaction('rw', db$8.tables, regeneratorRuntime.mark(function _callee94() { + return regeneratorRuntime.wrap(function _callee94$(_context97) { + while (1) switch (_context97.prev = _context97.next) { + case 0: + _context97.next = 2; + return db$8.table1.add({ id: 1 }); + + case 2: + _context97.next = 4; + return db$8.table1.where('id').between(0, 2).delete(); + + case 4: + case 'end': + return _context97.stop(); + } + }, _callee94, this); + })); + }); + + case 2: + case 'end': + return _context98.stop(); + } + }, _callee95, this); + })); + + 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$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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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$5(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$5(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$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; + return { next: verb(0), "throw": verb(1), "return": verb(2) }; + 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$6(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$6(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, _b, x; + return __generator$6(this, function (_c) { + switch (_c.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, [_c.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 = _c.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$6(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