diff --git a/addons/Dexie.Observable/dist/README.md b/addons/Dexie.Observable/dist/README.md deleted file mode 100644 index 9f81d49ef..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/dexie/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..8a836e7e5 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.d.ts @@ -0,0 +1,116 @@ +// Type definitions for dexie-observable v4.0.1-beta.13 +// Project: https://github.com/dexie/Dexie.js/tree/master/addons/Dexie.Observable +// Definitions by: David Fahlander + +import Dexie, { DexieEventSet } from 'dexie'; +import { IDatabaseChange } from '../api'; + +export interface SyncNodeConstructor { + new() : SyncNode; +} + +// +// Interfaces of Dexie.Observable +// + + +/** + * 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. + */ +export 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. +} + +export interface ObservableEventSet extends 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; +} + +// +// 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: { + version: string; + SyncNode: 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: SyncNode; + + _changes: Dexie.Table; + _syncNodes: Dexie.Table; + _intercomm: Dexie.Table; + } + + // 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: MessageEvent)=>any): void; + } + + // Extended IndexSpec with uuid boolean for primary key. + interface IndexSpec { + uuid: boolean; + } + + interface DexieConstructor { + Observable: { + (db: Dexie) : void; + + version: string; + createUUID: () => string; + on: ObservableEventSet; + localStorageImpl: { + setItem(key: string, value: string): void, + getItem(key: string): string, + removeItem(key: string): void; + }; + _onStorage: (event: StorageEvent) => 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..6ad2cacc0 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js @@ -0,0 +1,1010 @@ +/* ========================================================================== + * 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} + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; + +function nop() { } +function promisableChain(f1, f2) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res && typeof res.then === 'function') { + var thiz = this, args = arguments; + return res.then(function () { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; +} +function createUUID() { + // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript + var d = Date.now(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = (d + Math.random() * 16) % 16 | 0; + d = Math.floor(d / 16); + return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16); + }); + return uuid; +} + +function initOverrideCreateTransaction(db, wakeupObservers) { + return function overrideCreateTransaction(origFunc) { + return function (mode, storenames, dbschema, parent) { + if (db.dynamicallyOpened()) + return origFunc.apply(this, arguments); // Don't observe dynamically opened databases. + var addChanges = false; + if (mode === 'readwrite' && storenames.some(function (storeName) { + return dbschema[storeName] && dbschema[storeName].observable; + })) { + // At least one included store is a observable store. Make sure to also include the _changes store. + addChanges = true; + storenames = storenames.slice(0); // Clone + if (storenames.indexOf("_changes") === -1) + storenames.push("_changes"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla) + } + // Call original db._createTransaction() + var trans = origFunc.call(this, mode, storenames, dbschema, parent); + // If this transaction is bound to any observable table, make sure to add changes when transaction completes. + if (addChanges) { + trans._lastWrittenRevision = 0; + trans.on('complete', function () { + if (trans._lastWrittenRevision) { + // Changes were written in this transaction. + if (!parent) { + // This is root-level transaction, i.e. a physical commit has happened. + // Delay-trigger a wakeup call: + if (wakeupObservers.timeoutHandle) + clearTimeout(wakeupObservers.timeoutHandle); + wakeupObservers.timeoutHandle = setTimeout(function () { + delete wakeupObservers.timeoutHandle; + wakeupObservers(trans._lastWrittenRevision); + }, 25); + } + else { + // This is just a virtual commit of a sub transaction. + // Wait with waking up observers until root transaction has committed. + // Make sure to mark root transaction so that it will wakeup observers upon commit. + var rootTransaction = (function findRootTransaction(trans) { + return trans.parent ? findRootTransaction(trans.parent) : trans; + })(parent); + rootTransaction._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rootTransaction.lastWrittenRevision || 0); + } + } + }); + // Derive "source" property from parent transaction by default + if (trans.parent && trans.parent.source) + trans.source = trans.parent.source; + } + return trans; + }; + }; +} + +function initWakeupObservers(db, Observable, localStorage) { + return function wakeupObservers(lastWrittenRevision) { + // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too. + if (Observable.latestRevision[db.name] < lastWrittenRevision) { + // Set the static property lastRevision[db.name] to the revision of the last written change. + Observable.latestRevision[db.name] = lastWrittenRevision; + // Wakeup ourselves, and any other db instances on this window: + Dexie.ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision); + }); + // Observable.on.latestRevisionIncremented will only wakeup db's in current window. + // We need a storage event to wakeup other windwos. + // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for + // the purpose to wakeup db instances in other windows. + if (localStorage) + localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id. + } + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function initCreatingHook(db, table) { + return function creatingHook(primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = Dexie.Observable.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 && event.key.indexOf("Dexie.Observable/") === 0) { // For example "Dexie.Observable/latestRevision/FriendsDB" + 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$2 = 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$2.reject(new Dexie.DatabaseClosedError()) : + Promise$2.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 // If we couldn't find a node -> send to master + 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$2(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$2.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$2.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} + * + * https://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$1 = Dexie.Promise; +var browserIsShuttingDown = false; +/** Dexie addon for change tracking and real-time observation. + * + * @param {Dexie} db + */ +function Observable(db) { + if (!/^(3|4)\./.test(Dexie.version)) + throw new Error("Missing dexie version 3.x or 4.x"); + if (db.observable) { + if (db.observable.version !== "{version}") + throw new Error("Mixed versions of dexie-observable"); + return; // Addon already active. + } + 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 = { version: "{version}" }; + 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._syncNodes.put(mySyncNode.node).then(Dexie.ignoreTransaction(function () { + // By default, this node will become master unless we discover an existing, up-to-date master + var mySyncNodeShouldBecomeMaster = 1; + return db._syncNodes.orderBy('isMaster').reverse().modify(function (existingNode) { + if (existingNode.isMaster) { + if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Existing master record is out-of-date; demote it + existingNode.isMaster = 0; + } + else { + // An existing up-to-date master record exists, so it will remain master + mySyncNodeShouldBecomeMaster = 0; + } + } + // The local node reference may be unassigned at any point by a database close() operation + if (!mySyncNode.node) + return; + // Assign the local node state + // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause + if (existingNode.id === mySyncNode.node.id) { + existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster; + } + }); + })).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().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$1.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$1.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.version = "{version}"; +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 === null || global === void 0 ? void 0 : global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); +} +if (Dexie.Observable) { + if (Dexie.Observable.version !== "{version}") { + throw new Error("Mixed versions of dexie-observable"); + } +} +else { + // Register addon: + Dexie.Observable = Observable; + Dexie.addons.push(Observable); +} +var Dexie_Observable = Dexie.Observable; + +export { Dexie_Observable as default }; +//# 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..1afb48493 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.es.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.es.js","sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/change_types.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/on-storage.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js"],"sourcesContent":["export function nop() {}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function() {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\n });\n return uuid;\n}\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1)\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = (function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n })(parent);\n rootTransaction._lastWrittenRevision = Math.max(\n trans._lastWrittenRevision,\n rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n if (localStorage) localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = Dexie.Observable.createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: table.name,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n };\n}\n","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n };\n}\n","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n })\n .catch((e) => {\n console.log(obj)\n console.log(e.stack)\n })\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n };\n}\n","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key && event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n };\n}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(origFunc) {\n return function(stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function(tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function(tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * https://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\n/** Dexie addon for change tracking and real-time observation.\n * \n * @param {Dexie} db \n */\nfunction Observable(db) {\n if (!/^(3|4)\\./.test(Dexie.version))\n throw new Error(`Missing dexie version 3.x or 4.x`);\n if (db.observable) {\n if (db.observable.version !== \"{version}\") throw new Error(`Mixed versions of dexie-observable`);\n return; // Addon already active.\n }\n\n var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n db.observable = {version: \"{version}\"};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode.node = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\n\n db.close = override(db.close, function(origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function(origDelete) {\n return function() {\n return origDelete.apply(this, arguments).then(function(result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n \n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = (lastChange ? lastChange.rev : 0);\n mySyncNode.node = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function() {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db._syncNodes.put(mySyncNode.node).then(Dexie.ignoreTransaction(() => {\n // By default, this node will become master unless we discover an existing, up-to-date master\n var mySyncNodeShouldBecomeMaster = 1;\n return db._syncNodes.orderBy('isMaster').reverse().modify(existingNode => {\n if (existingNode.isMaster) {\n if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Existing master record is out-of-date; demote it\n existingNode.isMaster = 0;\n } else {\n // An existing up-to-date master record exists, so it will remain master\n mySyncNodeShouldBecomeMaster = 0;\n }\n }\n\n // The local node reference may be unassigned at any point by a database close() operation\n if (!mySyncNode.node) return;\n\n // Assign the local node state\n // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause\n if (existingNode.id === mySyncNode.node.id) {\n existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster;\n }\n });\n })).then(() => {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }).then(function () {\n cleanup();\n });\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function() {\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(new Dexie.DatabaseClosedError());\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = (changes.length === LIMIT);\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n Dexie.vip(function() { // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n })\n .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted.\n // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function() {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function() {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n}\n\n//\n// Static properties and methods\n// \n\nObservable.version = \"{version}\";\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global?.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n\nif (Dexie.Observable) {\n if (Dexie.Observable.version !== \"{version}\") {\n throw new Error (`Mixed versions of dexie-observable`);\n }\n} else {\n // Register addon:\n Dexie.Observable = Observable;\n Dexie.addons.push(Observable);\n}\n\nexport default Dexie.Observable;\n"],"names":["Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;SAAgB,GAAG,MAAK;SAER,eAAe,CAAC,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,E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,CAAC;IAC9B,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;CACjC;AAED,uBAAe,KAAK,CAAC,UAAU;;;;"} \ 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..d9a78deb2 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js @@ -0,0 +1,1020 @@ +/* ========================================================================== + * 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 4.0.1-beta.13, Wed Oct 18 2023 + * + * https://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 = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.Dexie = global.Dexie || {}, global.Dexie.Observable = factory(global.Dexie))); +})(this, (function (Dexie) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var Dexie__default = /*#__PURE__*/_interopDefaultLegacy(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__default["default"].ignoreTransaction(function () { + Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision); + }); + // Observable.on.latestRevisionIncremented will only wakeup db's in current window. + // We need a storage event to wakeup other windwos. + // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for + // the purpose to wakeup db instances in other windows. + if (localStorage) + localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id. + } + }; + } + + // Change Types + var CREATE = 1; + var UPDATE = 2; + var DELETE = 3; + + function initCreatingHook(db, table) { + return function creatingHook(primKey, obj, trans) { + /// + var rv = undefined; + if (primKey === undefined && table.schema.primKey.uuid) { + primKey = rv = Dexie__default["default"].Observable.createUUID(); + if (table.schema.primKey.keyPath) { + Dexie__default["default"].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__default["default"].deepClone(oldObj); + for (var propPath in mods) { + var mod = mods[propPath]; + if (typeof mod === 'undefined') { + Dexie__default["default"].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__default["default"].getByKeyPath(oldObj, propPath); + if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) { + Dexie__default["default"].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 && event.key.indexOf("Dexie.Observable/") === 0) { // For example "Dexie.Observable/latestRevision/FriendsDB" + 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__default["default"].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$2 = Dexie__default["default"].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$2.reject(new Dexie__default["default"].DatabaseClosedError()) : + Promise$2.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__default["default"].extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ... + return Dexie__default["default"].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 // If we couldn't find a node -> send to master + 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$2(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__default["default"].ignoreTransaction(function () { + db._syncNodes.toArray(function (nodes) { + return Promise$2.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$2.reject(new Dexie__default["default"].DatabaseClosedError()); + return Dexie__default["default"].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__default["default"].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 4.0.1-beta.13, Wed Oct 18 2023 + * + * https://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__default["default"].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__default["default"].override; + var Promise$1 = Dexie__default["default"].Promise; + var browserIsShuttingDown = false; + /** Dexie addon for change tracking and real-time observation. + * + * @param {Dexie} db + */ + function Observable(db) { + if (!/^(3|4)\./.test(Dexie__default["default"].version)) + throw new Error("Missing dexie version 3.x or 4.x"); + if (db.observable) { + if (db.observable.version !== "4.0.1-beta.13") + throw new Error("Mixed versions of dexie-observable"); + return; // Addon already active. + } + 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__default["default"].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 = { version: "4.0.1-beta.13" }; + 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__default["default"].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__default["default"].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._syncNodes.put(mySyncNode.node).then(Dexie__default["default"].ignoreTransaction(function () { + // By default, this node will become master unless we discover an existing, up-to-date master + var mySyncNodeShouldBecomeMaster = 1; + return db._syncNodes.orderBy('isMaster').reverse().modify(function (existingNode) { + if (existingNode.isMaster) { + if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) { + // Existing master record is out-of-date; demote it + existingNode.isMaster = 0; + } + else { + // An existing up-to-date master record exists, so it will remain master + mySyncNodeShouldBecomeMaster = 0; + } + } + // The local node reference may be unassigned at any point by a database close() operation + if (!mySyncNode.node) + return; + // Assign the local node state + // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause + if (existingNode.id === mySyncNode.node.id) { + existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster; + } + }); + })).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__default["default"].vip(function () { + readChanges().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$1.reject(new Dexie__default["default"].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__default["default"].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$1.reject(new Dexie__default["default"].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__default["default"].vip(function () { + db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup); + }); + } + } + } + // + // Static properties and methods + // + Observable.version = "4.0.1-beta.13"; + Observable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37; + Observable.on = Dexie__default["default"].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 === null || global === void 0 ? void 0 : global.addEventListener) { + global.addEventListener("storage", Observable._onStorage); + global.addEventListener("beforeunload", Observable._onBeforeUnload); + } + if (Dexie__default["default"].Observable) { + if (Dexie__default["default"].Observable.version !== "4.0.1-beta.13") { + throw new Error("Mixed versions of dexie-observable"); + } + } + else { + // Register addon: + Dexie__default["default"].Observable = Observable; + Dexie__default["default"].addons.push(Observable); + } + var Dexie_Observable = Dexie__default["default"].Observable; + + return Dexie_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..d6fe708fa --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-observable.js","sources":["../src/utils.js","../src/override-create-transaction.js","../src/wakeup-observers.js","../src/change_types.js","../src/hooks/creating.js","../src/hooks/updating.js","../src/hooks/deleting.js","../src/hooks/crud-monitor.js","../src/on-storage.js","../src/override-open.js","../src/intercomm.js","../src/override-parse-stores-spec.js","../src/delete-old-changes.js","../src/Dexie.Observable.js"],"sourcesContent":["export function nop() {}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function() {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this, args = arguments;\n return res.then(function() {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n\nexport function createUUID() {\n // Decent solution from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\n var d = Date.now();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = (d + Math.random() * 16) % 16 | 0;\n d = Math.floor(d / 16);\n return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);\n });\n return uuid;\n}\n","export default function initOverrideCreateTransaction(db, wakeupObservers) {\n return function overrideCreateTransaction(origFunc) {\n return function (mode, storenames, dbschema, parent) {\n if (db.dynamicallyOpened()) return origFunc.apply(this, arguments); // Don't observe dynamically opened databases.\n var addChanges = false;\n if (mode === 'readwrite' && storenames.some(function (storeName) {\n return dbschema[storeName] && dbschema[storeName].observable;\n })) {\n // At least one included store is a observable store. Make sure to also include the _changes store.\n addChanges = true;\n storenames = storenames.slice(0); // Clone\n if (storenames.indexOf(\"_changes\") === -1)\n storenames.push(\"_changes\"); // Otherwise, firefox will hang... (I've reported the bug to Mozilla@Bugzilla)\n }\n // Call original db._createTransaction()\n var trans = origFunc.call(this, mode, storenames, dbschema, parent);\n // If this transaction is bound to any observable table, make sure to add changes when transaction completes.\n if (addChanges) {\n trans._lastWrittenRevision = 0;\n trans.on('complete', function () {\n if (trans._lastWrittenRevision) {\n // Changes were written in this transaction.\n if (!parent) {\n // This is root-level transaction, i.e. a physical commit has happened.\n // Delay-trigger a wakeup call:\n if (wakeupObservers.timeoutHandle) clearTimeout(wakeupObservers.timeoutHandle);\n wakeupObservers.timeoutHandle = setTimeout(function () {\n delete wakeupObservers.timeoutHandle;\n wakeupObservers(trans._lastWrittenRevision);\n }, 25);\n } else {\n // This is just a virtual commit of a sub transaction.\n // Wait with waking up observers until root transaction has committed.\n // Make sure to mark root transaction so that it will wakeup observers upon commit.\n var rootTransaction = (function findRootTransaction(trans) {\n return trans.parent ? findRootTransaction(trans.parent) : trans;\n })(parent);\n rootTransaction._lastWrittenRevision = Math.max(\n trans._lastWrittenRevision,\n rootTransaction.lastWrittenRevision || 0);\n }\n }\n });\n // Derive \"source\" property from parent transaction by default\n if (trans.parent && trans.parent.source) trans.source = trans.parent.source;\n }\n return trans;\n };\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initWakeupObservers(db, Observable, localStorage) {\n return function wakeupObservers(lastWrittenRevision) {\n // Make sure Observable.latestRevision[db.name] is still below our value, now when some time has elapsed and other db instances in same window possibly could have made changes too.\n if (Observable.latestRevision[db.name] < lastWrittenRevision) {\n // Set the static property lastRevision[db.name] to the revision of the last written change.\n Observable.latestRevision[db.name] = lastWrittenRevision;\n // Wakeup ourselves, and any other db instances on this window:\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(db.name, lastWrittenRevision);\n });\n // Observable.on.latestRevisionIncremented will only wakeup db's in current window.\n // We need a storage event to wakeup other windwos.\n // Since indexedDB lacks storage events, let's use the storage event from WebStorage just for\n // the purpose to wakeup db instances in other windows.\n if (localStorage) localStorage.setItem('Dexie.Observable/latestRevision/' + db.name, lastWrittenRevision); // In IE, this will also wakeup our own window. However, onLatestRevisionIncremented will work around this by only running once per revision id.\n }\n };\n}\n","// Change Types\nexport const CREATE = 1;\nexport const UPDATE = 2;\nexport const DELETE = 3;\n","import Dexie from 'dexie';\n\nimport {CREATE} from '../change_types';\n\nexport default function initCreatingHook(db, table) {\n return function creatingHook(primKey, obj, trans) {\n /// \n var rv = undefined;\n if (primKey === undefined && table.schema.primKey.uuid) {\n primKey = rv = Dexie.Observable.createUUID();\n if (table.schema.primKey.keyPath) {\n Dexie.setByKeyPath(obj, table.schema.primKey.keyPath, primKey);\n }\n }\n\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: table.name,\n key: primKey === undefined ? null : primKey,\n type: CREATE,\n obj: obj\n };\n\n var promise = db._changes.add(change).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n });\n\n // Wait for onsuccess so that we have the primKey if it is auto-incremented and update the change item if so.\n this.onsuccess = function (resultKey) {\n if (primKey != resultKey)\n promise._then(function () {\n change.key = resultKey;\n db._changes.put(change);\n });\n };\n\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n\n return rv;\n };\n}\n","import Dexie from 'dexie';\n\nimport {UPDATE} from '../change_types';\n\nexport default function initUpdatingHook(db, tableName) {\n return function updatingHook(mods, primKey, oldObj, trans) {\n /// \n // mods may contain property paths with undefined as value if the property\n // is being deleted. Since we cannot persist undefined we need to act\n // like those changes is setting the value to null instead.\n var modsWithoutUndefined = {};\n // As of current Dexie version (1.0.3) hook may be called even if it wouldn't really change.\n // Therefore we may do that kind of optimization here - to not add change entries if\n // there's nothing to change.\n var anythingChanged = false;\n var newObj = Dexie.deepClone(oldObj);\n for (var propPath in mods) {\n var mod = mods[propPath];\n if (typeof mod === 'undefined') {\n Dexie.delByKeyPath(newObj, propPath);\n modsWithoutUndefined[propPath] = null; // Null is as close we could come to deleting a property when not allowing undefined.\n anythingChanged = true;\n } else {\n var currentValue = Dexie.getByKeyPath(oldObj, propPath);\n if (mod !== currentValue && JSON.stringify(mod) !== JSON.stringify(currentValue)) {\n Dexie.setByKeyPath(newObj, propPath, mod);\n modsWithoutUndefined[propPath] = mod;\n anythingChanged = true;\n }\n }\n }\n if (anythingChanged) {\n var change = {\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: UPDATE,\n mods: modsWithoutUndefined,\n oldObj: oldObj,\n obj: newObj\n };\n var promise = db._changes.add(change); // Just so we get the correct revision order of the update...\n this.onsuccess = function () {\n promise._then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n });\n };\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n }\n };\n}\n","import {DELETE} from '../change_types';\n\nexport default function initDeletingHook(db, tableName) {\n return function deletingHook(primKey, obj, trans) {\n /// \n var promise = db._changes.add({\n source: trans.source || null, // If a \"source\" is marked on the transaction, store it. Useful for observers that want to ignore their own changes.\n table: tableName,\n key: primKey,\n type: DELETE,\n oldObj: obj\n }).then(function (rev) {\n trans._lastWrittenRevision = Math.max(trans._lastWrittenRevision, rev);\n return rev;\n })\n .catch((e) => {\n console.log(obj)\n console.log(e.stack)\n })\n this.onerror = function () {\n // If the main operation fails, make sure to regret the change.\n // Using _then because if promise is already fullfilled, the standard then() would\n // do setTimeout() and we would loose the transaction.\n promise._then(function (rev) {\n // Will only happen if app code catches the main operation error to prohibit transaction from aborting.\n db._changes.delete(rev);\n });\n };\n };\n}\n","import initCreatingHook from './creating';\nimport initUpdatingHook from './updating';\nimport initDeletingHook from './deleting';\n\nexport default function initCrudMonitor(db) {\n//\n// The Creating/Updating/Deleting hook will make sure any change is stored to the changes table\n//\n return function crudMonitor(table) {\n /// \n if (table.hook._observing) return;\n table.hook._observing = true;\n\n const tableName = table.name;\n table.hook('creating').subscribe(initCreatingHook(db, table));\n\n table.hook('updating').subscribe(initUpdatingHook(db, tableName));\n\n table.hook('deleting').subscribe(initDeletingHook(db, tableName));\n };\n}\n","import Dexie from 'dexie';\n\nexport default function initOnStorage(Observable) {\n return function onStorage(event) {\n // We use the onstorage event to trigger onLatestRevisionIncremented since we will wake up when other windows modify the DB as well!\n if (event.key && event.key.indexOf(\"Dexie.Observable/\") === 0) { // For example \"Dexie.Observable/latestRevision/FriendsDB\"\n var parts = event.key.split('/');\n var prop = parts[1];\n var dbname = parts[2];\n if (prop === 'latestRevision') {\n var rev = parseInt(event.newValue, 10);\n if (!isNaN(rev) && rev > Observable.latestRevision[dbname]) {\n Observable.latestRevision[dbname] = rev;\n Dexie.ignoreTransaction(function () {\n Observable.on('latestRevisionIncremented').fire(dbname, rev);\n });\n }\n } else if (prop.indexOf(\"deadnode:\") === 0) {\n var nodeID = parseInt(prop.split(':')[1], 10);\n if (event.newValue) {\n Observable.on.suicideNurseCall.fire(dbname, nodeID);\n }\n } else if (prop === 'intercomm') {\n if (event.newValue) {\n Observable.on.intercomm.fire(dbname);\n }\n }\n }\n };\n}\n","export default function initOverrideOpen(db, SyncNode, crudMonitor) {\n return function overrideOpen(origOpen) {\n return function () {\n //\n // Make sure to subscribe to \"creating\", \"updating\" and \"deleting\" hooks for all observable tables that were created in the stores() method.\n //\n Object.keys(db._allTables).forEach(tableName => {\n let table = db._allTables[tableName];\n if (table.schema.observable) {\n crudMonitor(table);\n }\n if (table.name === \"_syncNodes\") {\n table.mapToClass(SyncNode);\n }\n });\n return origOpen.apply(this, arguments);\n }\n };\n}\n","import Dexie from 'dexie';\n\nconst Promise = Dexie.Promise;\n\nexport default function initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage) {\n//\n// Intercommunication between nodes\n//\n// Enable inter-process communication between browser windows using localStorage storage event (is registered in Dexie.Observable)\n\n var requestsWaitingForReply = {};\n\n /**\n * @param {string} type Type of message\n * @param message Message to send\n * @param {number} destinationNode ID of destination node\n * @param {{wantReply: boolean, isFailure: boolean, requestId: number}} options If {wantReply: true}, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n */\n db.observable.sendMessage = function (type, message, destinationNode, options) {\n /// Type of message\n /// Message to send\n /// ID of destination node\n /// {wantReply: Boolean, isFailure: Boolean, requestId: Number}. If wantReply, the returned promise will complete with the reply from remote. Otherwise it will complete when message has been successfully sent.\n options = options || {};\n if (!mySyncNode.node)\n return options.wantReply ?\n Promise.reject(new Dexie.DatabaseClosedError()) :\n Promise.resolve(); // If caller doesn't want a reply, it won't catch errors either.\n\n var msg = {message: message, destinationNode: destinationNode, sender: mySyncNode.node.id, type: type};\n Dexie.extend(msg, options); // wantReply: wantReply, success: !isFailure, requestId: ...\n return Dexie.ignoreTransaction(()=> {\n var tables = [\"_intercomm\"];\n if (options.wantReply) tables.push(\"_syncNodes\"); // If caller wants a reply, include \"_syncNodes\" in transaction to check that there's a receiver there. Otherwise, new master will get it.\n var promise = db.transaction('rw', tables, () => {\n if (options.wantReply) {\n // Check that there is a receiver there to take the request.\n return db._syncNodes.where('id').equals(destinationNode).count(receiverAlive => {\n if (receiverAlive)\n return db._intercomm.add(msg);\n else // If we couldn't find a node -> send to master\n return db._syncNodes.where('isMaster').above(0).first(function (masterNode) {\n msg.destinationNode = masterNode.id;\n return db._intercomm.add(msg)\n });\n });\n } else {\n // If caller doesn't need a response, we don't have to make sure that it gets one.\n return db._intercomm.add(msg);\n }\n }).then(messageId => {\n var rv = null;\n if (options.wantReply) {\n rv = new Promise(function (resolve, reject) {\n requestsWaitingForReply[messageId.toString()] = {resolve: resolve, reject: reject};\n });\n }\n if (localStorage) {\n localStorage.setItem(\"Dexie.Observable/intercomm/\" + db.name, messageId.toString());\n }\n Observable.on.intercomm.fire(db.name);\n return rv;\n });\n\n if (!options.wantReply) {\n promise.catch(()=> {\n });\n return;\n } else {\n // Forward rejection to caller if it waits for reply.\n return promise;\n }\n });\n };\n\n // Send a message to all local _syncNodes\n db.observable.broadcastMessage = function (type, message, bIncludeSelf) {\n if (!mySyncNode.node) return;\n var mySyncNodeId = mySyncNode.node.id;\n Dexie.ignoreTransaction(()=> {\n db._syncNodes.toArray(nodes => {\n return Promise.all(nodes\n .filter(node => node.type === 'local' && (bIncludeSelf || node.id !== mySyncNodeId))\n .map(node => db.observable.sendMessage(type, message, node.id)));\n }).catch(()=> {\n });\n });\n };\n\n function consumeIntercommMessages() {\n // Check if we got messages:\n if (!mySyncNode.node) return Promise.reject(new Dexie.DatabaseClosedError());\n\n return Dexie.ignoreTransaction(()=> {\n return db.transaction('rw', '_intercomm', function() {\n return db._intercomm.where({destinationNode: mySyncNode.node.id}).toArray(messages => {\n messages.forEach(msg => consumeMessage(msg));\n return db._intercomm.where('id').anyOf(messages.map(msg => msg.id)).delete();\n });\n });\n });\n }\n\n function consumeMessage(msg) {\n if (msg.type === 'response') {\n // This is a response. Lookup pending request and fulfill its promise.\n var request = requestsWaitingForReply[msg.requestId.toString()];\n if (request) {\n if (msg.isFailure) {\n request.reject(msg.message.error);\n } else {\n request.resolve(msg.message.result);\n }\n delete requestsWaitingForReply[msg.requestId.toString()];\n }\n } else {\n // This is a message or request. Fire the event and add an API for the subscriber to use if reply is requested\n msg.resolve = function (result) {\n db.observable.sendMessage('response', {result: result}, msg.sender, {requestId: msg.id});\n };\n msg.reject = function (error) {\n db.observable.sendMessage('response', {error: error.toString()}, msg.sender, {isFailure: true, requestId: msg.id});\n };\n db.on.message.fire(msg);\n }\n }\n\n // Listener for 'intercomm' events\n // Gets fired when we get a 'storage' event from local storage or when sendMessage is called\n // 'storage' is used to communicate between tabs (sendMessage changes the localStorage to trigger the event)\n // sendMessage is used to communicate in the same tab and to trigger a storage event\n function onIntercomm(dbname) {\n // When storage event trigger us to check\n if (dbname === db.name) {\n consumeIntercommMessages().catch('DatabaseClosedError', ()=> {});\n }\n }\n\n return {\n onIntercomm,\n consumeIntercommMessages\n };\n}\n","export default function overrideParseStoresSpec(origFunc) {\n return function(stores, dbSchema) {\n // Create the _changes and _syncNodes tables\n stores[\"_changes\"] = \"++rev\";\n stores[\"_syncNodes\"] = \"++id,myRevision,lastHeartBeat,&url,isMaster,type,status\";\n stores[\"_intercomm\"] = \"++id,destinationNode\";\n stores[\"_uncommittedChanges\"] = \"++id,node\"; // For remote syncing when server returns a partial result.\n // Call default implementation. Will populate the dbSchema structures.\n origFunc.call(this, stores, dbSchema);\n // Allow UUID primary keys using $$ prefix on primary key or indexes\n Object.keys(dbSchema).forEach(function(tableName) {\n var schema = dbSchema[tableName];\n if (schema.primKey.name.indexOf('$$') === 0) {\n schema.primKey.uuid = true;\n schema.primKey.name = schema.primKey.name.substr(2);\n schema.primKey.keyPath = schema.primKey.keyPath.substr(2);\n }\n });\n // Now mark all observable tables\n Object.keys(dbSchema).forEach(function(tableName) {\n // Marked observable tables with \"observable\" in their TableSchema.\n if (tableName.indexOf('_') !== 0 && tableName.indexOf('$') !== 0) {\n dbSchema[tableName].observable = true;\n }\n });\n };\n}\n","import Dexie from 'dexie';\n\nexport default function deleteOldChanges(db) {\n // This is a background job and should never be done within\n // a caller's transaction. Use Dexie.ignoreTransaction() to ensure that.\n // We should not return the Promise but catch it ourselves instead.\n\n // To prohibit starving the database we want to lock transactions as short as possible\n // and since we're not in a hurry, we could do this job in chunks and reschedule a\n // continuation every 500 ms.\n const CHUNK_SIZE = 100;\n\n Dexie.ignoreTransaction(()=>{\n return db._syncNodes.orderBy(\"myRevision\").first(oldestNode => {\n return db._changes\n .where(\"rev\").below(oldestNode.myRevision)\n .limit(CHUNK_SIZE)\n .primaryKeys();\n }).then(keysToDelete => {\n if (keysToDelete.length === 0) return; // Done.\n return db._changes.bulkDelete(keysToDelete).then(()=> {\n // If not done garbage collecting, reschedule a continuation of it until done.\n if (keysToDelete.length === CHUNK_SIZE) {\n // Limit reached. Changes are there are more job to do. Schedule again:\n setTimeout(() => db.isOpen() && deleteOldChanges(db), 500);\n }\n });\n });\n }).catch(()=>{\n // The operation is not crucial. A failure could almost only be due to that database has been closed.\n // No need to log this.\n });\n}\n","/* ========================================================================== \n * dexie-observable.js\n * ==========================================================================\n *\n * Dexie addon for observing database changes not just on local db instance\n * but also on other instances, tabs and windows.\n *\n * Comprises a base framework for dexie-syncable.js\n *\n * By David Fahlander, david.fahlander@gmail.com,\n * Nikolas Poniros, https://github.com/nponiros\n *\n * ==========================================================================\n *\n * Version {version}, {date}\n *\n * https://dexie.org\n *\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/\n * \n */\nimport Dexie from 'dexie';\nimport { nop, promisableChain, createUUID } from './utils';\n\nimport initOverrideCreateTransaction from './override-create-transaction';\nimport initWakeupObservers from './wakeup-observers';\nimport initCrudMonitor from './hooks/crud-monitor';\nimport initOnStorage from './on-storage';\nimport initOverrideOpen from './override-open';\nimport initIntercomm from './intercomm';\n\nimport overrideParseStoresSpec from './override-parse-stores-spec';\n\nimport deleteOldChanges from './delete-old-changes';\n\nvar global = self;\n\n/** class DatabaseChange\n *\n * Object contained by the _changes table.\n */\nvar DatabaseChange = Dexie.defineClass({\n rev: Number, // Auto-incremented primary key\n source: String, // Optional source creating the change. Set if transaction.source was set when doing the operation.\n table: String, // Table name\n key: Object, // Primary key. Any type.\n type: Number, // 1 = CREATE, 2 = UPDATE, 3 = DELETE\n obj: Object, // CREATE: obj contains the object created.\n mods: Object, // UPDATE: mods contains the modifications made to the object.\n oldObj: Object // DELETE: oldObj contains the object deleted. UPDATE: oldObj contains the old object before updates applied.\n});\n\n// Import some usable helper functions\nvar override = Dexie.override;\nvar Promise = Dexie.Promise;\nvar browserIsShuttingDown = false;\n\n/** Dexie addon for change tracking and real-time observation.\n * \n * @param {Dexie} db \n */\nfunction Observable(db) {\n if (!/^(3|4)\\./.test(Dexie.version))\n throw new Error(`Missing dexie version 3.x or 4.x`);\n if (db.observable) {\n if (db.observable.version !== \"{version}\") throw new Error(`Mixed versions of dexie-observable`);\n return; // Addon already active.\n }\n\n var NODE_TIMEOUT = 20000, // 20 seconds before local db instances are timed out. This is so that old changes can be deleted when not needed and to garbage collect old _syncNodes objects.\n HIBERNATE_GRACE_PERIOD = 20000, // 20 seconds\n // LOCAL_POLL: The time to wait before polling local db for changes and cleaning up old nodes. \n // Polling for changes is a fallback only needed in certain circomstances (when the onstorage event doesnt reach all listeners - when different browser windows doesnt share the same process)\n LOCAL_POLL = 500, // 500 ms. In real-world there will be this value + the time it takes to poll(). A small value is needed in Workers where we cannot rely on storage event.\n HEARTBEAT_INTERVAL = NODE_TIMEOUT - 5000;\n\n var localStorage = Observable.localStorageImpl;\n\n /** class SyncNode\n *\n * Object contained in the _syncNodes table.\n */\n var SyncNode = Dexie.defineClass({\n //id: Number,\n myRevision: Number,\n type: String, // \"local\" or \"remote\"\n lastHeartBeat: Number,\n deleteTimeStamp: Number, // In case lastHeartBeat is too old, a value of now + HIBERNATE_GRACE_PERIOD will be set here. If reached before node wakes up, node will be deleted.\n url: String, // Only applicable for \"remote\" nodes. Only used in Dexie.Syncable.\n isMaster: Number, // 1 if true. Not using Boolean because it's not possible to index Booleans in IE implementation of IDB.\n\n // Below properties should be extended in Dexie.Syncable. Not here. They apply to remote nodes only (type == \"remote\"):\n syncProtocol: String, // Tells which implementation of ISyncProtocol to use for remote syncing. \n syncContext: null,\n syncOptions: Object,\n connected: false, // FIXTHIS: Remove! Replace with status.\n status: Number,\n appliedRemoteRevision: null,\n remoteBaseRevisions: [{ local: Number, remote: null }],\n dbUploadState: {\n tablesToUpload: [String],\n currentTable: String,\n currentKey: null,\n localBaseRevision: Number\n }\n });\n\n db.observable = {version: \"{version}\"};\n db.observable.SyncNode = SyncNode;\n\n const wakeupObservers = initWakeupObservers(db, Observable, localStorage);\n const overrideCreateTransaction = initOverrideCreateTransaction(db, wakeupObservers);\n const crudMonitor = initCrudMonitor(db);\n const overrideOpen = initOverrideOpen(db, SyncNode, crudMonitor);\n\n var mySyncNode = {node: null};\n\n const intercomm = initIntercomm(db, Observable, SyncNode, mySyncNode, localStorage);\n const onIntercomm = intercomm.onIntercomm;\n const consumeIntercommMessages = intercomm.consumeIntercommMessages;\n\n // Allow other addons to access the local sync node. May be needed by Dexie.Syncable.\n Object.defineProperty(db, \"_localSyncNode\", {\n get: function() { return mySyncNode.node; }\n });\n\n var pollHandle = null,\n heartbeatHandle = null;\n\n if (Dexie.fake) {\n // This code will never run.\n // It's here just to enable auto-complete in visual studio - helps a lot when writing code.\n db.version(1).stores({\n _syncNodes: \"++id,myRevision,lastHeartBeat\",\n _changes: \"++rev\",\n _intercomm: \"++id,destinationNode\",\n _uncommittedChanges: \"++id,node\"\n });\n db._syncNodes.mapToClass(SyncNode);\n db._changes.mapToClass(DatabaseChange);\n mySyncNode.node = new SyncNode({\n myRevision: 0,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null\n });\n }\n\n //\n // Override parsing the stores to add \"_changes\" and \"_syncNodes\" tables.\n // It also adds UUID support for the primary key and sets tables as observable tables.\n //\n db.Version.prototype._parseStoresSpec = override(db.Version.prototype._parseStoresSpec, overrideParseStoresSpec);\n\n // changes event on db:\n db.on.addEventType({\n changes: 'asap',\n cleanup: [promisableChain, nop], // fire (nodesTable, changesTable, trans). Hook called when cleaning up nodes. Subscribers may return a Promise to to more stuff. May do additional stuff if local sync node is master.\n message: 'asap'\n });\n\n //\n // Override transaction creation to always include the \"_changes\" store when any observable store is involved.\n //\n db._createTransaction = override(db._createTransaction, overrideCreateTransaction);\n\n // If Observable.latestRevsion[db.name] is undefined, set it to 0 so that comparing against it always works.\n // You might think that it will always be undefined before this call, but in case another Dexie instance in the same\n // window with the same database name has been created already, this static property will already be set correctly.\n Observable.latestRevision[db.name] = Observable.latestRevision[db.name] || 0;\n\n //\n // Override open to setup hooks for db changes and map the _syncNodes table to class\n //\n db.open = override(db.open, overrideOpen);\n\n db.close = override(db.close, function(origClose) {\n return function () {\n if (db.dynamicallyOpened()) return origClose.apply(this, arguments); // Don't observe dynamically opened databases.\n // Teardown our framework.\n if (wakeupObservers.timeoutHandle) {\n clearTimeout(wakeupObservers.timeoutHandle);\n delete wakeupObservers.timeoutHandle;\n }\n Observable.on('latestRevisionIncremented').unsubscribe(onLatestRevisionIncremented);\n Observable.on('suicideNurseCall').unsubscribe(onSuicide);\n Observable.on('intercomm').unsubscribe(onIntercomm);\n Observable.on('beforeunload').unsubscribe(onBeforeUnload);\n // Inform other db instances in same window that we are dying:\n if (mySyncNode.node && mySyncNode.node.id) {\n Observable.on.suicideNurseCall.fire(db.name, mySyncNode.node.id);\n // Inform other windows as well:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. cleanup() may trigger twice per other db instance. But that doesnt to anything.\n }\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n mySyncNode.node = null;\n }\n\n if (pollHandle) clearTimeout(pollHandle);\n pollHandle = null;\n if (heartbeatHandle) clearTimeout(heartbeatHandle);\n heartbeatHandle = null;\n return origClose.apply(this, arguments);\n };\n });\n\n // Override Dexie.delete() in order to delete Observable.latestRevision[db.name].\n db.delete = override(db.delete, function(origDelete) {\n return function() {\n return origDelete.apply(this, arguments).then(function(result) {\n // Reset Observable.latestRevision[db.name]\n Observable.latestRevision[db.name] = 0;\n return result;\n });\n };\n });\n\n // When db opens, make sure to start monitor any changes before other db operations will start.\n db.on(\"ready\", function startObserving() {\n if (db.dynamicallyOpened()) return db; // Don't observe dynamically opened databases.\n \n return db.table(\"_changes\").orderBy(\"rev\").last(function(lastChange) {\n // Since startObserving() is called before database open() method, this will be the first database operation enqueued to db.\n // Therefore we know that the retrieved value will be This query will\n var latestRevision = (lastChange ? lastChange.rev : 0);\n mySyncNode.node = new SyncNode({\n myRevision: latestRevision,\n type: \"local\",\n lastHeartBeat: Date.now(),\n deleteTimeStamp: null,\n isMaster: 0\n });\n if (Observable.latestRevision[db.name] < latestRevision) {\n // Side track . For correctness whenever setting Observable.latestRevision[db.name] we must make sure the event is fired if increased:\n // There are other db instances in same window that hasnt yet been informed about a new revision\n Observable.latestRevision[db.name] = latestRevision;\n Dexie.ignoreTransaction(function() {\n Observable.on.latestRevisionIncremented.fire(latestRevision);\n });\n }\n // Add new sync node or if this is a reopening of the database after a close() call, update it.\n return db._syncNodes.put(mySyncNode.node).then(Dexie.ignoreTransaction(() => {\n // By default, this node will become master unless we discover an existing, up-to-date master\n var mySyncNodeShouldBecomeMaster = 1;\n return db._syncNodes.orderBy('isMaster').reverse().modify(existingNode => {\n if (existingNode.isMaster) {\n if (existingNode.lastHeartBeat < Date.now() - NODE_TIMEOUT) {\n // Existing master record is out-of-date; demote it\n existingNode.isMaster = 0;\n } else {\n // An existing up-to-date master record exists, so it will remain master\n mySyncNodeShouldBecomeMaster = 0;\n }\n }\n\n // The local node reference may be unassigned at any point by a database close() operation\n if (!mySyncNode.node) return;\n\n // Assign the local node state\n // This is guaranteed to apply *after* any existing master records have been inspected, due to the orderBy clause\n if (existingNode.id === mySyncNode.node.id) {\n existingNode.isMaster = mySyncNode.node.isMaster = mySyncNodeShouldBecomeMaster;\n }\n });\n })).then(() => {\n Observable.on('latestRevisionIncremented', onLatestRevisionIncremented); // Wakeup when a new revision is available.\n Observable.on('beforeunload', onBeforeUnload);\n Observable.on('suicideNurseCall', onSuicide);\n Observable.on('intercomm', onIntercomm);\n // Start polling for changes and do cleanups:\n pollHandle = setTimeout(poll, LOCAL_POLL);\n // Start heartbeat\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }).then(function () {\n cleanup();\n });\n });\n }, true); // True means the on(ready) event will survive a db reopening (db.close() / db.open()).\n\n var handledRevision = 0;\n\n function onLatestRevisionIncremented(dbname, latestRevision) {\n if (dbname === db.name) {\n if (handledRevision >= latestRevision) return; // Make sure to only run once per revision. (Workaround for IE triggering storage event on same window)\n handledRevision = latestRevision;\n Dexie.vip(function() {\n readChanges(latestRevision).catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n });\n });\n }\n }\n\n function readChanges(latestRevision, recursion, wasPartial) {\n // Whenever changes are read, fire db.on(\"changes\") with the array of changes. Eventually, limit the array to 1000 entries or so (an entire database is\n // downloaded from server AFTER we are initiated. For example, if first sync call fails, then after a while we get reconnected. However, that scenario\n // should be handled in case database is totally empty we should fail if sync is not available)\n if (!recursion && readChanges.ongoingOperation) {\n // We are already reading changes. Prohibit a parallell execution of this which would lead to duplicate trigging of 'changes' event.\n // Instead, the callback in toArray() will always check Observable.latestRevision[db.name] to see if it has changed and if so, re-launch readChanges().\n // The caller should get the Promise instance from the ongoing operation so that the then() method will resolve when operation is finished.\n return readChanges.ongoingOperation;\n }\n\n var partial = false;\n var ourSyncNode = mySyncNode.node; // Because mySyncNode can suddenly be set to null on database close, and worse, can be set to a new value if database is reopened.\n if (!ourSyncNode) {\n return Promise.reject(new Dexie.DatabaseClosedError());\n }\n var LIMIT = 1000;\n var promise = db._changes.where(\"rev\").above(ourSyncNode.myRevision).limit(LIMIT).toArray(function (changes) {\n if (changes.length > 0) {\n var lastChange = changes[changes.length - 1];\n partial = (changes.length === LIMIT);\n db.on('changes').fire(changes, partial);\n ourSyncNode.myRevision = lastChange.rev;\n } else if (wasPartial) {\n // No more changes, BUT since we have triggered on('changes') with partial = true,\n // we HAVE TO trigger changes again with empty list and partial = false\n db.on('changes').fire([], false);\n }\n\n let ourNodeStillExists = false;\n return db._syncNodes.where(':id').equals(ourSyncNode.id).modify(syncNode => {\n ourNodeStillExists = true;\n syncNode.lastHeartBeat = Date.now(); // Update heart beat (not nescessary, but why not!)\n syncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n syncNode.myRevision = Math.max(syncNode.myRevision, ourSyncNode.myRevision);\n }).then(()=>ourNodeStillExists);\n }).then(ourNodeStillExists =>{\n if (!ourNodeStillExists) {\n // My node has been deleted. We must have been lazy and got removed by another node.\n if (browserIsShuttingDown) {\n throw new Error(\"Browser is shutting down\");\n } else {\n db.close();\n console.error(\"Out of sync\"); // TODO: What to do? Reload the page?\n if (global.location) global.location.reload(true);\n throw new Error(\"Out of sync\"); // Will make current promise reject\n }\n }\n\n // Check if more changes have come since we started reading changes in the first place. If so, relaunch readChanges and let the ongoing promise not\n // resolve until all changes have been read.\n if (partial || Observable.latestRevision[db.name] > ourSyncNode.myRevision) {\n // Either there were more than 1000 changes or additional changes where added while we were reading these changes,\n // In either case, call readChanges() again until we're done.\n return readChanges(Observable.latestRevision[db.name], (recursion || 0) + 1, partial);\n }\n\n }).finally(function() {\n delete readChanges.ongoingOperation;\n });\n\n if (!recursion) {\n readChanges.ongoingOperation = promise;\n }\n return promise;\n }\n\n /**\n * The reason we need heartbeat in parallell with poll() is due to the risk of long-running\n * transactions while syncing changes from server to client in Dexie.Syncable. That transaction will\n * include _changes (which will block readChanges()) but not _syncNodes. So this heartbeat will go on\n * during that changes are being applied and update our lastHeartBeat property while poll() is waiting.\n * When cleanup() (who also is blocked by the sync) wakes up, it won't kill the master node because this\n * heartbeat job will have updated the master node's heartbeat during the long-running sync transaction.\n * \n * If we did not have this heartbeat, and a server send lots of changes that took more than NODE_TIMEOUT\n * (20 seconds), another node waking up after the sync would kill the master node and take over because\n * it would believe it was dead.\n */\n function heartbeat() {\n heartbeatHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n db.transaction('rw!', db._syncNodes, ()=>{\n db._syncNodes.where({id: currentInstance}).first(ourSyncNode => {\n if (!ourSyncNode) {\n // We do not exist anymore. Call db.close() to teardown polls etc.\n if (db.isOpen()) db.close();\n return;\n }\n ourSyncNode.lastHeartBeat = Date.now();\n ourSyncNode.deleteTimeStamp = null; // Reset \"deleteTimeStamp\" flag if it was there.\n return db._syncNodes.put(ourSyncNode);\n });\n }).catch('DatabaseClosedError', () => {\n // Ignore silently\n }).finally(() => {\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n heartbeatHandle = setTimeout(heartbeat, HEARTBEAT_INTERVAL);\n }\n });\n }\n\n function poll() {\n pollHandle = null;\n var currentInstance = mySyncNode.node && mySyncNode.node.id;\n if (!currentInstance) return;\n Dexie.vip(function() { // VIP ourselves. Otherwise we might not be able to consume intercomm messages from master node before database has finished opening. This would make DB stall forever. Cannot rely on storage-event since it may not always work in some browsers of different processes.\n readChanges(Observable.latestRevision[db.name]).then(cleanup).then(consumeIntercommMessages)\n .catch('DatabaseClosedError', ()=>{\n // Handle database closed error gracefully while reading changes.\n // Don't trigger 'unhandledrejection'.\n // Even though we intercept the close() method, it might be called when in the middle of\n // reading changes and then that flow will cancel with DatabaseClosedError.\n })\n .finally(function() {\n // Poll again in given interval:\n if (mySyncNode.node && mySyncNode.node.id === currentInstance && db.isOpen()) {\n pollHandle = setTimeout(poll, LOCAL_POLL);\n }\n });\n });\n }\n\n \n function cleanup() {\n var ourSyncNode = mySyncNode.node;\n if (!ourSyncNode) return Promise.reject(new Dexie.DatabaseClosedError());\n return db.transaction('rw', '_syncNodes', '_changes', '_intercomm', function() {\n // Cleanup dead local nodes that has no heartbeat for over a minute\n // Dont do the following:\n //nodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).and(function (node) { return node.type == \"local\"; }).delete();\n // Because client may have been in hybernate mode and recently woken up. That would lead to deletion of all nodes.\n // Instead, we should mark any old nodes for deletion in a minute or so. If they still dont wakeup after that minute we could consider them dead.\n var weBecameMaster = false;\n db._syncNodes.where(\"lastHeartBeat\").below(Date.now() - NODE_TIMEOUT).filter(node => node.type === 'local').modify(function(node) {\n if (node.deleteTimeStamp && node.deleteTimeStamp < Date.now()) {\n // Delete the node.\n delete this.value;\n // Cleanup localStorage \"deadnode:\" entry for this node (localStorage API was used to wakeup other windows (onstorage event) - an event type missing in indexedDB.)\n if (localStorage) {\n localStorage.removeItem('Dexie.Observable/deadnode:' + node.id + '/' + db.name);\n }\n // Check if we are deleting a master node\n if (node.isMaster) {\n // The node we are deleting is master. We must take over that role.\n // OK to call nodes.update(). No need to call Dexie.vip() because nodes is opened in existing transaction!\n db._syncNodes.update(ourSyncNode, { isMaster: 1 });\n weBecameMaster = true;\n }\n // Cleanup intercomm messages destinated to the node being deleted.\n // Those that waits for reply should be redirected to us.\n db._intercomm.where({destinationNode: node.id}).modify(function(msg) {\n if (msg.wantReply)\n msg.destinationNode = ourSyncNode.id;\n else\n // Delete the message from DB and if someone is waiting for reply, let ourselved answer the request.\n delete this.value;\n });\n } else if (!node.deleteTimeStamp) {\n // Mark the node for deletion\n node.deleteTimeStamp = Date.now() + HIBERNATE_GRACE_PERIOD;\n }\n }).then(function() {\n // Cleanup old revisions that no node is interested of.\n Observable.deleteOldChanges(db);\n return db.on(\"cleanup\").fire(weBecameMaster);\n });\n });\n }\n\n function onBeforeUnload() {\n // Mark our own sync node for deletion.\n if (!mySyncNode.node) return;\n browserIsShuttingDown = true;\n mySyncNode.node.deleteTimeStamp = 1; // One millisecond after 1970. Makes it occur in the past but still keeps it truthy.\n mySyncNode.node.lastHeartBeat = 0;\n db._syncNodes.put(mySyncNode.node); // This async operation may be cancelled since the browser is closing down now.\n Observable.wereTheOneDying = true; // If other nodes in same window wakes up by this call, make sure they dont start taking over mastership and stuff...\n // Inform other windows that we're gone, so that they may take over our role if needed. Setting localStorage item below will trigger Observable.onStorage, which will trigger onSuicie() below:\n if (localStorage) {\n localStorage.setItem('Dexie.Observable/deadnode:' + mySyncNode.node.id.toString() + '/' + db.name, \"dead\"); // In IE, this will also wakeup our own window. However, that is doublechecked in nursecall subscriber below.\n }\n }\n\n function onSuicide(dbname, nodeID) {\n if (dbname === db.name && !Observable.wereTheOneDying) {\n // Make sure it's dead indeed. Second bullet. Why? Because it has marked itself for deletion in the onbeforeunload event, which is fired just before window dies.\n // It's own call to put() may have been cancelled.\n // Note also that in IE, this event may be called twice, but that doesnt harm!\n Dexie.vip(function() {\n db._syncNodes.update(nodeID, { deleteTimeStamp: 1, lastHeartBeat: 0 }).then(cleanup);\n });\n }\n }\n\n}\n\n//\n// Static properties and methods\n// \n\nObservable.version = \"{version}\";\nObservable.latestRevision = {}; // Latest revision PER DATABASE. Example: Observable.latestRevision.FriendsDB = 37;\nObservable.on = Dexie.Events(null, \"latestRevisionIncremented\", \"suicideNurseCall\", \"intercomm\", \"beforeunload\"); // fire(dbname, value);\nObservable.createUUID = createUUID;\n\nObservable.deleteOldChanges = deleteOldChanges;\n\nObservable._onStorage = initOnStorage(Observable);\n\nObservable._onBeforeUnload = function() {\n Observable.on.beforeunload.fire();\n};\n\ntry {\n Observable.localStorageImpl = global.localStorage;\n} catch (ex){}\n\n//\n// Map window events to static events in Dexie.Observable:\n//\nif (global?.addEventListener) {\n global.addEventListener(\"storage\", Observable._onStorage);\n global.addEventListener(\"beforeunload\", Observable._onBeforeUnload);\n}\n\nif (Dexie.Observable) {\n if (Dexie.Observable.version !== \"{version}\") {\n throw new Error (`Mixed versions of dexie-observable`);\n }\n} else {\n // Register addon:\n Dexie.Observable = Observable;\n Dexie.addons.push(Observable);\n}\n\nexport default Dexie.Observable;\n"],"names":["Dexie","Promise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAAgB,GAAG,MAAK;aAER,eAAe,CAAC,EAAE,EAAE,EAAE;QACpC,IAAI,EAAE,KAAK,GAAG;YAAE,OAAO,EAAE,CAAC;QAC1B,OAAO;YACL,IAAI,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;YACpC,IAAI,GAAG,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,EAAE;gBACzC,IAAI,IAAI,GAAG,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC;gBAClC,OAAO,GAAG,CAAC,IAAI,CAAC;oBACd,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;iBAC7B,CAAC,CAAC;aACJ;YACD,OAAO,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SAClC,CAAC;IACJ,CAAC;aAEe,UAAU;;QAExB,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACnB,IAAI,IAAI,GAAG,sCAAsC,CAAC,OAAO,CAAC,OAAO,EAAE,UAAS,CAAC;YAC3E,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;YAC1C,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;YACvB,OAAO,CAAC,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;SAC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CAAC;IAEnC,UAAU,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;IAE/C,UAAU,CAAC,UAAU,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;IAElD,UAAU,CAAC,eAAe,GAAG;QACzB,UAAU,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,CAAC;IACtC,CAAC,CAAC;IAEF,IAAI;QACA,UAAU,CAAC,gBAAgB,GAAG,MAAM,CAAC,YAAY,CAAC;KACrD;IAAC,OAAO,EAAE,EAAC,GAAE;IAEd;IACA;IACA;IACA,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,EAAE;QAC1B,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;QAC1D,MAAM,CAAC,gBAAgB,CAAC,cAAc,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC;KACvE;IAED,IAAIA,yBAAK,CAAC,UAAU,EAAE;QAClB,IAAIA,yBAAK,CAAC,UAAU,CAAC,OAAO,KAAK,WAAW,EAAE;YAC1C,MAAM,IAAI,KAAK,CAAE,oCAAoC,CAAC,CAAC;SAC1D;KACJ;SAAM;;QAEHA,yBAAK,CAAC,UAAU,GAAG,UAAU,CAAC;QAC9BA,yBAAK,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;KACjC;AAED,2BAAeA,yBAAK,CAAC,UAAU;;;;;;;;"} \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.min.js b/addons/Dexie.Observable/dist/dexie-observable.min.js new file mode 100644 index 000000000..596c55d36 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js @@ -0,0 +1 @@ +(function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n(require("dexie")):"function"==typeof define&&define.amd?define(["dexie"],n):((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie=e.Dexie||{},e.Dexie.Observable=n(e.Dexie))})(this,function(e){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var j=n(e);function B(){}function C(o,i){return o===B?i:function(){var e,n,t=o.apply(this,arguments);return t&&"function"==typeof t.then?(e=this,n=arguments,t.then(function(){return i.apply(e,n)})):i.apply(this,arguments)}}var l=1,m=2,u=3;function k(t){return function(e){var n,a,s,d,f,i,r;e.hook._observing||(e.hook._observing=!0,n=e.name,e.hook("creating").subscribe((a=t,s=e,function(n,e,t){var o=void 0,i=(void 0===n&&s.schema.primKey.uuid&&(n=o=j.default.Observable.createUUID(),s.schema.primKey.keyPath&&j.default.setByKeyPath(e,s.schema.primKey.keyPath,n)),{source:t.source||null,table:s.name,key:void 0===n?null:n,type:l,obj:e}),r=a._changes.add(i).then(function(e){return t._lastWrittenRevision=Math.max(t._lastWrittenRevision,e),e});return this.onsuccess=function(e){n!=e&&r._then(function(){i.key=e,a._changes.put(i)})},this.onerror=function(){r._then(function(e){a._changes.delete(e)})},o})),e.hook("updating").subscribe((d=t,f=n,function(e,n,t,o){var i,r,a={},s=!1,l=j.default.deepClone(t);for(i in e){var u,c=e[i];void 0===c?(j.default.delByKeyPath(l,i),s=!(a[i]=null)):c!==(u=j.default.getByKeyPath(t,i))&&JSON.stringify(c)!==JSON.stringify(u)&&(j.default.setByKeyPath(l,i,c),a[i]=c,s=!0)}s&&(n={source:o.source||null,table:f,key:n,type:m,mods:a,oldObj:t,obj:l},r=d._changes.add(n),this.onsuccess=function(){r._then(function(e){o._lastWrittenRevision=Math.max(o._lastWrittenRevision,e)})},this.onerror=function(){r._then(function(e){d._changes.delete(e)})})})),e.hook("deleting").subscribe((i=t,r=n,function(e,n,t){var o=i._changes.add({source:t.source||null,table:r,key:e,type:u,oldObj:n}).then(function(e){return t._lastWrittenRevision=Math.max(t._lastWrittenRevision,e),e}).catch(function(e){console.log(n),console.log(e.stack)});this.onerror=function(){o._then(function(e){i._changes.delete(e)})}})))}}var c=j.default.Promise;function E(r,a,e,s,l){var u={};function n(){return s.node?j.default.ignoreTransaction(function(){return r.transaction("rw","_intercomm",function(){return r._intercomm.where({destinationNode:s.node.id}).toArray(function(e){return e.forEach(function(e){var n=e;"response"===n.type?(e=u[n.requestId.toString()])&&(n.isFailure?e.reject(n.message.error):e.resolve(n.message.result),delete u[n.requestId.toString()]):(n.resolve=function(e){r.observable.sendMessage("response",{result:e},n.sender,{requestId:n.id})},n.reject=function(e){r.observable.sendMessage("response",{error:e.toString()},n.sender,{isFailure:!0,requestId:n.id})},r.on.message.fire(n))}),r._intercomm.where("id").anyOf(e.map(function(e){return e.id})).delete()})})}):c.reject(new j.default.DatabaseClosedError)}return r.observable.sendMessage=function(e,n,t,o){var i;return o=o||{},s.node?(i={message:n,destinationNode:t,sender:s.node.id,type:e},j.default.extend(i,o),j.default.ignoreTransaction(function(){var e=["_intercomm"],e=(o.wantReply&&e.push("_syncNodes"),r.transaction("rw",e,function(){return o.wantReply?r._syncNodes.where("id").equals(t).count(function(e){return e?r._intercomm.add(i):r._syncNodes.where("isMaster").above(0).first(function(e){return i.destinationNode=e.id,r._intercomm.add(i)})}):r._intercomm.add(i)}).then(function(t){var e=null;return o.wantReply&&(e=new c(function(e,n){u[t.toString()]={resolve:e,reject:n}})),l&&l.setItem("Dexie.Observable/intercomm/"+r.name,t.toString()),a.on.intercomm.fire(r.name),e}));if(o.wantReply)return e;e.catch(function(){})})):o.wantReply?c.reject(new j.default.DatabaseClosedError):c.resolve()},r.observable.broadcastMessage=function(n,t,o){var i;s.node&&(i=s.node.id,j.default.ignoreTransaction(function(){r._syncNodes.toArray(function(e){return c.all(e.filter(function(e){return"local"===e.type&&(o||e.id!==i)}).map(function(e){return r.observable.sendMessage(n,t,e.id)}))}).catch(function(){})}))},{onIntercomm:function(e){e===r.name&&n().catch("DatabaseClosedError",function(){})},consumeIntercommMessages:n}}function H(t){return function(e,n){e._changes="++rev",e._syncNodes="++id,myRevision,lastHeartBeat,&url,isMaster,type,status",e._intercomm="++id,destinationNode",e._uncommittedChanges="++id,node",t.call(this,e,n),Object.keys(n).forEach(function(e){e=n[e];0===e.primKey.name.indexOf("$$")&&(e.primKey.uuid=!0,e.primKey.name=e.primKey.name.substr(2),e.primKey.keyPath=e.primKey.keyPath.substr(2))}),Object.keys(n).forEach(function(e){0!==e.indexOf("_")&&0!==e.indexOf("$")&&(n[e].observable=!0)})}}var r,K=self,P=j.default.defineClass({rev:Number,source:String,table:String,key:Object,type:Number,obj:Object,mods:Object,oldObj:Object}),W=j.default.override,U=j.default.Promise,q=!1;function V(a){if(!/^(3|4)\./.test(j.default.version))throw new Error("Missing dexie version 3.x or 4.x");if(a.observable){if("4.0.1-beta.13"!==a.observable.version)throw new Error("Mixed versions of dexie-observable")}else var n,t,o,s,l,i,r,u,c=2e4,d=2e4,f=c-5e3,m=V.localStorageImpl,v=j.default.defineClass({myRevision:Number,type:String,lastHeartBeat:Number,deleteTimeStamp:Number,url:String,isMaster:Number,syncProtocol:String,syncContext:null,syncOptions:Object,connected:!1,status:Number,appliedRemoteRevision:null,remoteBaseRevisions:[{local:Number,remote:null}],dbUploadState:{tablesToUpload:[String],currentTable:String,currentKey:null,localBaseRevision:Number}}),y=(a.observable={version:"4.0.1-beta.13"},a.observable.SyncNode=v,function(e){t.latestRevision[n.name]r.myRevision)return N(V.latestRevision[a.name],(n||0)+1,i)}).finally(function(){delete N.ongoingOperation}),n||(N.ongoingOperation=t),t):U.reject(new j.default.DatabaseClosedError))}function T(){R=null;var e=p.node&&p.node.id;e&&a.transaction("rw!",a._syncNodes,function(){a._syncNodes.where({id:e}).first(function(e){if(e)return e.lastHeartBeat=Date.now(),e.deleteTimeStamp=null,a._syncNodes.put(e);a.isOpen()&&a.close()})}).catch("DatabaseClosedError",function(){}).finally(function(){p.node&&p.node.id===e&&a.isOpen()&&(R=setTimeout(T,f))})}function S(){x=null;var e=p.node&&p.node.id;e&&j.default.vip(function(){N(V.latestRevision[a.name]).then(D).then(_).catch("DatabaseClosedError",function(){}).finally(function(){p.node&&p.node.id===e&&a.isOpen()&&(x=setTimeout(S,500))})})}function D(){var t=p.node;return t?a.transaction("rw","_syncNodes","_changes","_intercomm",function(){var n=!1;a._syncNodes.where("lastHeartBeat").below(Date.now()-c).filter(function(e){return"local"===e.type}).modify(function(e){e.deleteTimeStamp&&e.deleteTimeStampr.latestRevision[t]&&(r.latestRevision[t]=o,j.default.ignoreTransaction(function(){r.on("latestRevisionIncremented").fire(t,o)}))):0===n.indexOf("deadnode:")?(i=parseInt(n.split(":")[1],10),e.newValue&&r.on.suicideNurseCall.fire(t,i)):"intercomm"===n&&e.newValue&&r.on.intercomm.fire(t))}),V._onBeforeUnload=function(){V.on.beforeunload.fire()};try{V.localStorageImpl=K.localStorage}catch(e){}if(null!=K&&K.addEventListener&&(K.addEventListener("storage",V._onStorage),K.addEventListener("beforeunload",V._onBeforeUnload)),j.default.Observable){if("4.0.1-beta.13"!==j.default.Observable.version)throw new Error("Mixed versions of dexie-observable")}else j.default.Observable=V,j.default.addons.push(V);return j.default.Observable}); \ No newline at end of file diff --git a/addons/Dexie.Observable/dist/dexie-observable.min.js.map b/addons/Dexie.Observable/dist/dexie-observable.min.js.map new file mode 100644 index 000000000..174d3f893 --- /dev/null +++ b/addons/Dexie.Observable/dist/dexie-observable.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["dexie-observable.js"],"names":["global","factory","exports","module","require","define","amd","globalThis","self","Dexie","Observable","this","_interopDefaultLegacy","e","default","Dexie__default","nop","promisableChain","f1","f2","thiz","args","res","apply","arguments","then","CREATE","UPDATE","DELETE","initCrudMonitor","db","table","tableName","hook","_observing","name","subscribe","primKey","obj","trans","rv","undefined","change","schema","uuid","createUUID","keyPath","setByKeyPath","source","key","type","promise","_changes","add","rev","_lastWrittenRevision","Math","max","onsuccess","resultKey","_then","put","onerror","delete","mods","oldObj","propPath","modsWithoutUndefined","anythingChanged","newObj","deepClone","currentValue","mod","delByKeyPath","getByKeyPath","JSON","stringify","catch","console","log","stack","Promise$2","Promise","initIntercomm","SyncNode","mySyncNode","localStorage","requestsWaitingForReply","consumeIntercommMessages","node","ignoreTransaction","transaction","_intercomm","where","destinationNode","id","toArray","messages","forEach","msg","consumeMessage","request","requestId","toString","isFailure","reject","message","error","resolve","result","observable","sendMessage","sender","on","fire","anyOf","map","DatabaseClosedError","options","extend","tables","wantReply","push","_syncNodes","equals","count","receiverAlive","above","first","masterNode","messageId","setItem","intercomm","broadcastMessage","bIncludeSelf","mySyncNodeId","nodes","all","filter","onIntercomm","dbname","overrideParseStoresSpec","origFunc","stores","dbSchema","call","Object","keys","indexOf","substr","DatabaseChange","defineClass","Number","String","override","Promise$1","browserIsShuttingDown","test","version","Error","wakeupObservers","crudMonitor","NODE_TIMEOUT","HIBERNATE_GRACE_PERIOD","HEARTBEAT_INTERVAL","localStorageImpl","myRevision","lastHeartBeat","deleteTimeStamp","url","isMaster","syncProtocol","syncContext","syncOptions","connected","status","appliedRemoteRevision","remoteBaseRevisions","local","remote","dbUploadState","tablesToUpload","currentTable","currentKey","localBaseRevision","lastWrittenRevision","latestRevision","overrideCreateTransaction","mode","storenames","dbschema","parent","addChanges","dynamicallyOpened","some","storeName","slice","rootTransaction","findRootTransaction","timeoutHandle","clearTimeout","setTimeout","overrideOpen","origOpen","_allTables","mapToClass","pollHandle","defineProperty","get","heartbeatHandle","handledRevision","fake","_uncommittedChanges","Date","now","Version","prototype","_parseStoresSpec","addEventType","changes","cleanup","_createTransaction","open","close","origClose","unsubscribe","onLatestRevisionIncremented","onSuicide","onBeforeUnload","suicideNurseCall","origDelete","orderBy","last","lastChange","latestRevisionIncremented","mySyncNodeShouldBecomeMaster","reverse","modify","existingNode","poll","heartbeat","vip","readChanges","recursion","wasPartial","partial","ourSyncNode","ongoingOperation","limit","length","ourNodeStillExists","syncNode","location","reload","finally","currentInstance","isOpen","weBecameMaster","below","value","removeItem","update","deleteOldChanges","wereTheOneDying","nodeID","Events","d","replace","c","r","random","floor","oldestNode","primaryKeys","keysToDelete","bulkDelete","_onStorage","event","prop","parts","split","parseInt","newValue","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EAAO+R,iBAAiB,UAAWrR,EAAW0Q,UAAU,EACxDpR,EAAO+R,iBAAiB,eAAgBrR,EAAWkR,eAAe,GAElE7Q,EAAwB,QAAEL,YAC1B,GAAqD,kBAAjDK,EAAwB,QAAEL,WAAWoJ,QACrC,MAAM,IAAIC,MAAM,oCAAoC,CACxD,MAIAhJ,EAAwB,QAAEL,WAAaA,EACvCK,EAAwB,QAAEiR,OAAOtK,KAAKhH,CAAU,EAIpD,OAFuBK,EAAwB,QAAEL,UAIpD,CAAC"} \ 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 407507cfb..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/dexie/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..1797059c3 --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.d.ts @@ -0,0 +1,111 @@ +// Type definitions for dexie-syncable v4.0.1-beta.13 +// Project: https://github.com/dfahlander/Dexie.js/tree/master/addons/Dexie.Syncable +// Definitions by: David Fahlander + +import Dexie, { DexieEventSet } from 'dexie'; +import 'dexie-observable'; +import { ISyncProtocol, SyncStatus } from '../api'; +import {IDatabaseChange} from 'dexie-observable/api'; + + +export interface SyncableEventSet extends DexieEventSet { + (eventName: 'statusChanged', subscriber: (status: number, url: string) => void): void; +} + +// +// Extend Dexie interface +// +declare module 'dexie' { + interface Dexie { + syncable: { + version: string; + /** + * 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): Dexie.Promise; + + /** + * 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): Dexie.Promise; + + /** + * 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: 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; + } + + interface DexieConstructor { + Syncable: { + (db: Dexie) : void; + + version: string; + + /** + * See documentation at: + * https://dexie.org/docs/Syncable/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}; + } + } +} + +// +// Extend dexie-observable interfaces +// +declare module "dexie-observable" { + // Extend SyncNode interface from Dexie.Observable to + // allow storing remote nodes in table _syncNodes. + 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 + } + } +} + +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..b835db6ea --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.es.js @@ -0,0 +1,1214 @@ +/* ========================================================================== + * 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} + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; +import 'dexie-observable'; + +var Promise$3 = 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$3.reject(new Dexie.DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$3.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$3(function (resolve, reject) { + db.on("ready", function () { + // First, check if this is the very first time we connect to given URL. + // Need to know, because if it is, we should stall the promise returned to + // db.on('ready') to not be fulfilled until the initial sync has succeeded. + return db._syncNodes.get({ url: url }, function (node) { + // Ok, now we know whether we should await the connect promise or not. + // No matter, we should now connect (will maybe create the SyncNode instance + // representing the given URL) + var connectPromise = db.syncable.connect(protocolName, url, options); + connectPromise.then(resolve, reject); // Resolve the returned promise when connected. + // Ok, so let's see if we should suspend DB queries until connected or not: + if (node && node.appliedRemoteRevision) { + // The very first initial sync has been done so we need not wait + // for the connect promise to complete. It can continue in background. + // Returning here will resume db.on('ready') and resume all queries that + // the application has put to the database. + return; + } + // This was the very first time we connect to the remote server, + // we must make sure that the initial sync request succeeeds before resuming + // database queries that the application code puts onto the database. + // If OFFLINE or other error, don't allow the application to proceed. + // We are assuming that an initial sync is essential for the application to + // function correctly. + return connectPromise; + }); + }); + // Force open() to happen. Otherwise connect() may stall forever. + db.open().catch(function (ex) { + // If open fails, db.on('ready') may not have been called and we must + // reject promise with InvalidStateError + reject(new Dexie.InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open", ex)); + }); + }); + return promise; + } + }; +} + +function initPersistedContext(node) { + // + // PersistedContext : IPersistedContext + // + return /** @class */ (function () { + function PersistedContext(nodeID, otherProps) { + this.nodeID = nodeID; + if (otherProps) + Dexie.extend(this, otherProps); + } + PersistedContext.prototype.save = function () { + // Store this instance in the syncContext property of the node it belongs to. + return Dexie.vip(function () { + return node.save(); + }); + }; + return PersistedContext; + }()); +} + +function initGetOrCreateSyncNode(db, protocolName, url) { + return function getOrCreateSyncNode(options) { + return db.transaction('rw', db._syncNodes, db._changes, function () { + if (!url) + throw new Error("Url cannot be empty"); + // Returning a promise from transaction scope will make the transaction promise resolve with the value of that promise. + return db._syncNodes.where("url").equalsIgnoreCase(url).first(function (node) { + // If we found a node it will be instanceof SyncNode as Dexie.Observable + // maps to class + if (node) { + var PersistedContext = initPersistedContext(node); + // Node already there. Make syncContext become an instance of PersistedContext: + node.syncContext = new PersistedContext(node.id, node.syncContext); + node.syncProtocol = protocolName; // In case it was changed (would be very strange but...) could happen... + node.syncOptions = options; // Options could have been changed + db._syncNodes.put(node); + } + else { + // Create new node and sync everything + node = new db.observable.SyncNode(); + node.myRevision = -1; + node.appliedRemoteRevision = null; + node.remoteBaseRevisions = []; + node.type = "remote"; + node.syncProtocol = protocolName; + node.url = url; + node.syncOptions = options; + node.lastHeartBeat = Date.now(); + node.dbUploadState = null; + var PersistedContext_1 = initPersistedContext(node); + Dexie.Promise.resolve(function () { + // If options.initialUpload is explicitely false, set myRevision to currentRevision. + if (options.initialUpload === false) + return db._changes.toCollection().lastKey(function (currentRevision) { + node.myRevision = currentRevision; + }); + }()).then(function () { + db._syncNodes.add(node).then(function (nodeID) { + node.syncContext = new PersistedContext_1(nodeID); // Update syncContext in db with correct nodeId. + db._syncNodes.put(node); + }); + }); + } + return node; // returning node will make the db.transaction()-promise resolve with this value. + }); + }); + }; +} + +function initEnqueue(db) { + return function enqueue(context, fn, instanceID) { + function _enqueue() { + if (!context.ongoingOperation) { + context.ongoingOperation = Dexie.ignoreTransaction(function () { + return Dexie.vip(function () { + return fn(); + }); + }).finally(function () { + delete context.ongoingOperation; + }); + } + else { + context.ongoingOperation = context.ongoingOperation.then(function () { + return enqueue(context, fn, instanceID); + }); + } + return context.ongoingOperation; + } + if (!instanceID) { + // Caller wants to enqueue it until database becomes open. + if (db.isOpen()) { + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + } + else if (db._localSyncNode && instanceID === db._localSyncNode.id) { + // DB is already open but queue doesn't want it to be queued if database has been closed (request bound to current instance of DB) + return _enqueue(); + } + else { + return Dexie.Promise.reject(new Dexie.DatabaseClosedError()); + } + }; +} + +function initSaveToUncommittedChanges(db, node) { + return function saveToUncommittedChanges(changes, remoteRevision) { + return db.transaction('rw!', db._uncommittedChanges, function () { + return db._uncommittedChanges.bulkAdd(changes.map(function (change) { + var changeWithNodeId = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) + changeWithNodeId.obj = change.obj; + if (change.mods) + changeWithNodeId.mods = change.mods; + return changeWithNodeId; + })); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + return node.save(); + }); + }; +} + +// Change Types +var CREATE = 1; +var UPDATE = 2; +var DELETE = 3; + +function bulkUpdate(table, changes) { + var keys = changes.map(function (c) { return c.key; }); + var map = {}; + // Retrieve current object of each change to update and map each + // found object's primary key to the existing object: + return table.where(':id').anyOf(keys).raw().each(function (obj, cursor) { + map[cursor.primaryKey + ''] = obj; + }).then(function () { + // Filter away changes whose key wasn't found in the local database + // (we can't update them if we do not know the existing values) + var updatesThatApply = changes.filter(function (c) { return map.hasOwnProperty(c.key + ''); }); + // Apply modifications onto each existing object (in memory) + // and generate array of resulting objects to put using bulkPut(): + var objsToPut = updatesThatApply.map(function (c) { + var curr = map[c.key + '']; + Object.keys(c.mods).forEach(function (keyPath) { + Dexie.setByKeyPath(curr, keyPath, c.mods[keyPath]); + }); + return curr; + }); + return table.bulkPut(objsToPut); + }); +} + +function initApplyChanges(db) { + return function applyChanges(changes) { + var collectedChanges = {}; + changes.forEach(function (change) { + var _a; + if (!collectedChanges.hasOwnProperty(change.table)) { + collectedChanges[change.table] = (_a = {}, _a[CREATE] = [], _a[DELETE] = [], _a[UPDATE] = [], _a); + } + collectedChanges[change.table][change.type].push(change); + }); + 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); + 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()) { // Database was closed. + 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(); + } + } + // 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 ".concat(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} + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ +var override = Dexie.override, Promise$1 = Dexie.Promise, Observable = Dexie.Observable; +/** Dexie addon for remote database sync. + * + * @param {Dexie} db + */ +function Syncable(db) { + if (!/^(3|4)\./.test(Dexie.version)) + throw new Error("Missing dexie version 3.x or 4.x"); + if (!db.observable || (db.observable.version !== "{version}" && !/^(3|4)\./.test(db.observable.version))) + throw new Error("Missing dexie-observable version 3.x or 4.x"); + if (db.syncable) { + if (db.syncable.version !== "{version}") + throw new Error("Mixed versions of dexie-syncable: \"{version}\" vs \"".concat(db.syncable.version, "\"")); + return; // Addon already active. + } + 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$1.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 ".concat(node.url, ". ").concat(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 = { + version: "{version}" + }; + 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$1.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$1.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise$1.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$1.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.version = "{version}"; +Syncable.Statuses = Statuses; +Syncable.StatusTexts = StatusTexts; +Syncable.registeredProtocols = {}; // Map when key is the provider name. +Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a synchronization protocol that can synchronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + var partialsThreshold = protocolInstance.partialsThreshold; + if (typeof partialsThreshold === 'number') { + // Don't allow NaN or negative threshold + if (isNaN(partialsThreshold) || partialsThreshold < 0) { + throw new Error('The given number for the threshold is not supported'); + } + // If the threshold is 0 we will not send any client changes but will get server changes + } + else { + // Use Infinity as the default so simple protocols don't have to care about partial synchronization + protocolInstance.partialsThreshold = Infinity; + } + Syncable.registeredProtocols[name] = protocolInstance; +}; +if (Dexie.Syncable) { + if (Dexie.Syncable.version !== "{version}") { + throw new Error("Mixed versions of dexie-syncable: \"{version}\" vs \"".concat(Dexie.Syncable.version, "\"")); + } +} +else { + // Register addon in Dexie: + Dexie.Syncable = Syncable; + Dexie.addons.push(Syncable); +} +var Dexie_Syncable = Dexie.Syncable; + +export { Dexie_Syncable as default }; diff --git a/addons/Dexie.Syncable/dist/dexie-syncable.js b/addons/Dexie.Syncable/dist/dexie-syncable.js new file mode 100644 index 000000000..79a78c84f --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.js @@ -0,0 +1,1223 @@ +/* ========================================================================== + * 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 4.0.1-beta.13, Wed Oct 18 2023 + * + * https://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 = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.Dexie = global.Dexie || {}, global.Dexie.Syncable = factory(global.Dexie))); +})(this, (function (Dexie) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var Dexie__default = /*#__PURE__*/_interopDefaultLegacy(Dexie); + + var Promise$3 = Dexie__default["default"].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$3.reject(new Dexie__default["default"].DatabaseClosedError()); + } + else if (db.hasFailed()) { + // Database has failed to open + return Promise$3.reject(new Dexie__default["default"].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$3(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__default["default"].InvalidStateError("Dexie.Syncable: Couldn't connect. Database failed to open", ex)); + }); + }); + return promise; + } + }; + } + + function initPersistedContext(node) { + // + // PersistedContext : IPersistedContext + // + return /** @class */ (function () { + function PersistedContext(nodeID, otherProps) { + this.nodeID = nodeID; + if (otherProps) + Dexie__default["default"].extend(this, otherProps); + } + PersistedContext.prototype.save = function () { + // Store this instance in the syncContext property of the node it belongs to. + return Dexie__default["default"].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__default["default"].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__default["default"].ignoreTransaction(function () { + return Dexie__default["default"].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__default["default"].Promise.reject(new Dexie__default["default"].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__default["default"].Promise.reject(new Dexie__default["default"].DatabaseClosedError()); + } + }; + } + + function initSaveToUncommittedChanges(db, node) { + return function saveToUncommittedChanges(changes, remoteRevision) { + return db.transaction('rw!', db._uncommittedChanges, function () { + return db._uncommittedChanges.bulkAdd(changes.map(function (change) { + var changeWithNodeId = { + node: node.id, + type: change.type, + table: change.table, + key: change.key + }; + if (change.obj) + changeWithNodeId.obj = change.obj; + if (change.mods) + changeWithNodeId.mods = change.mods; + return changeWithNodeId; + })); + }).then(function () { + node.appliedRemoteRevision = remoteRevision; + return node.save(); + }); + }; + } + + // Change Types + var CREATE = 1; + var UPDATE = 2; + var DELETE = 3; + + function bulkUpdate(table, changes) { + var keys = changes.map(function (c) { return c.key; }); + var map = {}; + // Retrieve current object of each change to update and map each + // found object's primary key to the existing object: + return table.where(':id').anyOf(keys).raw().each(function (obj, cursor) { + map[cursor.primaryKey + ''] = obj; + }).then(function () { + // Filter away changes whose key wasn't found in the local database + // (we can't update them if we do not know the existing values) + var updatesThatApply = changes.filter(function (c) { return map.hasOwnProperty(c.key + ''); }); + // Apply modifications onto each existing object (in memory) + // and generate array of resulting objects to put using bulkPut(): + var objsToPut = updatesThatApply.map(function (c) { + var curr = map[c.key + '']; + Object.keys(c.mods).forEach(function (keyPath) { + Dexie__default["default"].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) { + var _a; + if (!collectedChanges.hasOwnProperty(change.table)) { + collectedChanges[change.table] = (_a = {}, _a[CREATE] = [], _a[DELETE] = [], _a[UPDATE] = [], _a); + } + collectedChanges[change.table][change.type].push(change); + }); + 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__default["default"].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__default["default"].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__default["default"].setByKeyPath(clonedChange.obj, keyPath, nextChange.mods[keyPath]); + }); + return clonedChange; + } + + function combineUpdateAndUpdate(prevChange, nextChange) { + var clonedChange = Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].deepClone(node.dbUploadState), [], collection); + } + else { + var collection = db.table(dbUploadState.currentTable).orderBy(':id'); + return getTableObjectsAsChanges(Dexie__default["default"].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__default["default"].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__default["default"].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); + 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__default["default"].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__default["default"].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__default["default"].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()) { // Database was closed. + 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(); + } + } + // 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__default["default"].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 ".concat(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__default["default"].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__default["default"].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__default["default"].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 4.0.1-beta.13, Wed Oct 18 2023 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + var override = Dexie__default["default"].override, Promise$1 = Dexie__default["default"].Promise, Observable = Dexie__default["default"].Observable; + /** Dexie addon for remote database sync. + * + * @param {Dexie} db + */ + function Syncable(db) { + if (!/^(3|4)\./.test(Dexie__default["default"].version)) + throw new Error("Missing dexie version 3.x or 4.x"); + if (!db.observable || (db.observable.version !== "4.0.1-beta.13" && !/^(3|4)\./.test(db.observable.version))) + throw new Error("Missing dexie-observable version 3.x or 4.x"); + if (db.syncable) { + if (db.syncable.version !== "4.0.1-beta.13") + throw new Error("Mixed versions of dexie-syncable: \"4.0.1-beta.13\" vs \"".concat(db.syncable.version, "\"")); + return; // Addon already active. + } + var activePeers = []; + var connectFn = initConnectFn(db, activePeers); + var syncableConnect = initSyncableConnect(db, connectFn); + db.on('message', function (msg) { + // Message from other local node arrives... + Dexie__default["default"].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__default["default"].ignoreTransaction(function () { return Dexie__default["default"].vip(function () { + return db._syncNodes.where({ type: 'remote' }) + .filter(function (node) { return node.status !== Statuses.OFFLINE; }) + .toArray(function (connectedRemoteNodes) { return Promise$1.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 ".concat(node.url, ". ").concat(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 = { + version: "4.0.1-beta.13" + }; + db.syncable.getStatus = function (url, cb) { + if (db.isOpen()) { + return Dexie__default["default"].vip(function () { + return db._syncNodes.where('url').equals(url).first(function (node) { + return node ? node.status : Statuses.OFFLINE; + }); + }).then(cb); + } + else { + return Promise$1.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__default["default"].Events(db, { statusChanged: "asap" }); + db.syncable.disconnect = function (url) { + return Dexie__default["default"].ignoreTransaction(function () { + return Promise$1.resolve().then(function () { + if (db._localSyncNode && db._localSyncNode.isMaster) { + return Promise$1.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$1.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.version = "4.0.1-beta.13"; + Syncable.Statuses = Statuses; + Syncable.StatusTexts = StatusTexts; + Syncable.registeredProtocols = {}; // Map when key is the provider name. + Syncable.registerSyncProtocol = function (name, protocolInstance) { + /// + /// Register a synchronization protocol that can synchronize databases with remote servers. + /// + /// Provider name + /// Implementation of ISyncProtocol + var partialsThreshold = protocolInstance.partialsThreshold; + if (typeof partialsThreshold === 'number') { + // Don't allow NaN or negative threshold + if (isNaN(partialsThreshold) || partialsThreshold < 0) { + throw new Error('The given number for the threshold is not supported'); + } + // If the threshold is 0 we will not send any client changes but will get server changes + } + else { + // Use Infinity as the default so simple protocols don't have to care about partial synchronization + protocolInstance.partialsThreshold = Infinity; + } + Syncable.registeredProtocols[name] = protocolInstance; + }; + if (Dexie__default["default"].Syncable) { + if (Dexie__default["default"].Syncable.version !== "4.0.1-beta.13") { + throw new Error("Mixed versions of dexie-syncable: \"4.0.1-beta.13\" vs \"".concat(Dexie__default["default"].Syncable.version, "\"")); + } + } + else { + // Register addon in Dexie: + Dexie__default["default"].Syncable = Syncable; + Dexie__default["default"].addons.push(Syncable); + } + var Dexie_Syncable = Dexie__default["default"].Syncable; + + return Dexie_Syncable; + +})); 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..29608f73a --- /dev/null +++ b/addons/Dexie.Syncable/dist/dexie-syncable.min.js @@ -0,0 +1 @@ +(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="undefined"!=typeof globalThis?globalThis:e||self).Dexie=e.Dexie||{},e.Dexie.Syncable=n(e.Dexie))})(this,function(e){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var E=n(e),c=E.default.Promise;function b(e){return n.prototype.save=function(){return E.default.vip(function(){return e.save()})},n;function n(e,n){this.nodeID=e,n&&E.default.extend(this,n)}}function C(u){return function(e){var c={},n=(e.forEach(function(e){var n;c.hasOwnProperty(e.table)||(c[e.table]=((n={})[1]=[],n[3]=[],n[2]=[],n)),c[e.table][e.type].push(e)}),Object.keys(c)),e=n.map(function(e){return u.table(e)});return u.transaction("rw",e,function(){n.forEach(function(e){var n,t,o,r=u.table(e),a=!r.schema.primKey.keyPath,i=c[e][1],s=c[e][3],e=c[e][2];0=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 g(e,n){switch(e.type){case 1:switch(n.type){case 1:return n;case 2:return t=n,i=E.default.deepClone(e),Object.keys(t.mods).forEach(function(e){E.default.setByKeyPath(i.obj,e,t.mods[e])}),i;case 3:return n}break;case 2:switch(n.type){case 1:return n;case 2:return o=e,r=n,a=E.default.deepClone(o),Object.keys(r.mods).forEach(function(n){var t=!1;Object.keys(o.mods).filter(function(e){return 0===n.indexOf(e+".")}).forEach(function(e){E.default.setByKeyPath(a.mods[e],n.substr(e.length+1),r.mods[n]),t=!0}),t||(a.mods[n]=r.mods[n]),Object.keys(o.mods).filter(function(e){return 0===e.indexOf(n+".")}).forEach(function(e){delete a.mods[e]})}),a;case 3:return n}break;case 3:switch(n.type){case 1:return n;case 2:case 3:return e}}var o,r,a,t,i}function r(b,v,e){var p=e;return function(e,o){var u,l,f,i,s,c,d,y,h,r,n,t=function(e,n,t,o){var r={},a=0,i=!1,s=l.id,c=e;return u.transaction("r",u._changes,function(){return u._changes.where("rev").between(e,t,!1,!0).until(function(){if(a===n)return i=!0}).each(function(e){var n,t;c=e.rev,e.source!==s&&(n={type:e.type,table:e.table,key:e.key},1===e.type?n.obj=e.obj:2===e.type&&(n.mods=e.mods),e=e.table+":"+e.key,(t=r[e])?(t=g(t,n),r[e]=t):(r[e]=n,++a))})}).then(function(){var e=Object.keys(r).map(function(e){return r[e]});return f.hasMoreToGive=i,o(e,i,{myRevision:c})})},a=(i=u=b,c=p,d=t,y=f=v,h=o,function e(t,r,n){var a=!1;return n.until(function(){if(r.length===c)return a=!0}).each(function(e,n){r.push({type:1,table:t.currentTable,key:n.key,obj:n.value}),t.currentKey=n.key}).then(function(){var o;return a?(y.hasMoreToGive=!0,h(r,null,!0,{dbUploadState:t})):0===t.tablesToUpload.length?(o=m(s),d(t.localBaseRevision,c-r.length,o.maxClientRevision,function(e,n,t){return r=r.concat(e),t.dbUploadState=null,h(r,o.remoteBaseRevision,n,t)})):(t.currentTable=t.tablesToUpload.shift(),e(t,r,i.table(t.currentTable).orderBy(":id")))})});return 0<=(s=l=e).myRevision?(r=m(e),t(e.myRevision,p,r.maxClientRevision,function(e,n,t){return o(e,r.remoteBaseRevision,n,t)})):null===e.dbUploadState?0===(t=b.tables.filter(function(e){return e.schema.observable}).map(function(e){return e.name})).length?E.default.Promise.resolve(o([],null,!1,{})):(n={tablesToUpload:t,currentTable:t.shift(),currentKey:null},b._changes.orderBy("rev").last(function(e){n.localBaseRevision=e&&e.rev||0;e=b.table(n.currentTable).orderBy(":id");return a(n,[],e)})):(t=e.dbUploadState.currentKey?b.table(e.dbUploadState.currentTable).where(":id").above(e.dbUploadState.currentKey):b.table(n.currentTable).orderBy(":id"),a(E.default.deepClone(e.dbUploadState),[],t))}}var _={ERROR:-1,OFFLINE:0,CONNECTING:1,ONLINE:2,SYNCING:3,ERROR_WILL_RETRY:4},S=E.default.Promise;function v(v,p,m,g,N){a=v;var a,R=function e(n,t,o){function r(){return n.ongoingOperation?n.ongoingOperation=n.ongoingOperation.then(function(){return e(n,t,o)}):n.ongoingOperation=E.default.ignoreTransaction(function(){return E.default.vip(function(){return t()})}).finally(function(){delete n.ongoingOperation}),n.ongoingOperation}return o?a._localSyncNode&&o===a._localSyncNode.id?r():E.default.Promise.reject(new E.default.DatabaseClosedError):a.isOpen()?r():E.default.Promise.reject(new E.default.DatabaseClosedError)},O={hasMoreToGive:!0};function w(){return v._localSyncNode&&v._localSyncNode.id===m}return function(l,u){var f,s=r(v,O,p.partialsThreshold),d=u.url;function y(e){l.status!==e&&(l.status=e,l.save().then(function(){v.syncable.on.statusChanged.fire(e,d),v.observable.broadcastMessage("syncStatusChanged",{newStatus:e,url:d},!1)}).catch("DatabaseClosedError",function(){}))}return u.on("disconnect",function(e){isNaN(e)||y(e)}),y(_.CONNECTING),c();function c(){return R(c,function(){return t(l,e)},m)}function e(e,r,a,n){var t=new S(function(t,o){N.p=function(e){o(e)},E.default.asap(function(){try{p.sync(l.syncContext,d,g,r,l.appliedRemoteRevision,e,a,b,i,function(e){t(e)},n)}catch(e){n(e,1/0)}function n(e,n){o(e),w()&&(!isNaN(n)&&n<1/0?(setTimeout(function(){w()&&(y(_.SYNCING),c().catch("DatabaseClosedError",h))},n),y(_.ERROR_WILL_RETRY),f&&f.disconnect&&f.disconnect(),f=null):h(e))}})});return t.then(function(){}).finally(function(){N.p=null});function i(){return Object.keys(n).forEach(function(e){E.default.setByKeyPath(l,e,n[e])}),t.then(o),l.save()}}function h(e){u.disconnect(_.ERROR,e)}function t(a,i){return s(a,function e(n,t,o,r){return 0===n.length&&"myRevision"in r&&r.myRevision!==a.myRevision?(Object.keys(r).forEach(function(e){E.default.setByKeyPath(a,e,r[e])}),a.save().catch("DatabaseClosedError",function(){}),s(a,e)):i(n,t,o,r)})}function b(e,n,t){var o,r,a,i,s,c=function(e,n){return o.transaction("rw!",o._uncommittedChanges,function(){return o._uncommittedChanges.bulkAdd(e.map(function(e){var n={node:r.id,type:e.type,table:e.table,key:e.key};return e.obj&&(n.obj=e.obj),e.mods&&(n.mods=e.mods),n}))}).then(function(){return r.appliedRemoteRevision=n,r.save()})},u=(i=r=l,s=C(a=o=v),function(n,o){var e=a.tables.filter(function(e){return"_changes"===e.name||"_uncommittedChanges"===e.name||e.schema.observable});return a.transaction("rw!",e,function(){var e=E.default.currentTransaction,t=0;return a._changes.orderBy("rev").last(function(e){t=e&&e.rev||0}).then(function(){return e.source=i.id,a._uncommittedChanges.where("node").equals(i.id).toArray()}).then(function(e){return s(e)}).then(function(){return a._uncommittedChanges.where("node").equals(i.id).delete()}).then(function(){return s(n)}).then(function(){return a._changes.orderBy("rev").last()}).then(function(e){e=e&&e.rev||0;if(i.appliedRemoteRevision=o,i.remoteBaseRevisions.push({remote:o,local:e}),i.myRevision===t&&(i.myRevision=e),1=i.remoteBaseRevisions[n].local){i.remoteBaseRevisions.splice(0,n);break}i.save().catch(function(e){console.warn("Dexie.Syncable: Unable to save SyncNode after applying remote changes: "+(e.stack||e))})})})});return R(b,function(){return w()?(t?c:u)(e,n).catch(function(e){return h(e),S.reject(e)}):S.reject(new E.default.DatabaseClosedError)},m)}function o(e){var r,a,i;function s(){t(l,function(e,n,t,o){p.sync(l.syncContext,d,g,n,l.appliedRemoteRevision,e,t,b,function(){Object.keys(o).forEach(function(e){E.default.setByKeyPath(l,e,o[e])}),l.save().catch("DatabaseClosedError",function(){})},function(e){f&&(f=e,t?s():!isNaN(e.again)&&e.again<1/0?(y(_.ONLINE),setTimeout(function(){f&&(y(_.SYNCING),s())},e.again)):u.disconnect(_.OFFLINE))},function(e,n){!isNaN(n)&&n<1/0?f&&(setTimeout(function(){f&&(y(_.SYNCING),s())},n),y(_.ERROR_WILL_RETRY)):h(e)})}).catch(h)}function n(){f&&(y(_.SYNCING),i?a=!0:c())}function c(){f&&(i=!(a=!1),t(l,function(e,n,t,o){f&&(0 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 }; + } + } + + function getSchemaString(table) { + var primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes); + return primKeyAndIndexes.map(function (index) { return index.src; }).join(','); + } + function extractDbSchema(exportedDb) { + var schema = {}; + for (var _i = 0, _a = exportedDb.tables; _i < _a.length; _i++) { + var table = _a[_i]; + schema[table.name] = table.schema; + } + return schema; + } + function readBlobAsync(blob, type) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onabort = function (ev) { return reject(new Error("file read aborted")); }; + reader.onerror = function (ev) { return reject(ev.target.error); }; + reader.onload = function (ev) { return resolve(ev.target.result); }; + if (type === 'binary') + reader.readAsArrayBuffer(blob); + else + reader.readAsText(blob); + }); + } + function readBlobSync(blob, type) { + if (typeof FileReaderSync === 'undefined') { + throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.'); + } + var reader = new FileReaderSync(); // Requires worker environment + var data = type === 'binary' ? + reader.readAsArrayBuffer(blob) : + reader.readAsText(blob); + return data; + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var typeson = createCommonjsModule(function (module, exports) { + (function (global, factory) { + module.exports = factory() ; + }(commonjsGlobal, (function () { + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; + } + + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; + } + + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } + } + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); + } + + function _iterableToArrayLimit(arr, i) { + if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { + return; + } + + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); + } + + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + + /** + * We keep this function minimized so if using two instances of this + * library, where one is minimized and one is not, it will still work + * with `hasConstructorOf`. + * With ES6 classes, we may be able to simply use `class TypesonPromise + * extends Promise` and add a string tag for detection. + * @param {function} f + */ + // eslint-disable-next-line max-len + // eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new + var TypesonPromise = function TypesonPromise(f) { + _classCallCheck(this, TypesonPromise); + + this.p = new Promise(f); + }; // eslint-disable-next-line max-len + // class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi + + + TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill + + /* istanbul ignore else */ + + if (typeof Symbol !== 'undefined') { + // Ensure `isUserObject` will return `false` for `TypesonPromise` + TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise'; + } + /** + * + * @param {function} [onFulfilled] + * @param {function} [onRejected] + * @returns {TypesonPromise} + */ + + + TypesonPromise.prototype.then = function (onFulfilled, onRejected) { + var _this = this; + + return new TypesonPromise(function (typesonResolve, typesonReject) { + // eslint-disable-next-line promise/catch-or-return + _this.p.then(function (res) { + // eslint-disable-next-line promise/always-return + typesonResolve(onFulfilled ? onFulfilled(res) : res); + })["catch"](function (res) { + return onRejected ? onRejected(res) : Promise.reject(res); + }).then(typesonResolve, typesonReject); + }); + }; + /** + * + * @param {function} onRejected + * @returns {TypesonPromise} + */ + + + TypesonPromise.prototype["catch"] = function (onRejected) { + return this.then(null, onRejected); + }; + /** + * + * @param {Any} v + * @returns {TypesonPromise} + */ + + + TypesonPromise.resolve = function (v) { + return new TypesonPromise(function (typesonResolve) { + typesonResolve(v); + }); + }; + /** + * + * @param {Any} v + * @returns {TypesonPromise} + */ + + + TypesonPromise.reject = function (v) { + return new TypesonPromise(function (typesonResolve, typesonReject) { + typesonReject(v); + }); + }; + + ['all', 'race'].forEach(function (meth) { + /** + * + * @param {Promise[]} promArr + * @returns {TypesonPromise} + */ + TypesonPromise[meth] = function (promArr) { + return new TypesonPromise(function (typesonResolve, typesonReject) { + // eslint-disable-next-line promise/catch-or-return + Promise[meth](promArr.map(function (prom) { + return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom; + })).then(typesonResolve, typesonReject); + }); + }; + }); + + var _ref = {}, + toStr = _ref.toString, + hasOwn = {}.hasOwnProperty, + getProto = Object.getPrototypeOf, + fnToString = hasOwn.toString; + /** + * Second argument not in use internally, but provided for utility. + * @param {Any} v + * @param {boolean} catchCheck + * @returns {boolean} + */ + + function isThenable(v, catchCheck) { + return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v["catch"] === 'function'); + } + /** + * + * @param {Any} val + * @returns {string} + */ + + + function toStringTag(val) { + return toStr.call(val).slice(8, -1); + } + /** + * This function is dependent on both constructors + * being identical so any minimization is expected of both. + * @param {Any} a + * @param {function} b + * @returns {boolean} + */ + + + function hasConstructorOf(a, b) { + if (!a || _typeof(a) !== 'object') { + return false; + } + + var proto = getProto(a); + + if (!proto) { + return b === null; + } + + var Ctor = hasOwn.call(proto, 'constructor') && proto.constructor; + + if (typeof Ctor !== 'function') { + return b === null; + } + + if (b === Ctor) { + return true; + } + + if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) { + return true; + } + + if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) { + return true; + } + + return false; + } + /** + * + * @param {Any} val + * @returns {boolean} + */ + + + function isPlainObject(val) { + // Mirrors jQuery's + if (!val || toStringTag(val) !== 'Object') { + return false; + } + + var proto = getProto(val); + + if (!proto) { + // `Object.create(null)` + return true; + } + + return hasConstructorOf(val, Object); + } + /** + * + * @param {Any} val + * @returns {boolean} + */ + + + function isUserObject(val) { + if (!val || toStringTag(val) !== 'Object') { + return false; + } + + var proto = getProto(val); + + if (!proto) { + // `Object.create(null)` + return true; + } + + return hasConstructorOf(val, Object) || isUserObject(proto); + } + /** + * + * @param {Any} v + * @returns {boolean} + */ + + + function isObject(v) { + return v && _typeof(v) === 'object'; + } + /** + * + * @param {string} keyPathComponent + * @returns {string} + */ + + + function escapeKeyPathComponent(keyPathComponent) { + return keyPathComponent.replace(/~/g, '~0').replace(/\./g, '~1'); + } + /** + * + * @param {string} keyPathComponent + * @returns {string} + */ + + + function unescapeKeyPathComponent(keyPathComponent) { + return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~'); + } + /** + * @param {PlainObject|GenericArray} obj + * @param {string} keyPath + * @returns {Any} + */ + + + function getByKeyPath(obj, keyPath) { + if (keyPath === '') { + return obj; + } + + var period = keyPath.indexOf('.'); + + if (period > -1) { + var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; + return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1)); + } + + return obj[unescapeKeyPathComponent(keyPath)]; + } + /** + * + * @param {PlainObject} obj + * @param {string} keyPath + * @param {Any} value + * @returns {Any} + */ + + + function setAtKeyPath(obj, keyPath, value) { + if (keyPath === '') { + return value; + } + + var period = keyPath.indexOf('.'); + + if (period > -1) { + var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; + return setAtKeyPath(innerObj, keyPath.slice(period + 1), value); + } + + obj[unescapeKeyPathComponent(keyPath)] = value; + return obj; + } + /** + * + * @param {external:JSON} value + * @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"| + * "object"|"symbol"} + */ + + + function getJSONType(value) { + return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof(value); + } + + var keys = Object.keys, + isArray = Array.isArray, + hasOwn$1 = {}.hasOwnProperty, + internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric']; + /** + * Handle plain object revivers first so reference setting can use + * revived type (e.g., array instead of object); assumes revived + * has same structure or will otherwise break subsequent references. + * @param {PlainObjectType} a + * @param {PlainObjectType} b + * @returns {1|-1|boolean} + */ + + function nestedPathsFirst(a, b) { + if (a.keypath === '') { + return -1; + } + + var as = a.keypath.match(/\./g) || 0; + var bs = b.keypath.match(/\./g) || 0; + + if (as) { + as = as.length; + } + + if (bs) { + bs = bs.length; + } + + return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath; + } + /** + * An instance of this class can be used to call `stringify()` and `parse()`. + * Typeson resolves cyclic references by default. Can also be extended to + * support custom types using the register() method. + * + * @class + * @param {{cyclic: boolean}} [options] - if cyclic (default true), + * cyclic references will be handled gracefully. + */ + + + var Typeson = + /*#__PURE__*/ + function () { + function Typeson(options) { + _classCallCheck(this, Typeson); + + this.options = options; // Replacers signature: replace (value). Returns falsy if not + // replacing. Otherwise ['Date', value.getTime()] + + this.plainObjectReplacers = []; + this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}]. + // Sample: [{'Date': value => new Date(value)}, {plain: false}] + + this.revivers = {}; + /** Types registered via `register()`. */ + + this.types = {}; + } + /** + * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON + */ + + /** + * @callback JSONReplacer + * @param {""|string} key + * @param {JSON} value + * @returns {number|string|boolean|null|PlainObject|undefined} + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter + */ + + /** + * Serialize given object to Typeson. + * Initial arguments work identical to those of `JSON.stringify`. + * The `replacer` argument has nothing to do with our replacers. + * @param {Any} obj + * @param {JSONReplacer|string[]} replacer + * @param {number|string} space + * @param {object} opts + * @returns {string|Promise} Promise resolves to a string + */ + + + _createClass(Typeson, [{ + key: "stringify", + value: function stringify(obj, replacer, space, opts) { + opts = _objectSpread2({}, this.options, {}, opts, { + stringification: true + }); + var encapsulated = this.encapsulate(obj, null, opts); + + if (isArray(encapsulated)) { + return JSON.stringify(encapsulated[0], replacer, space); + } + + return encapsulated.then(function (res) { + return JSON.stringify(res, replacer, space); + }); + } + /** + * Also sync but throws on non-sync result. + * @param {Any} obj + * @param {JSONReplacer|string[]} replacer + * @param {number|string} space + * @param {object} opts + * @returns {string} + */ + + }, { + key: "stringifySync", + value: function stringifySync(obj, replacer, space, opts) { + return this.stringify(obj, replacer, space, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * + * @param {Any} obj + * @param {JSONReplacer|string[]} replacer + * @param {number|string} space + * @param {object} opts + * @returns {Promise} + */ + + }, { + key: "stringifyAsync", + value: function stringifyAsync(obj, replacer, space, opts) { + return this.stringify(obj, replacer, space, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * Parse Typeson back into an obejct. + * Initial arguments works identical to those of `JSON.parse()`. + * @param {string} text + * @param {function} reviver This JSON reviver has nothing to do with + * our revivers. + * @param {object} opts + * @returns {external:JSON} + */ + + }, { + key: "parse", + value: function parse(text, reviver, opts) { + opts = _objectSpread2({}, this.options, {}, opts, { + parse: true + }); + return this.revive(JSON.parse(text, reviver), opts); + } + /** + * Also sync but throws on non-sync result. + * @param {string} text + * @param {function} reviver This JSON reviver has nothing to do with + * our revivers. + * @param {object} opts + * @returns {external:JSON} + */ + + }, { + key: "parseSync", + value: function parseSync(text, reviver, opts) { + return this.parse(text, reviver, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * @param {string} text + * @param {function} reviver This JSON reviver has nothing to do with + * our revivers. + * @param {object} opts + * @returns {Promise} Resolves to `external:JSON` + */ + + }, { + key: "parseAsync", + value: function parseAsync(text, reviver, opts) { + return this.parse(text, reviver, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * + * @param {Any} obj + * @param {object} stateObj + * @param {object} [opts={}] + * @returns {string[]|false} + */ + + }, { + key: "specialTypeNames", + value: function specialTypeNames(obj, stateObj) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + opts.returnTypeNames = true; + return this.encapsulate(obj, stateObj, opts); + } + /** + * + * @param {Any} obj + * @param {PlainObject} stateObj + * @param {PlainObject} [opts={}] + * @returns {Promise|GenericArray|PlainObject|string|false} + */ + + }, { + key: "rootTypeName", + value: function rootTypeName(obj, stateObj) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + opts.iterateNone = true; + return this.encapsulate(obj, stateObj, opts); + } + /** + * Encapsulate a complex object into a plain Object by replacing + * registered types with plain objects representing the types data. + * + * This method is used internally by `Typeson.stringify()`. + * @param {Any} obj - Object to encapsulate. + * @param {PlainObject} stateObj + * @param {PlainObject} opts + * @returns {Promise|GenericArray|PlainObject|string|false} + */ + + }, { + key: "encapsulate", + value: function encapsulate(obj, stateObj, opts) { + opts = _objectSpread2({ + sync: true + }, this.options, {}, opts); + var _opts = opts, + sync = _opts.sync; + var that = this, + types = {}, + refObjs = [], + // For checking cyclic references + refKeys = [], + // For checking cyclic references + promisesDataRoot = []; // Clone the object deeply while at the same time replacing any + // special types or cyclic reference: + + var cyclic = 'cyclic' in opts ? opts.cyclic : true; + var _opts2 = opts, + encapsulateObserver = _opts2.encapsulateObserver; + + var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot); + /** + * + * @param {Any} ret + * @returns {GenericArray|PlainObject|string|false} + */ + + + function finish(ret) { + // Add `$types` to result only if we ever bumped into a + // special type (or special case where object has own `$types`) + var typeNames = Object.values(types); + + if (opts.iterateNone) { + if (typeNames.length) { + return typeNames[0]; + } + + return Typeson.getJSONType(ret); + } + + if (typeNames.length) { + if (opts.returnTypeNames) { + return _toConsumableArray(new Set(typeNames)); + } // Special if array (or a primitive) was serialized + // because JSON would ignore custom `$types` prop on it + + + if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its + // own `$types` property (to avoid ambiguity) + hasOwn$1.call(ret, '$types')) { + ret = { + $: ret, + $types: { + $: types + } + }; + } else { + ret.$types = types; + } // No special types + + } else if (isObject(ret) && hasOwn$1.call(ret, '$types')) { + ret = { + $: ret, + $types: true + }; + } + + if (opts.returnTypeNames) { + return false; + } + + return ret; + } + /** + * + * @param {Any} ret + * @param {GenericArray} promisesData + * @returns {Promise} + */ + + + function checkPromises(_x, _x2) { + return _checkPromises.apply(this, arguments); + } + /** + * + * @param {object} stateObj + * @param {object} ownKeysObj + * @param {function} cb + * @returns {undefined} + */ + + + function _checkPromises() { + _checkPromises = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee2(ret, promisesData) { + var promResults; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all(promisesData.map(function (pd) { + return pd[1].p; + })); + + case 2: + promResults = _context2.sent; + _context2.next = 5; + return Promise.all(promResults.map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(promResult) { + var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; + + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + newPromisesData = []; + _promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; + _prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; + encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); + isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself + // returns a `Typeson.Promise` + + if (!(keyPath && isTypesonPromise)) { + _context.next = 11; + break; + } + + _context.next = 8; + return encaps.p; + + case 8: + encaps2 = _context.sent; + parentObj[key] = encaps2; + return _context.abrupt("return", checkPromises(ret, newPromisesData)); + + case 11: + if (keyPath) { + parentObj[key] = encaps; + } else if (isTypesonPromise) { + ret = encaps.p; + } else { + // If this is itself a `Typeson.Promise` (because the + // original value supplied was a `Promise` or + // because the supplied custom type value resolved + // to one), returning it below will be fine since + // a `Promise` is expected anyways given current + // config (and if not a `Promise`, it will be ready + // as the resolve value) + ret = encaps; + } + + return _context.abrupt("return", checkPromises(ret, newPromisesData)); + + case 13: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x3) { + return _ref.apply(this, arguments); + }; + }())); + + case 5: + return _context2.abrupt("return", ret); + + case 6: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _checkPromises.apply(this, arguments); + } + + function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { + Object.assign(stateObj, ownKeysObj); + var vals = internalStateObjPropsToIgnore.map(function (prop) { + var tmp = stateObj[prop]; + delete stateObj[prop]; + return tmp; + }); // eslint-disable-next-line callback-return + + cb(); + internalStateObjPropsToIgnore.forEach(function (prop, i) { + stateObj[prop] = vals[i]; + }); + } + /** + * + * @param {string} keypath + * @param {Any} value + * @param {boolean} cyclic + * @param {PlainObject} stateObj + * @param {boolean} promisesData + * @param {boolean} resolvingTypesonPromise + * @param {string} detectedType + * @returns {Any} + */ + + + function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) { + var ret; + var observerData = {}; + + var $typeof = _typeof(value); + + var runObserver = encapsulateObserver ? function (obj) { + var type = detectedType || stateObj.type || Typeson.getJSONType(value); + encapsulateObserver(Object.assign(obj || observerData, { + keypath: keypath, + value: value, + cyclic: cyclic, + stateObj: stateObj, + promisesData: promisesData, + resolvingTypesonPromise: resolvingTypesonPromise, + awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise) + }, { + type: type + })); + } : null; + + if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) { + if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) { + if (stateObj.replaced) { + ret = value; + } else { + ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); + } + + if (ret !== value) { + observerData = { + replaced: ret + }; + } + } else { + ret = value; + } + + if (runObserver) { + runObserver(); + } + + return ret; + } + + if (value === null) { + if (runObserver) { + runObserver(); + } + + return value; + } + + if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') { + // Options set to detect cyclic references and be able + // to rewrite them. + var refIndex = refObjs.indexOf(value); + + if (refIndex < 0) { + if (cyclic === true) { + refObjs.push(value); + refKeys.push(keypath); + } + } else { + types[keypath] = '#'; + + if (runObserver) { + runObserver({ + cyclicKeypath: refKeys[refIndex] + }); + } + + return '#' + refKeys[refIndex]; + } + } + + var isPlainObj = isPlainObject(value); + var isArr = isArray(value); + var replaced = // Running replace will cause infinite loop as will test + // positive again + (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object + // replacers, don't try finding a replacer + value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver); + var clone; + + if (replaced !== value) { + ret = replaced; + observerData = { + replaced: replaced + }; + } else { + // eslint-disable-next-line no-lonely-if + if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { + promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); + ret = value; + } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { + clone = new Array(value.length); + observerData = { + clone: clone + }; + } else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') { + clone = {}; + + if (stateObj.addLength) { + clone.length = value.length; + } + + observerData = { + clone: clone + }; + } else { + ret = value; // Only clone vanilla objects and arrays + } + } + + if (runObserver) { + runObserver(); + } + + if (opts.iterateNone) { + return clone || ret; + } + + if (!clone) { + return ret; + } // Iterate object or array + + + if (stateObj.iterateIn) { + var _loop = function _loop(key) { + var ownKeysObj = { + ownKeys: hasOwn$1.call(value, key) + }; + + _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { + var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key); + + var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); + + if (hasConstructorOf(val, TypesonPromise)) { + promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); + } else if (val !== undefined) { + clone[key] = val; + } + }); + }; + + // eslint-disable-next-line guard-for-in + for (var key in value) { + _loop(key); + } + + if (runObserver) { + runObserver({ + endIterateIn: true, + end: true + }); + } + } else { + // Note: Non-indexes on arrays won't survive stringify so + // somewhat wasteful for arrays, but so too is iterating + // all numeric indexes on sparse arrays when not wanted + // or filtering own keys for positive integers + keys(value).forEach(function (key) { + var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key); + var ownKeysObj = { + ownKeys: true + }; + + _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { + var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); + + if (hasConstructorOf(val, TypesonPromise)) { + promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); + } else if (val !== undefined) { + clone[key] = val; + } + }); + }); + + if (runObserver) { + runObserver({ + endIterateOwn: true, + end: true + }); + } + } // Iterate array for non-own numeric properties (we can't + // replace the prior loop though as it iterates non-integer + // keys) + + + if (stateObj.iterateUnsetNumeric) { + var vl = value.length; + + var _loop2 = function _loop2(i) { + if (!(i in value)) { + // No need to escape numeric + var kp = keypath + (keypath ? '.' : '') + i; + var ownKeysObj = { + ownKeys: false + }; + + _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { + var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); + + if (hasConstructorOf(val, TypesonPromise)) { + promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]); + } else if (val !== undefined) { + clone[i] = val; + } + }); + } + }; + + for (var i = 0; i < vl; i++) { + _loop2(i); + } + + if (runObserver) { + runObserver({ + endIterateUnsetNumeric: true, + end: true + }); + } + } + + return clone; + } + /** + * + * @param {string} keypath + * @param {Any} value + * @param {PlainObject} stateObj + * @param {GenericArray} promisesData + * @param {boolean} plainObject + * @param {boolean} resolvingTypesonPromise + * @param {function} [runObserver] + * @returns {*} + */ + + + function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) { + // Encapsulate registered types + var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers; + var i = replacers.length; + + while (i--) { + var replacer = replacers[i]; + + if (replacer.test(value, stateObj)) { + var type = replacer.type; + + if (that.revivers[type]) { + // Record the type only if a corresponding reviver + // exists. This is to support specs where only + // replacement is done. + // For example, ensuring deep cloning of the object, + // or replacing a type to its equivalent without + // the need to revive it. + var existing = types[keypath]; // type can comprise an array of types (see test + // "should support intermediate types") + + types[keypath] = existing ? [type].concat(existing) : type; + } + + Object.assign(stateObj, { + type: type, + replaced: true + }); + + if ((sync || !replacer.replaceAsync) && !replacer.replace) { + if (runObserver) { + runObserver({ + typeDetected: true + }); + } + + return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type); + } + + if (runObserver) { + runObserver({ + replacing: true + }); + } // Now, also traverse the result in case it contains its + // own types to replace + + + var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync'; + return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type); + } + } + + return value; + } + + return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Sync method requested but async result obtained'); + }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Async method requested but sync result obtained'); + }() // If this is a synchronous request for stringification, yet + // a promise is the result, we don't want to resolve leading + // to an async result, so we return an array to avoid + // ambiguity + : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret)); + } + /** + * Also sync but throws on non-sync result. + * @param {*} obj + * @param {object} stateObj + * @param {object} opts + * @returns {*} + */ + + }, { + key: "encapsulateSync", + value: function encapsulateSync(obj, stateObj, opts) { + return this.encapsulate(obj, stateObj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * @param {*} obj + * @param {object} stateObj + * @param {object} opts + * @returns {*} + */ + + }, { + key: "encapsulateAsync", + value: function encapsulateAsync(obj, stateObj, opts) { + return this.encapsulate(obj, stateObj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * Revive an encapsulated object. + * This method is used internally by `Typeson.parse()`. + * @param {object} obj - Object to revive. If it has `$types` member, the + * properties that are listed there will be replaced with its true type + * instead of just plain objects. + * @param {object} opts + * @throws TypeError If mismatch between sync/async type and result + * @returns {Promise|*} If async, returns a Promise that resolves to `*` + */ + + }, { + key: "revive", + value: function revive(obj, opts) { + var types = obj && obj.$types; // No type info added. Revival not needed. + + if (!types) { + return obj; + } // Object happened to have own `$types` property but with + // no actual types, so we unescape and return that object + + + if (types === true) { + return obj.$; + } + + opts = _objectSpread2({ + sync: true + }, this.options, {}, opts); + var _opts3 = opts, + sync = _opts3.sync; + var keyPathResolutions = []; + var stateObj = {}; + var ignore$Types = true; // Special when root object is not a trivial Object, it will + // be encapsulated in `$`. It will also be encapsulated in + // `$` if it has its own `$` property to avoid ambiguity + + if (types.$ && isPlainObject(types.$)) { + obj = obj.$; + types = types.$; + ignore$Types = false; + } + + var that = this; + /** + * @callback RevivalReducer + * @param {Any} value + * @param {string} type + * @returns {Any} + */ + + /** + * + * @param {string} type + * @param {Any} val + * @returns {[type]} [description] + */ + + function executeReviver(type, val) { + var _ref2 = that.revivers[type] || [], + _ref3 = _slicedToArray(_ref2, 1), + reviver = _ref3[0]; + + if (!reviver) { + throw new Error('Unregistered type: ' + type); + } // Only `sync` expected here, as problematic async would + // be missing both `reviver` and `reviverAsync`, and + // encapsulation shouldn't have added types, so + // should have made an early exit + + + if (sync && !('revive' in reviver)) { + // Just return value as is + return val; + } + + return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj); + } + /** + * + * @returns {void|TypesonPromise} + */ + + + function revivePlainObjects() { + // const references = []; + // const reviveTypes = []; + var plainObjectTypes = []; + Object.entries(types).forEach(function (_ref4) { + var _ref5 = _slicedToArray(_ref4, 2), + keypath = _ref5[0], + type = _ref5[1]; + + if (type === '#') { + /* + references.push({ + keypath, + reference: getByKeyPath(obj, keypath) + }); + */ + return; + } + + [].concat(type).forEach(function (type) { + var _ref6 = that.revivers[type] || [null, {}], + _ref7 = _slicedToArray(_ref6, 2), + plain = _ref7[1].plain; + + if (!plain) { + // reviveTypes.push({keypath, type}); + return; + } + + plainObjectTypes.push({ + keypath: keypath, + type: type + }); + delete types[keypath]; // Avoid repeating + }); + }); + + if (!plainObjectTypes.length) { + return undefined; + } // console.log(plainObjectTypes.sort(nestedPathsFirst)); + + /** + * @typedef {PlainObject} PlainObjectType + * @property {string} keypath + * @property {string} type + */ + + + return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) { + var keypath = _ref8.keypath, + type = _ref8.type; + + if (isThenable(possibleTypesonPromise)) { + return possibleTypesonPromise.then(function (val) { + return reducer(val, { + keypath: keypath, + type: type + }); + }); + } // console.log('obj', JSON.stringify(keypath), obj); + + + var val = getByKeyPath(obj, keypath); + val = executeReviver(type, val); + + if (hasConstructorOf(val, TypesonPromise)) { + return val.then(function (v) { + var newVal = setAtKeyPath(obj, keypath, v); + + if (newVal === v) { + obj = newVal; + } + + return undefined; + }); + } + + var newVal = setAtKeyPath(obj, keypath, val); + + if (newVal === val) { + obj = newVal; + } + + return undefined; + }, undefined // This argument must be explicit + ); // references.forEach(({keypath, reference}) => {}); + // reviveTypes.sort(nestedPathsFirst).forEach(() => {}); + } + + var revivalPromises = []; + /** + * + * @param {string} keypath + * @param {Any} value + * @param {?(Array|object)} target + * @param {Array|object} [clone] + * @param {string} [key] + * @returns {Any} + */ + + function _revive(keypath, value, target, clone, key) { + if (ignore$Types && keypath === '$types') { + return undefined; + } + + var type = types[keypath]; + var isArr = isArray(value); + + if (isArr || isPlainObject(value)) { + var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array + + + keys(value).forEach(function (k) { + var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k); + + var set = function set(v) { + if (hasConstructorOf(v, Undefined)) { + _clone[k] = undefined; + } else if (v !== undefined) { + _clone[k] = v; + } + + return v; + }; + + if (hasConstructorOf(val, TypesonPromise)) { + revivalPromises.push(val.then(function (ret) { + return set(ret); + })); + } else { + set(val); + } + }); + value = _clone; // Try to resolve cyclic reference as soon as available + + while (keyPathResolutions.length) { + var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4), + _target = _keyPathResolutions$[0], + keyPath = _keyPathResolutions$[1], + _clone2 = _keyPathResolutions$[2], + k = _keyPathResolutions$[3]; + + var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or + // `undefined` + + if (val !== undefined) { + _clone2[k] = val; + } else { + break; + } + + keyPathResolutions.splice(0, 1); + } + } + + if (!type) { + return value; + } + + if (type === '#') { + var _ret = getByKeyPath(target, value.slice(1)); + + if (_ret === undefined) { + // Cyclic reference not yet available + keyPathResolutions.push([target, value.slice(1), clone, key]); + } + + return _ret; + } // `type` can be an array here + + + return [].concat(type).reduce(function reducer(val, typ) { + if (hasConstructorOf(val, TypesonPromise)) { + return val.then(function (v) { + // TypesonPromise here too + return reducer(v, typ); + }); + } + + return executeReviver(typ, val); + }, value); + } + /** + * + * @param {Any} retrn + * @returns {undefined|Any} + */ + + + function checkUndefined(retrn) { + return hasConstructorOf(retrn, Undefined) ? undefined : retrn; + } + + var possibleTypesonPromise = revivePlainObjects(); + var ret; + + if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { + ret = possibleTypesonPromise.then(function () { + return obj; + }); + } else { + ret = _revive('', obj, null); + + if (revivalPromises.length) { + // Ensure children resolved + ret = TypesonPromise.resolve(ret).then(function (r) { + return TypesonPromise.all([// May be a TypesonPromise or not + r].concat(revivalPromises)); + }).then(function (_ref9) { + var _ref10 = _slicedToArray(_ref9, 1), + r = _ref10[0]; + + return r; + }); + } + } + + return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Sync method requested but async result obtained'); + }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Async method requested but sync result obtained'); + }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret)); + } + /** + * Also sync but throws on non-sync result. + * @param {Any} obj + * @param {object} opts + * @returns {Any} + */ + + }, { + key: "reviveSync", + value: function reviveSync(obj, opts) { + return this.revive(obj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * @param {Any} obj + * @param {object} opts + * @returns {Promise} Resolves to `*` + */ + + }, { + key: "reviveAsync", + value: function reviveAsync(obj, opts) { + return this.revive(obj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * Register types. + * For examples on how to use this method, see + * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}. + * @param {object.[]} typeSpecSets - Types and + * their functions [test, encapsulate, revive]; + * @param {object} opts + * @returns {Typeson} + */ + + }, { + key: "register", + value: function register(typeSpecSets, opts) { + opts = opts || {}; + [].concat(typeSpecSets).forEach(function R(typeSpec) { + var _this = this; + + // Allow arrays of arrays of arrays... + if (isArray(typeSpec)) { + return typeSpec.map(function (typSpec) { + return R.call(_this, typSpec); + }); + } + + typeSpec && keys(typeSpec).forEach(function (typeId) { + if (typeId === '#') { + throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects'); + } else if (Typeson.JSON_TYPES.includes(typeId)) { + throw new TypeError('Plain JSON object types are reserved as type names'); + } + + var spec = typeSpec[typeId]; + var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers; + var existingReplacer = replacers.filter(function (r) { + return r.type === typeId; + }); + + if (existingReplacer.length) { + // Remove existing spec and replace with this one. + replacers.splice(replacers.indexOf(existingReplacer[0]), 1); + delete this.revivers[typeId]; + delete this.types[typeId]; + } + + if (typeof spec === 'function') { + // Support registering just a class without replacer/reviver + var Class = spec; + spec = { + test: function test(x) { + return x && x.constructor === Class; + }, + replace: function replace(x) { + return _objectSpread2({}, x); + }, + revive: function revive(x) { + return Object.assign(Object.create(Class.prototype), x); + } + }; + } else if (isArray(spec)) { + var _spec = spec, + _spec2 = _slicedToArray(_spec, 3), + test = _spec2[0], + replace = _spec2[1], + revive = _spec2[2]; + + spec = { + test: test, + replace: replace, + revive: revive + }; + } + + if (!spec || !spec.test) { + return; + } + + var replacerObj = { + type: typeId, + test: spec.test.bind(spec) + }; + + if (spec.replace) { + replacerObj.replace = spec.replace.bind(spec); + } + + if (spec.replaceAsync) { + replacerObj.replaceAsync = spec.replaceAsync.bind(spec); + } + + var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Infinity; + + if (spec.testPlainObjects) { + this.plainObjectReplacers.splice(start, 0, replacerObj); + } else { + this.nonplainObjectReplacers.splice(start, 0, replacerObj); + } // Todo: We might consider a testAsync type + + + if (spec.revive || spec.reviveAsync) { + var reviverObj = {}; + + if (spec.revive) { + reviverObj.revive = spec.revive.bind(spec); + } + + if (spec.reviveAsync) { + reviverObj.reviveAsync = spec.reviveAsync.bind(spec); + } + + this.revivers[typeId] = [reviverObj, { + plain: spec.testPlainObjects + }]; + } // Record to be retrieved via public types property. + + + this.types[typeId] = spec; + }, this); + }, this); + return this; + } + }]); + + return Typeson; + }(); + /** + * We keep this function minimized so if using two instances of this + * library, where one is minimized and one is not, it will still work + * with `hasConstructorOf`. + * @class + */ + + + var Undefined = function Undefined() { + _classCallCheck(this, Undefined); + }; // eslint-disable-line space-before-blocks + + + Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values + // To insist `undefined` should be added + + Typeson.Undefined = Undefined; // To support async encapsulation/stringification + + Typeson.Promise = TypesonPromise; // Some fundamental type-checking utilities + + Typeson.isThenable = isThenable; + Typeson.toStringTag = toStringTag; + Typeson.hasConstructorOf = hasConstructorOf; + Typeson.isObject = isObject; + Typeson.isPlainObject = isPlainObject; + Typeson.isUserObject = isUserObject; + Typeson.escapeKeyPathComponent = escapeKeyPathComponent; + Typeson.unescapeKeyPathComponent = unescapeKeyPathComponent; + Typeson.getByKeyPath = getByKeyPath; + Typeson.getJSONType = getJSONType; + Typeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object']; + + return Typeson; + + }))); + }); + + var structuredCloning = createCommonjsModule(function (module, exports) { + !function(e,t){module.exports=t();}(commonjsGlobal,(function(){function _typeof$1(e){return (_typeof$1="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck$1(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);re.length)&&(t=e.length);for(var r=0,n=new Array(t);r-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(""===t)return r;var n=t.indexOf(".");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function _await(e,t,r){return r?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}var o=Object.keys,a=Array.isArray,c={}.hasOwnProperty,u=["type","replaced","iterateIn","iterateUnsetNumeric"];function _async(e){return function(){for(var t=[],r=0;rn?-1:rt.keypath}var s=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={};}return function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(Typeson,[{key:"stringify",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var i=this.encapsulate(e,null,n);return a(i)?JSON.stringify(i[0],t,r):i.then((function(e){return JSON.stringify(e,t,r)}))}},{key:"stringifySync",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:"parse",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:"parseSync",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:"rootTypeName",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:"encapsulate",value:function encapsulate(t,r,n){var i=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var o=!1,a=[],c=_slicedToArray(r.splice(0,1),1),u=_slicedToArray(c[0],7),s=u[0],f=u[2],l=u[3],p=u[4],y=u[5],v=u[6],b=_encapsulate(s,n,f,l,a,!0,v),d=hasConstructorOf(b,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(s&&d)return _await(b.p,(function(e){return p[y]=e,o=!0,i(t,a)}))}),(function(e){return o?e:(s?p[y]=b:t=d?b.p:b,i(t,a))}))})))),(function(){return t}))}))})),s=(n=_objectSpread2(_objectSpread2({sync:!0},this.options),n)).sync,f=this,l={},p=[],y=[],v=[],b=!("cyclic"in n)||n.cyclic,d=n.encapsulateObserver,h=_encapsulate("",t,b,r||{},v);function finish(e){var t=Object.values(l);if(n.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=l:e={$:e,$types:{$:l}};}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return !n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=u.map((function(t){var r=e[t];return delete e[t],r}));r(),u.forEach((function(t,r){e[t]=n[r];}));}function _encapsulate(t,r,i,u,s,v,b){var h,g={},m=_typeof(r),O=d?function(n){var o=b||u.type||Typeson.getJSONType(r);d(Object.assign(n||g,{keypath:t,value:r,cyclic:i,stateObj:u,promisesData:s,resolvingTypesonPromise:v,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:o}));}:null;if(["string","boolean","number","undefined"].includes(m))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY?(h=u.replaced?r:replace(t,r,u,s,!1,v,O))!==r&&(g={replaced:h}):h=r,O&&O(),h;if(null===r)return O&&O(),r;if(i&&!u.iterateIn&&!u.iterateUnsetNumeric&&r&&"object"===_typeof(r)){var _=p.indexOf(r);if(!(_<0))return l[t]="#",O&&O({cyclicKeypath:y[_]}),"#"+y[_];!0===i&&(p.push(r),y.push(t));}var j,S=isPlainObject(r),T=a(r),w=(S||T)&&(!f.plainObjectReplacers.length||u.replaced)||u.iterateIn?r:replace(t,r,u,s,S||T,null,O);if(w!==r?(h=w,g={replaced:w}):""===t&&hasConstructorOf(r,e)?(s.push([t,r,i,u,void 0,void 0,u.type]),h=r):T&&"object"!==u.iterateIn||"array"===u.iterateIn?(j=new Array(r.length),g={clone:j}):(["function","symbol"].includes(_typeof(r))||"toJSON"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!S&&"object"!==u.iterateIn?h=r:(j={},u.addLength&&(j.length=r.length),g={clone:j}),O&&O(),n.iterateNone)return j||h;if(!j)return h;if(u.iterateIn){var A=function _loop(n){var o={ownKeys:c.call(r,n)};_adaptBuiltinStateObjectProperties(u,o,(function(){var o=t+(t?".":"")+escapeKeyPathComponent(n),a=_encapsulate(o,r[n],Boolean(i),u,s,v);hasConstructorOf(a,e)?s.push([o,a,Boolean(i),u,j,n,u.type]):void 0!==a&&(j[n]=a);}));};for(var P in r)A(P);O&&O({endIterateIn:!0,end:!0});}else o(r).forEach((function(n){var o=t+(t?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(u,{ownKeys:!0},(function(){var t=_encapsulate(o,r[n],Boolean(i),u,s,v);hasConstructorOf(t,e)?s.push([o,t,Boolean(i),u,j,n,u.type]):void 0!==t&&(j[n]=t);}));})),O&&O({endIterateOwn:!0,end:!0});if(u.iterateUnsetNumeric){for(var I=r.length,C=function _loop2(n){if(!(n in r)){var o=t+(t?".":"")+n;_adaptBuiltinStateObjectProperties(u,{ownKeys:!1},(function(){var t=_encapsulate(o,void 0,Boolean(i),u,s,v);hasConstructorOf(t,e)?s.push([o,t,Boolean(i),u,j,n,u.type]):void 0!==t&&(j[n]=t);}));}},N=0;N>2],o+=O[(3&n[a])<<4|n[a+1]>>4],o+=O[(15&n[a+1])<<2|n[a+2]>>6],o+=O[63&n[a+2]];return i%3==2?o=o.slice(0,-1)+"=":i%3==1&&(o=o.slice(0,-2)+"=="),o},T=function decode(e){var t,r,n,i,o=e.length,a=.75*e.length,c=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);for(var u=new ArrayBuffer(a),s=new Uint8Array(u),f=0;f>4,s[c++]=(15&r)<<4|n>>2,s[c++]=(3&n)<<6|63&i;return u},w={arraybuffer:{test:function test(e){return "ArrayBuffer"===s.toStringTag(e)},replace:function replace(e,t){t.buffers||(t.buffers=[]);var r=t.buffers.indexOf(e);return r>-1?{index:r}:(t.buffers.push(e),S(e))},revive:function revive(e,t){if(t.buffers||(t.buffers=[]),"object"===_typeof$1(e))return t.buffers[e.index];var r=T(e);return t.buffers.push(r),r}}},A="undefined"==typeof self?commonjsGlobal:self,P={};["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"].forEach((function(e){var t=e,r=A[t];r&&(P[e.toLowerCase()]={test:function test(e){return s.toStringTag(e)===t},replace:function replace(e,t){var r=e.buffer,n=e.byteOffset,i=e.length;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(r);return o>-1?{index:o,byteOffset:n,length:i}:(t.buffers.push(r),{encoded:S(r),byteOffset:n,length:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var n,i=e.byteOffset,o=e.length,a=e.encoded,c=e.index;return "index"in e?n=t.buffers[c]:(n=T(a),t.buffers.push(n)),new r(n,i,o)}});}));var I={dataview:{test:function test(e){return "DataView"===s.toStringTag(e)},replace:function replace(e,t){var r=e.buffer,n=e.byteOffset,i=e.byteLength;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(r);return o>-1?{index:o,byteOffset:n,byteLength:i}:(t.buffers.push(r),{encoded:S(r),byteOffset:n,byteLength:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var r,n=e.byteOffset,i=e.byteLength,o=e.encoded,a=e.index;return "index"in e?r=t.buffers[a]:(r=T(o),t.buffers.push(r)),new DataView(r,n,i)}}},C={IntlCollator:{test:function test(e){return s.hasConstructorOf(e,Intl.Collator)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.Collator(e.locale,e)}},IntlDateTimeFormat:{test:function test(e){return s.hasConstructorOf(e,Intl.DateTimeFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.DateTimeFormat(e.locale,e)}},IntlNumberFormat:{test:function test(e){return s.hasConstructorOf(e,Intl.NumberFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.NumberFormat(e.locale,e)}}};function string2arraybuffer(e){for(var t=new Uint8Array(e.length),r=0;r> 2]; + base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4]; + base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6]; + base64 += chars[bytes[_i + 2] & 63]; + } + + if (len % 3 === 2) { + base64 = base64.slice(0, -1) + '='; + } else if (len % 3 === 1) { + base64 = base64.slice(0, -2) + '=='; + } + + return base64; + }; + /** + * @param {string} base64 + * @returns {ArrayBuffer} + */ + + var decode = function decode(base64) { + var len = base64.length; + var bufferLength = base64.length * 0.75; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (var _i2 = 0; _i2 < len; _i2 += 4) { + encoded1 = lookup[base64.codePointAt(_i2)]; + encoded2 = lookup[base64.codePointAt(_i2 + 1)]; + encoded3 = lookup[base64.codePointAt(_i2 + 2)]; + encoded4 = lookup[base64.codePointAt(_i2 + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + + return arraybuffer; + }; + + /* eslint-env browser, node */ + var _global = typeof self === 'undefined' ? global : self; + var exportObj = {}; + [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array' + ].forEach(function (typeName) { + var arrType = typeName; + var TypedArray = _global[arrType]; + if (TypedArray) { + exportObj[typeName.toLowerCase() + "2"] = { + test: function (x) { return typeson.toStringTag(x) === arrType; }, + replace: function (_a) { + var buffer = _a.buffer, byteOffset = _a.byteOffset, length = _a.length; + return { + buffer: buffer, + byteOffset: byteOffset, + length: length + }; + }, + revive: function (b64Obj) { + var buffer = b64Obj.buffer, byteOffset = b64Obj.byteOffset, length = b64Obj.length; + return new TypedArray(buffer, byteOffset, length); + } + }; + } + }); + + var arrayBuffer = { + arraybuffer: { + test: function (x) { return typeson.toStringTag(x) === 'ArrayBuffer'; }, + replace: function (b) { + return encode(b, 0, b.byteLength); + }, + revive: function (b64) { + var buffer = decode(b64); + return buffer; + } + } + }; + // See also typed-arrays! + + var TSON = new typeson().register(structuredCloning); + var readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only. + var blobsToAwait = []; + var blobsToAwaitPos = 0; + // Need to patch encapsulateAsync as it does not work as of typeson 5.8.2 + // Also, current version of typespn-registry-1.0.0-alpha.21 does not + // encapsulate/revive Blobs correctly (fails one of the unit tests in + // this library (test 'export-format')) + TSON.register([ + arrayBuffer, + exportObj, { + blob2: { + test: function (x) { return typeson.toStringTag(x) === 'Blob'; }, + replace: function (b) { + if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob + throw new Error('The Blob is closed'); + } + if (readBlobsSynchronously) { + var data = readBlobSync(b, 'binary'); + var base64 = encode(data, 0, data.byteLength); + return { + type: b.type, + data: base64 + }; + } + else { + blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true. + var result = { + type: b.type, + data: { start: blobsToAwaitPos, end: blobsToAwaitPos + b.size } + }; + blobsToAwaitPos += b.size; + return result; + } + }, + finalize: function (b, ba) { + b.data = encode(ba, 0, ba.byteLength); + }, + revive: function (_a) { + var type = _a.type, data = _a.data; + return new Blob([decode(data)], { type: type }); + } + } + } + ]); + TSON.mustFinalize = function () { return blobsToAwait.length > 0; }; + TSON.finalize = function (items) { return __awaiter(void 0, void 0, void 0, function () { + var allChunks, _i, items_1, item, types, arrayType, keyPath, typeName, typeSpec, b; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, readBlobAsync(new Blob(blobsToAwait), 'binary')]; + case 1: + allChunks = _a.sent(); + if (items) { + for (_i = 0, items_1 = items; _i < items_1.length; _i++) { + item = items_1[_i]; + // Manually go through all "blob" types in the result + // and lookup the data slice they point at. + if (item.$types) { + types = item.$types; + arrayType = types.$; + if (arrayType) + types = types.$; + for (keyPath in types) { + typeName = types[keyPath]; + typeSpec = TSON.types[typeName]; + if (typeSpec && typeSpec.finalize) { + b = Dexie__default["default"].getByKeyPath(item, arrayType ? "$." + keyPath : keyPath); + typeSpec.finalize(b, allChunks.slice(b.start, b.end)); + } + } + } + } + } + // Free up memory + blobsToAwait = []; + return [2 /*return*/]; + } + }); + }); }; + + var DEFAULT_ROWS_PER_CHUNK = 2000; + function exportDB(db, options) { + return __awaiter(this, void 0, void 0, function () { + function exportAll() { + return __awaiter(this, void 0, void 0, function () { + var tablesRowCounts, emptyExportJson, posEndDataArray, firstJsonSlice, filter, _loop_1, _i, tables_1, tableName; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all(db.tables.map(function (table) { return table.count(); }))]; + case 1: + tablesRowCounts = _a.sent(); + tablesRowCounts.forEach(function (rowCount, i) { return tables[i].rowCount = rowCount; }); + progress.totalRows = tablesRowCounts.reduce(function (p, c) { return p + c; }); + emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined); + posEndDataArray = emptyExportJson.lastIndexOf(']'); + firstJsonSlice = emptyExportJson.substring(0, posEndDataArray); + slices.push(firstJsonSlice); + filter = options.filter; + _loop_1 = function (tableName) { + var table, primKey, inbound, LIMIT, emptyTableExport, emptyTableExportJson, posEndRowsArray, lastKey, lastNumRows, mayHaveMoreRows, _loop_2, state_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + table = db.table(tableName); + primKey = table.schema.primKey; + inbound = !!primKey.keyPath; + LIMIT = options.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK; + emptyTableExport = inbound ? { + tableName: table.name, + inbound: true, + rows: [] + } : { + tableName: table.name, + inbound: false, + rows: [] + }; + emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined); + if (prettyJson) { + // Increase indentation according to this: + // { + // ... + // data: [ + // ... + // data: [ + // 123456<---- here + // ] + // ] + // } + emptyTableExportJson = emptyTableExportJson.split('\n').join('\n '); + } + posEndRowsArray = emptyTableExportJson.lastIndexOf(']'); + slices.push(emptyTableExportJson.substring(0, posEndRowsArray)); + lastKey = null; + lastNumRows = 0; + mayHaveMoreRows = true; + _loop_2 = function () { + var chunkedCollection, values, filteredValues, tsonValues, json, keys, keyvals, tsonTuples, json; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default["default"].ignoreTransaction(function () { return progressCallback(progress); }); + } + chunkedCollection = lastKey == null ? + table.limit(LIMIT) : + table.where(':id').above(lastKey).limit(LIMIT); + return [4 /*yield*/, chunkedCollection.toArray()]; + case 1: + values = _c.sent(); + if (values.length === 0) + return [2 /*return*/, "break"]; + if (lastKey != null && lastNumRows > 0) { + // Not initial chunk. Must add a comma: + slices.push(","); + if (prettyJson) { + slices.push("\n "); + } + } + mayHaveMoreRows = values.length === LIMIT; + if (!inbound) return [3 /*break*/, 4]; + filteredValues = filter ? + values.filter(function (value) { return filter(tableName, value); }) : + values; + tsonValues = filteredValues.map(function (value) { return TSON.encapsulate(value); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 3]; + return [4 /*yield*/, Dexie__default["default"].waitFor(TSON.finalize(tsonValues))]; + case 2: + _c.sent(); + _c.label = 3; + case 3: + json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = filteredValues.length; + lastKey = values.length > 0 ? + Dexie__default["default"].getByKeyPath(values[values.length - 1], primKey.keyPath) : + null; + return [3 /*break*/, 8]; + case 4: return [4 /*yield*/, chunkedCollection.primaryKeys()]; + case 5: + keys = _c.sent(); + keyvals = keys.map(function (key, i) { return [key, values[i]]; }); + if (filter) + keyvals = keyvals.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }); + tsonTuples = keyvals.map(function (tuple) { return TSON.encapsulate(tuple); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 7]; + return [4 /*yield*/, Dexie__default["default"].waitFor(TSON.finalize(tsonTuples))]; + case 6: + _c.sent(); + _c.label = 7; + case 7: + json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = keyvals.length; + lastKey = keys.length > 0 ? + keys[keys.length - 1] : + null; + _c.label = 8; + case 8: + progress.completedRows += values.length; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!mayHaveMoreRows) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_2()]; + case 2: + state_1 = _b.sent(); + if (state_1 === "break") + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + slices.push(emptyTableExportJson.substr(posEndRowsArray)); // "]}" + progress.completedTables += 1; + if (progress.completedTables < progress.totalTables) { + slices.push(","); + } + return [2 /*return*/]; + } + }); + }; + _i = 0, tables_1 = tables; + _a.label = 2; + case 2: + if (!(_i < tables_1.length)) return [3 /*break*/, 5]; + tableName = tables_1[_i].name; + return [5 /*yield**/, _loop_1(tableName)]; + case 3: + _a.sent(); + _a.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + slices.push(emptyExportJson.substr(posEndDataArray)); + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default["default"].ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); + } + var slices, tables, prettyJson, emptyExport, progressCallback, progress; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; + slices = []; + tables = db.tables.map(function (table) { return ({ + name: table.name, + schema: getSchemaString(table), + rowCount: 0 + }); }); + prettyJson = options.prettyJson; + emptyExport = { + formatName: "dexie", + formatVersion: 1, + data: { + databaseName: db.name, + databaseVersion: db.verno, + tables: tables, + data: [] + } + }; + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: NaN, + totalTables: db.tables.length + }; + _a.label = 1; + case 1: + _a.trys.push([1, , 6, 7]); + if (!options.noTransaction) return [3 /*break*/, 3]; + return [4 /*yield*/, exportAll()]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, db.transaction('r', db.tables, exportAll)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: return [3 /*break*/, 7]; + case 6: + TSON.finalize(); // Free up mem if error has occurred + return [7 /*endfinally*/]; + case 7: return [2 /*return*/, new Blob(slices, { type: "text/json" })]; + } + }); + }); + } + + var VERSION = 1; + + var fakeStream = {Stream: function(){}}; + + var clarinet_1 = createCommonjsModule(function (module, exports) { + (function (clarinet) { + + // non node-js needs to set clarinet debug on root + var env =(typeof process === 'object' && process.env) + ? process.env + : self; + + clarinet.parser = function (opt) { return new CParser(opt);}; + clarinet.CParser = CParser; + clarinet.CStream = CStream; + clarinet.createStream = createStream; + clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024; + clarinet.DEBUG = (env.CDEBUG==='debug'); + clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info'); + clarinet.EVENTS = + [ "value" + , "string" + , "key" + , "openobject" + , "closeobject" + , "openarray" + , "closearray" + , "error" + , "end" + , "ready" + ]; + + var buffers = { + textNode: undefined, + numberNode: "" + } + , streamWraps = clarinet.EVENTS.filter(function (ev) { + return ev !== "error" && ev !== "end"; + }) + , S = 0 + , Stream + ; + + clarinet.STATE = + { BEGIN : S++ + , VALUE : S++ // general stuff + , OPEN_OBJECT : S++ // { + , CLOSE_OBJECT : S++ // } + , OPEN_ARRAY : S++ // [ + , CLOSE_ARRAY : S++ // ] + , TEXT_ESCAPE : S++ // \ stuff + , STRING : S++ // "" + , BACKSLASH : S++ + , END : S++ // No more stack + , OPEN_KEY : S++ // , "a" + , CLOSE_KEY : S++ // : + , TRUE : S++ // r + , TRUE2 : S++ // u + , TRUE3 : S++ // e + , FALSE : S++ // a + , FALSE2 : S++ // l + , FALSE3 : S++ // s + , FALSE4 : S++ // e + , NULL : S++ // u + , NULL2 : S++ // l + , NULL3 : S++ // l + , NUMBER_DECIMAL_POINT : S++ // . + , NUMBER_DIGIT : S++ // [0-9] + }; + + for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_; + + // switcharoo + S = clarinet.STATE; + + const Char = { + tab : 0x09, // \t + lineFeed : 0x0A, // \n + carriageReturn : 0x0D, // \r + space : 0x20, // " " + + doubleQuote : 0x22, // " + plus : 0x2B, // + + comma : 0x2C, // , + minus : 0x2D, // - + period : 0x2E, // . + + _0 : 0x30, // 0 + _9 : 0x39, // 9 + + colon : 0x3A, // : + + E : 0x45, // E + + openBracket : 0x5B, // [ + backslash : 0x5C, // \ + closeBracket : 0x5D, // ] + + a : 0x61, // a + b : 0x62, // b + e : 0x65, // e + f : 0x66, // f + l : 0x6C, // l + n : 0x6E, // n + r : 0x72, // r + s : 0x73, // s + t : 0x74, // t + u : 0x75, // u + + openBrace : 0x7B, // { + closeBrace : 0x7D, // } + }; + + if (!Object.create) { + Object.create = function (o) { + function f () { this["__proto__"] = o; } + f.prototype = o; + return new f; + }; + } + + if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function (o) { + return o["__proto__"]; + }; + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = []; + for (var i in o) if (o.hasOwnProperty(i)) a.push(i); + return a; + }; + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10) + , maxActual = 0 + ; + for (var buffer in buffers) { + var len = parser[buffer] === undefined ? 0 : parser[buffer].length; + if (len > maxAllowed) { + switch (buffer) { + case "text": + closeText(parser); + break; + + default: + error(parser, "Max buffer length exceeded: "+ buffer); + } + } + maxActual = Math.max(maxActual, len); + } + parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual) + + parser.position; + } + + function clearBuffers (parser) { + for (var buffer in buffers) { + parser[buffer] = buffers[buffer]; + } + } + + var stringTokenPattern = /[\\"\n]/g; + + function CParser (opt) { + if (!(this instanceof CParser)) return new CParser (opt); + + var parser = this; + clearBuffers(parser); + parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH; + parser.q = parser.c = parser.p = ""; + parser.opt = opt || {}; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.state = S.BEGIN; + parser.stack = new Array(); + // mostly just for error reporting + parser.position = parser.column = 0; + parser.line = 1; + parser.slashed = false; + parser.unicodeI = 0; + parser.unicodeS = null; + parser.depth = 0; + emit(parser, "onready"); + } + + CParser.prototype = + { end : function () { end(this); } + , write : write + , resume : function () { this.error = null; return this; } + , close : function () { return this.write(null); } + }; + + try { Stream = fakeStream.Stream; } + catch (ex) { Stream = function () {}; } + + function createStream (opt) { return new CStream(opt); } + + function CStream (opt) { + if (!(this instanceof CStream)) return new CStream(opt); + + this._parser = new CParser(opt); + this.writable = true; + this.readable = true; + + //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached + this.string = ''; + + var me = this; + Stream.apply(me); + + this._parser.onend = function () { me.emit("end"); }; + this._parser.onerror = function (er) { + me.emit("error", er); + me._parser.error = null; + }; + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, "on" + ev, + { get : function () { return me._parser["on" + ev]; } + , set : function (h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on"+ev] = h; + return h; + } + me.on(ev, h); + } + , enumerable : true + , configurable : false + }); + }); + } + + CStream.prototype = Object.create(Stream.prototype, + { constructor: { value: CStream } }); + + CStream.prototype.write = function (data) { + data = new Buffer(data); + for (var i = 0; i < data.length; i++) { + var n = data[i]; + + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j]; + } + this.string = this.temp_buffs[this.bytes_in_sequence].toString(); + this.bytes_in_sequence = this.bytes_remaining = 0; + + // move iterator forward by number of byte read during sequencing + i = i + j - 1; + + // pass data to parser and move forward to parse rest of data + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + + // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (this.bytes_remaining === 0 && n >= 128) { + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split + + for (var k = 0; k <= (data.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - data.length; + + // immediately return as we need another chunk to sequence the character + return true; + } else { + this.string = data.slice(i, (i + this.bytes_in_sequence)).toString(); + i = i + this.bytes_in_sequence - 1; + + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + } + + // is there a range of characters that are immediately parsable? + for (var p = i; p < data.length; p++) { + if (data[p] >= 128) break; + } + this.string = data.slice(i, p).toString(); + this._parser.write(this.string); + this.emit("data", this.string); + i = p - 1; + + // handle any remaining characters using multibyte logic + continue; + } + }; + + CStream.prototype.end = function (chunk) { + if (chunk && chunk.length) this._parser.write(chunk.toString()); + this._parser.end(); + return true; + }; + + CStream.prototype.on = function (ev, handler) { + var me = this; + if (!me._parser["on"+ev] && streamWraps.indexOf(ev) !== -1) { + me._parser["on"+ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] + : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + } + return Stream.prototype.on.call(me, ev, handler); + }; + + CStream.prototype.destroy = function () { + clearBuffers(this._parser); + this.emit("close"); + }; + + function emit(parser, event, data) { + if(clarinet.INFO) console.log('-- emit', event, data); + if (parser[event]) parser[event](data); + } + + function emitNode(parser, event, data) { + closeValue(parser); + emit(parser, event, data); + } + + function closeValue(parser, event) { + parser.textNode = textopts(parser.opt, parser.textNode); + if (parser.textNode !== undefined) { + emit(parser, (event ? event : "onvalue"), parser.textNode); + } + parser.textNode = undefined; + } + + function closeNumber(parser) { + if (parser.numberNode) + emit(parser, "onvalue", parseFloat(parser.numberNode)); + parser.numberNode = ""; + } + + function textopts (opt, text) { + if (text === undefined) { + return text; + } + if (opt.trim) text = text.trim(); + if (opt.normalize) text = text.replace(/\s+/g, " "); + return text; + } + + function error (parser, er) { + closeValue(parser); + er += "\nLine: "+parser.line+ + "\nColumn: "+parser.column+ + "\nChar: "+parser.c; + er = new Error(er); + parser.error = er; + emit(parser, "onerror", er); + return parser; + } + + function end(parser) { + if (parser.state !== S.VALUE || parser.depth !== 0) + error(parser, "Unexpected end"); + + closeValue(parser); + parser.c = ""; + parser.closed = true; + emit(parser, "onend"); + CParser.call(parser, parser.opt); + return parser; + } + + function isWhitespace(c) { + return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab; + } + + function write (chunk) { + var parser = this; + if (this.error) throw this.error; + if (parser.closed) return error(parser, + "Cannot write after close. Assign an onready handler."); + if (chunk === null) return end(parser); + var i = 0, c = chunk.charCodeAt(0), p = parser.p; + if (clarinet.DEBUG) console.log('write -> [' + chunk + ']'); + while (c) { + p = c; + parser.c = c = chunk.charCodeAt(i++); + // if chunk doesnt have next, like streaming char by char + // this way we need to check if previous is really previous + // if not we need to reset to what the parser says is the previous + // from buffer + if(p !== c ) parser.p = p; + else p = parser.p; + + if(!c) break; + + if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]); + parser.position ++; + if (c === Char.lineFeed) { + parser.line ++; + parser.column = 0; + } else parser.column ++; + switch (parser.state) { + + case S.BEGIN: + if (c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if (!isWhitespace(c)) + error(parser, "Non-whitespace before {[."); + continue; + + case S.OPEN_KEY: + case S.OPEN_OBJECT: + if (isWhitespace(c)) continue; + if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY); + else { + if(c === Char.closeBrace) { + emit(parser, 'onopenobject'); + this.depth++; + emit(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else parser.stack.push(S.CLOSE_OBJECT); + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else error(parser, "Malformed object key should start with \""); + continue; + + case S.CLOSE_KEY: + case S.CLOSE_OBJECT: + if (isWhitespace(c)) continue; + (parser.state === S.CLOSE_KEY) ? 'key' : 'object'; + if(c === Char.colon) { + if(parser.state === S.CLOSE_OBJECT) { + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser, 'onopenobject'); + this.depth++; + } else closeValue(parser, 'onkey'); + parser.state = S.VALUE; + } else if (c === Char.closeBrace) { + emitNode(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if(c === Char.comma) { + if(parser.state === S.CLOSE_OBJECT) + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser); + parser.state = S.OPEN_KEY; + } else error(parser, 'Bad object'); + continue; + + case S.OPEN_ARRAY: // after an array there always a value + case S.VALUE: + if (isWhitespace(c)) continue; + if(parser.state===S.OPEN_ARRAY) { + emit(parser, 'onopenarray'); + this.depth++; + parser.state = S.VALUE; + if(c === Char.closeBracket) { + emit(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else { + parser.stack.push(S.CLOSE_ARRAY); + } + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if(c === Char.t) parser.state = S.TRUE; + else if(c === Char.f) parser.state = S.FALSE; + else if(c === Char.n) parser.state = S.NULL; + else if(c === Char.minus) { // keep and continue + parser.numberNode += "-"; + } else if(Char._0 <= c && c <= Char._9) { + parser.numberNode += String.fromCharCode(c); + parser.state = S.NUMBER_DIGIT; + } else error(parser, "Bad value"); + continue; + + case S.CLOSE_ARRAY: + if(c === Char.comma) { + parser.stack.push(S.CLOSE_ARRAY); + closeValue(parser, 'onvalue'); + parser.state = S.VALUE; + } else if (c === Char.closeBracket) { + emitNode(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if (isWhitespace(c)) + continue; + else error(parser, 'Bad array'); + continue; + + case S.STRING: + if (parser.textNode === undefined) { + parser.textNode = ""; + } + + // thanks thejh, this is an about 50% performance improvement. + var starti = i-1 + , slashed = parser.slashed + , unicodeI = parser.unicodeI + ; + STRING_BIGLOOP: while (true) { + if (clarinet.DEBUG) + console.log(i,c,clarinet.STATE[parser.state] + ,slashed); + // zero means "no unicode active". 1-4 mean "parse some more". end after 4. + while (unicodeI > 0) { + parser.unicodeS += String.fromCharCode(c); + c = chunk.charCodeAt(i++); + parser.position++; + if (unicodeI === 4) { + // TODO this might be slow? well, probably not used too often anyway + parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16)); + unicodeI = 0; + starti = i-1; + } else { + unicodeI++; + } + // we can just break here: no stuff we skipped that still has to be sliced out or so + if (!c) break STRING_BIGLOOP; + } + if (c === Char.doubleQuote && !slashed) { + parser.state = parser.stack.pop() || S.VALUE; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + if (c === Char.backslash && !slashed) { + slashed = true; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + c = chunk.charCodeAt(i++); + parser.position++; + if (!c) break; + } + if (slashed) { + slashed = false; + if (c === Char.n) { parser.textNode += '\n'; } + else if (c === Char.r) { parser.textNode += '\r'; } + else if (c === Char.t) { parser.textNode += '\t'; } + else if (c === Char.f) { parser.textNode += '\f'; } + else if (c === Char.b) { parser.textNode += '\b'; } + else if (c === Char.u) { + // \uxxxx. meh! + unicodeI = 1; + parser.unicodeS = ''; + } else { + parser.textNode += String.fromCharCode(c); + } + c = chunk.charCodeAt(i++); + parser.position++; + starti = i-1; + if (!c) break; + else continue; + } + + stringTokenPattern.lastIndex = i; + var reResult = stringTokenPattern.exec(chunk); + if (reResult === null) { + i = chunk.length+1; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + i = reResult.index+1; + c = chunk.charCodeAt(reResult.index); + if (!c) { + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + } + parser.slashed = slashed; + parser.unicodeI = unicodeI; + continue; + + case S.TRUE: + if (c === Char.r) parser.state = S.TRUE2; + else error(parser, 'Invalid true started with t'+ c); + continue; + + case S.TRUE2: + if (c === Char.u) parser.state = S.TRUE3; + else error(parser, 'Invalid true started with tr'+ c); + continue; + + case S.TRUE3: + if(c === Char.e) { + emit(parser, "onvalue", true); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid true started with tru'+ c); + continue; + + case S.FALSE: + if (c === Char.a) parser.state = S.FALSE2; + else error(parser, 'Invalid false started with f'+ c); + continue; + + case S.FALSE2: + if (c === Char.l) parser.state = S.FALSE3; + else error(parser, 'Invalid false started with fa'+ c); + continue; + + case S.FALSE3: + if (c === Char.s) parser.state = S.FALSE4; + else error(parser, 'Invalid false started with fal'+ c); + continue; + + case S.FALSE4: + if (c === Char.e) { + emit(parser, "onvalue", false); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid false started with fals'+ c); + continue; + + case S.NULL: + if (c === Char.u) parser.state = S.NULL2; + else error(parser, 'Invalid null started with n'+ c); + continue; + + case S.NULL2: + if (c === Char.l) parser.state = S.NULL3; + else error(parser, 'Invalid null started with nu'+ c); + continue; + + case S.NULL3: + if(c === Char.l) { + emit(parser, "onvalue", null); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid null started with nul'+ c); + continue; + + case S.NUMBER_DECIMAL_POINT: + if(c === Char.period) { + parser.numberNode += "."; + parser.state = S.NUMBER_DIGIT; + } else error(parser, 'Leading zero not followed by .'); + continue; + + case S.NUMBER_DIGIT: + if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c); + else if (c === Char.period) { + if(parser.numberNode.indexOf('.')!==-1) + error(parser, 'Invalid number has two dots'); + parser.numberNode += "."; + } else if (c === Char.e || c === Char.E) { + if(parser.numberNode.indexOf('e')!==-1 || + parser.numberNode.indexOf('E')!==-1 ) + error(parser, 'Invalid number has two exponential'); + parser.numberNode += "e"; + } else if (c === Char.plus || c === Char.minus) { + if(!(p === Char.e || p === Char.E)) + error(parser, 'Invalid symbol in number'); + parser.numberNode += String.fromCharCode(c); + } else { + closeNumber(parser); + i--; // go back one + parser.state = parser.stack.pop() || S.VALUE; + } + continue; + + default: + error(parser, "Unknown state: " + parser.state); + } + } + if (parser.position >= parser.bufferCheckPosition) + checkBufferLength(parser); + return parser; + } + + })(exports); + }); + + function JsonStream(blob) { + var pos = 0; + var parser = JsonParser(true); + var rv = { + pullAsync: function (numBytes) { + return __awaiter(this, void 0, void 0, function () { + var slize, jsonPart, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + return [4 /*yield*/, readBlobAsync(slize, 'text')]; + case 1: + jsonPart = _a.sent(); + result = parser.write(jsonPart); + rv.result = result || {}; + return [2 /*return*/, result]; + } + }); + }); + }, + pullSync: function (numBytes) { + var slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + var jsonPart = readBlobSync(slize, 'text'); + var result = parser.write(jsonPart); + rv.result = result || {}; + return result; + }, + done: function () { + return parser.done(); + }, + eof: function () { + return pos >= blob.size; + }, + result: {} + }; + return rv; + } + function JsonParser(allowPartial) { + var parser = clarinet_1.parser(); + var level = 0; + var result; + var stack = []; + var obj; + var key; + var done = false; + var array = false; + parser.onopenobject = function (newKey) { + var newObj = {}; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + key = newKey; + array = false; + ++level; + }; + parser.onkey = function (newKey) { return key = newKey; }; + parser.onvalue = function (value) { return array ? obj.push(value) : obj[key] = value; }; + parser.oncloseobject = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + parser.onopenarray = function () { + var newObj = []; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + array = true; + key = null; + ++level; + }; + parser.onclosearray = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + return { + write: function (jsonPart) { + parser.write(jsonPart); + return result; + }, + done: function () { + return done; + } + }; + } + + var DEFAULT_KILOBYTES_PER_CHUNK = 1024; + function importDB(exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + var CHUNK_SIZE, stream, dbExport, db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + stream = _a.sent(); + dbExport = stream.result.data; + db = new Dexie__default["default"](dbExport.databaseName); + db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport)); + return [4 /*yield*/, importInto(db, stream, options)]; + case 2: + _a.sent(); + return [2 /*return*/, db]; + } + }); + }); + } + function peakImportFile(exportedData) { + return __awaiter(this, void 0, void 0, function () { + var stream; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = JsonStream(exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(5 * 1024)]; + case 2: + _a.sent(); // 5 k is normally enough for the headers. If not, it will just do another go. + if (stream.result.data && stream.result.data.data) { + // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it. + delete stream.result.data.data; // Don't return half-baked data array. + return [3 /*break*/, 3]; + } + return [3 /*break*/, 1]; + case 3: return [2 /*return*/, stream.result]; + } + }); + }); + } + function importInto(db, exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + function importAll() { + return __awaiter(this, void 0, void 0, function () { + var _loop_1, _i, _a, tableExport, state_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _loop_1 = function (tableExport) { + var tableName, table, tableSchemaStr, sourceRows, rows, i, obj, filter, filteredRows, _c, keys, values; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + if (!tableExport.rows) + return [2 /*return*/, "break"]; // Need to pull more! + if (!tableExport.rows.incomplete && tableExport.rows.length === 0) + return [2 /*return*/, "continue"]; + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default["default"].ignoreTransaction(function () { return progressCallback(progress); }); + } + tableName = tableExport.tableName; + table = db.table(tableName); + tableSchemaStr = dbExport.tables.filter(function (t) { return t.name === tableName; })[0].schema; + if (!table) { + if (!options.acceptMissingTables) + throw new Error("Exported table ".concat(tableExport.tableName, " is missing in installed database")); + else + return [2 /*return*/, "continue"]; + } + if (!options.acceptChangedPrimaryKey && + tableSchemaStr.split(',')[0] != table.schema.primKey.src) { + throw new Error("Primary key differs for table ".concat(tableExport.tableName, ". ")); + } + sourceRows = tableExport.rows; + rows = []; + for (i = 0; i < sourceRows.length; i++) { + obj = sourceRows[i]; + if (!obj.incomplete) { + rows.push(TSON.revive(obj)); + } + else { + break; + } + } + filter = options.filter; + filteredRows = filter ? + tableExport.inbound ? + rows.filter(function (value) { return filter(tableName, value); }) : + rows.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }) : + rows; + _c = tableExport.inbound ? + [undefined, filteredRows] : + [filteredRows.map(function (row) { return row[0]; }), rows.map(function (row) { return row[1]; })], keys = _c[0], values = _c[1]; + if (!options.overwriteValues) return [3 /*break*/, 2]; + return [4 /*yield*/, table.bulkPut(values, keys)]; + case 1: + _d.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, table.bulkAdd(values, keys)]; + case 3: + _d.sent(); + _d.label = 4; + case 4: + progress.completedRows += rows.length; + if (!rows.incomplete) { + progress.completedTables += 1; + } + sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance. + return [2 /*return*/]; + } + }); + }; + _i = 0, _a = dbExport.data; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + tableExport = _a[_i]; + return [5 /*yield**/, _loop_1(tableExport)]; + case 2: + state_1 = _b.sent(); + if (state_1 === "break") + return [3 /*break*/, 4]; + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: + // Avoid unnescessary loops in "for (const tableExport of dbExport.data)" + while (dbExport.data.length > 0 && dbExport.data[0].rows && !dbExport.data[0].rows.incomplete) { + // We've already imported all rows from the first table. Delete its occurrence + dbExport.data.splice(0, 1); + } + if (!(!jsonStream.done() && !jsonStream.eof())) return [3 /*break*/, 8]; + if (!readBlobsSynchronously) return [3 /*break*/, 5]; + // If we can pull from blob synchronically, we don't have to + // keep transaction alive using Dexie.waitFor(). + // This will only be possible in workers. + jsonStream.pullSync(CHUNK_SIZE); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, Dexie__default["default"].waitFor(jsonStream.pullAsync(CHUNK_SIZE))]; + case 6: + _b.sent(); + _b.label = 7; + case 7: return [3 /*break*/, 9]; + case 8: return [3 /*break*/, 10]; + case 9: + return [3 /*break*/, 0]; + case 10: return [2 /*return*/]; + } + }); + }); + } + var CHUNK_SIZE, jsonStream, dbExportFile, readBlobsSynchronously, dbExport, progressCallback, progress, _i, _a, table; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + jsonStream = _b.sent(); + dbExportFile = jsonStream.result; + readBlobsSynchronously = 'FileReaderSync' in self; + dbExport = dbExportFile.data; + if (!options.acceptNameDiff && db.name !== dbExport.databaseName) + throw new Error("Name differs. Current database name is ".concat(db.name, " but export is ").concat(dbExport.databaseName)); + if (!options.acceptVersionDiff && db.verno !== dbExport.databaseVersion) { + // Possible feature: Call upgraders in some isolated way if this happens... ? + throw new Error("Database version differs. Current database is in version ".concat(db.verno, " but export is ").concat(dbExport.databaseVersion)); + } + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: dbExport.tables.reduce(function (p, c) { return p + c.rowCount; }, 0), + totalTables: dbExport.tables.length + }; + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default["default"].ignoreTransaction(function () { return progressCallback(progress); }); + } + if (!options.clearTablesBeforeImport) return [3 /*break*/, 5]; + _i = 0, _a = db.tables; + _b.label = 2; + case 2: + if (!(_i < _a.length)) return [3 /*break*/, 5]; + table = _a[_i]; + return [4 /*yield*/, table.clear()]; + case 3: + _b.sent(); + _b.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + if (!options.noTransaction) return [3 /*break*/, 7]; + return [4 /*yield*/, importAll()]; + case 6: + _b.sent(); + return [3 /*break*/, 9]; + case 7: return [4 /*yield*/, db.transaction('rw', db.tables, importAll)]; + case 8: + _b.sent(); + _b.label = 9; + case 9: + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie__default["default"].ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); + } + function loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE) { + return __awaiter(this, void 0, void 0, function () { + var stream, dbExportFile; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = ('slice' in exportedData ? + JsonStream(exportedData) : + exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(CHUNK_SIZE)]; + case 2: + _a.sent(); + if (stream.result.data && stream.result.data.data) + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + dbExportFile = stream.result; + if (!dbExportFile || dbExportFile.formatName != "dexie") + throw new Error("Given file is not a dexie export"); + if (dbExportFile.formatVersion > VERSION) { + throw new Error("Format version ".concat(dbExportFile.formatVersion, " not supported")); + } + if (!dbExportFile.data) { + throw new Error("No data in export file"); + } + if (!dbExportFile.data.databaseName) { + throw new Error("Missing databaseName in export file"); + } + if (!dbExportFile.data.databaseVersion) { + throw new Error("Missing databaseVersion in export file"); + } + if (!dbExportFile.data.tables) { + throw new Error("Missing tables in export file"); + } + return [2 /*return*/, stream]; + } + }); + }); + } + + // + // Extend Dexie interface (runtime wise) + // + Dexie__default["default"].prototype.export = function (options) { + return exportDB(this, options); + }; + Dexie__default["default"].prototype.import = function (blob, options) { + return importInto(this, blob, options); + }; + Dexie__default["default"].import = function (blob, options) { return importDB(blob, options); }; + var dexieExportImport = (function () { + throw new Error("This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options."); + }); + + exports["default"] = dexieExportImport; + exports.exportDB = exportDB; + exports.importDB = importDB; + exports.importInto = importInto; + exports.peakImportFile = peakImportFile; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=dexie-export-import.js.map diff --git a/addons/dexie-export-import/dist/dexie-export-import.js.map b/addons/dexie-export-import/dist/dexie-export-import.js.map new file mode 100644 index 000000000..a335aecfa --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-export-import.js","sources":["../../../node_modules/.pnpm/tslib@2.3.1/node_modules/tslib/tslib.es6.js","../src/helpers.ts","../../../node_modules/.pnpm/typeson@5.18.2_core-js-bundle@3.27.2_regenerator-runtime@0.13.11/node_modules/typeson/dist/typeson.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/node_modules/typeson/dist/typeson-esm.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/user-object.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/presets/array-nonindex-keys.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/undef.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/primitive-objects.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/presets/special-numbers.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/nan.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/infinity.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/negative-infinity.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/date.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/regexp.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/map.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/set.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/arraybuffer.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/typed-arrays.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/dataview.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/intl-types.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/utils/stringArrayBuffer.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/file.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/bigint.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/bigint-object.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/cryptokey.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/presets/structured-cloning.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/imagedata.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/imagebitmap.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/filelist.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/blob.js","../../../node_modules/.pnpm/base64-arraybuffer-es6@1.0.0/node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js","../src/tson-typed-array.ts","../src/tson-arraybuffer.ts","../src/tson.ts","../src/export.ts","../src/json-structure.ts","../tools/build-configs/fake-stream.js","../../../node_modules/.pnpm/github.com+dfahlander+clarinet@d1dc89f7e67488b16ad98b2464d29a9b3bc6f5ef/node_modules/clarinet/clarinet.js","../src/json-stream.ts","../src/import.ts","../src/dexie-export-import.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","import Dexie from 'dexie';\nimport { DexieExportedDatabase } from './json-structure';\n\nexport function getSchemaString(table: Dexie.Table) {\n const primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes);\n return primKeyAndIndexes.map(index => index.src).join(',');\n}\n\nexport function extractDbSchema(exportedDb: DexieExportedDatabase) {\n const schema: {\n [tableName: string]: string;\n } = {};\n for (const table of exportedDb.tables) {\n schema[table.name] = table.schema;\n }\n return schema;\n}\n\n\n// Missing FileReaderSync type in standard typescript libs:\ninterface FileReaderSync {\n readAsArrayBuffer(blob: Blob): ArrayBuffer;\n readAsBinaryString(blob: Blob): string;\n readAsDataURL(blob: Blob): string;\n readAsText(blob: Blob, encoding?: string): string;\n}\ndeclare var FileReaderSync: {\n prototype: FileReaderSync;\n new(): FileReaderSync;\n};\n// -----------------------------------------------\n\nexport interface TypeMapper {\n binary: ArrayBuffer;\n text: string;\n}\n\nexport function readBlobAsync(blob: Blob, type: T): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = ev => reject(new Error(\"file read aborted\"));\n reader.onerror = ev => reject((ev.target as any).error);\n reader.onload = ev => resolve((ev.target as any).result);\n if (type === 'binary')\n reader.readAsArrayBuffer(blob);\n else\n reader.readAsText(blob);\n });\n}\n\nexport function readBlobSync(blob: Blob, type: T): TypeMapper[T] {\n if (typeof FileReaderSync === 'undefined') {\n throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.');\n }\n const reader = new FileReaderSync(); // Requires worker environment\n const data = type === 'binary' ?\n reader.readAsArrayBuffer(blob) :\n reader.readAsText(blob);\n\n return data as TypeMapper[T];\n}\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = global || self, global.Typeson = factory());\n}(this, (function () { 'use strict';\n\n function _typeof(obj) {\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n }\n\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n }\n\n function _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n }\n\n function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n\n function _iterableToArray(iter) {\n if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter);\n }\n\n function _iterableToArrayLimit(arr, i) {\n if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\")) {\n return;\n }\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance\");\n }\n\n function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n\n /**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * With ES6 classes, we may be able to simply use `class TypesonPromise\n * extends Promise` and add a string tag for detection.\n * @param {function} f\n */\n // eslint-disable-next-line max-len\n // eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new\n var TypesonPromise = function TypesonPromise(f) {\n _classCallCheck(this, TypesonPromise);\n\n this.p = new Promise(f);\n }; // eslint-disable-next-line max-len\n // class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi\n\n\n TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill\n\n /* istanbul ignore else */\n\n if (typeof Symbol !== 'undefined') {\n // Ensure `isUserObject` will return `false` for `TypesonPromise`\n TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise';\n }\n /**\n *\n * @param {function} [onFulfilled]\n * @param {function} [onRejected]\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.prototype.then = function (onFulfilled, onRejected) {\n var _this = this;\n\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n _this.p.then(function (res) {\n // eslint-disable-next-line promise/always-return\n typesonResolve(onFulfilled ? onFulfilled(res) : res);\n })[\"catch\"](function (res) {\n return onRejected ? onRejected(res) : Promise.reject(res);\n }).then(typesonResolve, typesonReject);\n });\n };\n /**\n *\n * @param {function} onRejected\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n *\n * @param {Any} v\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.resolve = function (v) {\n return new TypesonPromise(function (typesonResolve) {\n typesonResolve(v);\n });\n };\n /**\n *\n * @param {Any} v\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.reject = function (v) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n typesonReject(v);\n });\n };\n\n ['all', 'race'].forEach(function (meth) {\n /**\n *\n * @param {Promise[]} promArr\n * @returns {TypesonPromise}\n */\n TypesonPromise[meth] = function (promArr) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n Promise[meth](promArr.map(function (prom) {\n return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom;\n })).then(typesonResolve, typesonReject);\n });\n };\n });\n\n var _ref = {},\n toStr = _ref.toString,\n hasOwn = {}.hasOwnProperty,\n getProto = Object.getPrototypeOf,\n fnToString = hasOwn.toString;\n /**\n * Second argument not in use internally, but provided for utility.\n * @param {Any} v\n * @param {boolean} catchCheck\n * @returns {boolean}\n */\n\n function isThenable(v, catchCheck) {\n return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v[\"catch\"] === 'function');\n }\n /**\n *\n * @param {Any} val\n * @returns {string}\n */\n\n\n function toStringTag(val) {\n return toStr.call(val).slice(8, -1);\n }\n /**\n * This function is dependent on both constructors\n * being identical so any minimization is expected of both.\n * @param {Any} a\n * @param {function} b\n * @returns {boolean}\n */\n\n\n function hasConstructorOf(a, b) {\n if (!a || _typeof(a) !== 'object') {\n return false;\n }\n\n var proto = getProto(a);\n\n if (!proto) {\n return b === null;\n }\n\n var Ctor = hasOwn.call(proto, 'constructor') && proto.constructor;\n\n if (typeof Ctor !== 'function') {\n return b === null;\n }\n\n if (b === Ctor) {\n return true;\n }\n\n if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) {\n return true;\n }\n\n if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) {\n return true;\n }\n\n return false;\n }\n /**\n *\n * @param {Any} val\n * @returns {boolean}\n */\n\n\n function isPlainObject(val) {\n // Mirrors jQuery's\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object);\n }\n /**\n *\n * @param {Any} val\n * @returns {boolean}\n */\n\n\n function isUserObject(val) {\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object) || isUserObject(proto);\n }\n /**\n *\n * @param {Any} v\n * @returns {boolean}\n */\n\n\n function isObject(v) {\n return v && _typeof(v) === 'object';\n }\n /**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\n function escapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~/g, '~0').replace(/\\./g, '~1');\n }\n /**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\n function unescapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~');\n }\n /**\n * @param {PlainObject|GenericArray} obj\n * @param {string} keyPath\n * @returns {Any}\n */\n\n\n function getByKeyPath(obj, keyPath) {\n if (keyPath === '') {\n return obj;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1));\n }\n\n return obj[unescapeKeyPathComponent(keyPath)];\n }\n /**\n *\n * @param {PlainObject} obj\n * @param {string} keyPath\n * @param {Any} value\n * @returns {Any}\n */\n\n\n function setAtKeyPath(obj, keyPath, value) {\n if (keyPath === '') {\n return value;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return setAtKeyPath(innerObj, keyPath.slice(period + 1), value);\n }\n\n obj[unescapeKeyPathComponent(keyPath)] = value;\n return obj;\n }\n /**\n *\n * @param {external:JSON} value\n * @returns {\"null\"|\"array\"|\"undefined\"|\"boolean\"|\"number\"|\"string\"|\n * \"object\"|\"symbol\"}\n */\n\n\n function getJSONType(value) {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof(value);\n }\n\n var keys = Object.keys,\n isArray = Array.isArray,\n hasOwn$1 = {}.hasOwnProperty,\n internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric'];\n /**\n * Handle plain object revivers first so reference setting can use\n * revived type (e.g., array instead of object); assumes revived\n * has same structure or will otherwise break subsequent references.\n * @param {PlainObjectType} a\n * @param {PlainObjectType} b\n * @returns {1|-1|boolean}\n */\n\n function nestedPathsFirst(a, b) {\n if (a.keypath === '') {\n return -1;\n }\n\n var as = a.keypath.match(/\\./g) || 0;\n var bs = b.keypath.match(/\\./g) || 0;\n\n if (as) {\n as = as.length;\n }\n\n if (bs) {\n bs = bs.length;\n }\n\n return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath;\n }\n /**\n * An instance of this class can be used to call `stringify()` and `parse()`.\n * Typeson resolves cyclic references by default. Can also be extended to\n * support custom types using the register() method.\n *\n * @class\n * @param {{cyclic: boolean}} [options] - if cyclic (default true),\n * cyclic references will be handled gracefully.\n */\n\n\n var Typeson =\n /*#__PURE__*/\n function () {\n function Typeson(options) {\n _classCallCheck(this, Typeson);\n\n this.options = options; // Replacers signature: replace (value). Returns falsy if not\n // replacing. Otherwise ['Date', value.getTime()]\n\n this.plainObjectReplacers = [];\n this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}].\n // Sample: [{'Date': value => new Date(value)}, {plain: false}]\n\n this.revivers = {};\n /** Types registered via `register()`. */\n\n this.types = {};\n }\n /**\n * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON\n */\n\n /**\n * @callback JSONReplacer\n * @param {\"\"|string} key\n * @param {JSON} value\n * @returns {number|string|boolean|null|PlainObject|undefined}\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter\n */\n\n /**\n * Serialize given object to Typeson.\n * Initial arguments work identical to those of `JSON.stringify`.\n * The `replacer` argument has nothing to do with our replacers.\n * @param {Any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {object} opts\n * @returns {string|Promise} Promise resolves to a string\n */\n\n\n _createClass(Typeson, [{\n key: \"stringify\",\n value: function stringify(obj, replacer, space, opts) {\n opts = _objectSpread2({}, this.options, {}, opts, {\n stringification: true\n });\n var encapsulated = this.encapsulate(obj, null, opts);\n\n if (isArray(encapsulated)) {\n return JSON.stringify(encapsulated[0], replacer, space);\n }\n\n return encapsulated.then(function (res) {\n return JSON.stringify(res, replacer, space);\n });\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {Any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {object} opts\n * @returns {string}\n */\n\n }, {\n key: \"stringifySync\",\n value: function stringifySync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n *\n * @param {Any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {object} opts\n * @returns {Promise}\n */\n\n }, {\n key: \"stringifyAsync\",\n value: function stringifyAsync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n * Parse Typeson back into an obejct.\n * Initial arguments works identical to those of `JSON.parse()`.\n * @param {string} text\n * @param {function} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {object} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parse\",\n value: function parse(text, reviver, opts) {\n opts = _objectSpread2({}, this.options, {}, opts, {\n parse: true\n });\n return this.revive(JSON.parse(text, reviver), opts);\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {string} text\n * @param {function} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {object} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parseSync\",\n value: function parseSync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n * @param {string} text\n * @param {function} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {object} opts\n * @returns {Promise} Resolves to `external:JSON`\n */\n\n }, {\n key: \"parseAsync\",\n value: function parseAsync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n *\n * @param {Any} obj\n * @param {object} stateObj\n * @param {object} [opts={}]\n * @returns {string[]|false}\n */\n\n }, {\n key: \"specialTypeNames\",\n value: function specialTypeNames(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.returnTypeNames = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n *\n * @param {Any} obj\n * @param {PlainObject} stateObj\n * @param {PlainObject} [opts={}]\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"rootTypeName\",\n value: function rootTypeName(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.iterateNone = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n * Encapsulate a complex object into a plain Object by replacing\n * registered types with plain objects representing the types data.\n *\n * This method is used internally by `Typeson.stringify()`.\n * @param {Any} obj - Object to encapsulate.\n * @param {PlainObject} stateObj\n * @param {PlainObject} opts\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"encapsulate\",\n value: function encapsulate(obj, stateObj, opts) {\n opts = _objectSpread2({\n sync: true\n }, this.options, {}, opts);\n var _opts = opts,\n sync = _opts.sync;\n var that = this,\n types = {},\n refObjs = [],\n // For checking cyclic references\n refKeys = [],\n // For checking cyclic references\n promisesDataRoot = []; // Clone the object deeply while at the same time replacing any\n // special types or cyclic reference:\n\n var cyclic = 'cyclic' in opts ? opts.cyclic : true;\n var _opts2 = opts,\n encapsulateObserver = _opts2.encapsulateObserver;\n\n var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot);\n /**\n *\n * @param {Any} ret\n * @returns {GenericArray|PlainObject|string|false}\n */\n\n\n function finish(ret) {\n // Add `$types` to result only if we ever bumped into a\n // special type (or special case where object has own `$types`)\n var typeNames = Object.values(types);\n\n if (opts.iterateNone) {\n if (typeNames.length) {\n return typeNames[0];\n }\n\n return Typeson.getJSONType(ret);\n }\n\n if (typeNames.length) {\n if (opts.returnTypeNames) {\n return _toConsumableArray(new Set(typeNames));\n } // Special if array (or a primitive) was serialized\n // because JSON would ignore custom `$types` prop on it\n\n\n if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its\n // own `$types` property (to avoid ambiguity)\n hasOwn$1.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: {\n $: types\n }\n };\n } else {\n ret.$types = types;\n } // No special types\n\n } else if (isObject(ret) && hasOwn$1.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: true\n };\n }\n\n if (opts.returnTypeNames) {\n return false;\n }\n\n return ret;\n }\n /**\n *\n * @param {Any} ret\n * @param {GenericArray} promisesData\n * @returns {Promise}\n */\n\n\n function checkPromises(_x, _x2) {\n return _checkPromises.apply(this, arguments);\n }\n /**\n *\n * @param {object} stateObj\n * @param {object} ownKeysObj\n * @param {function} cb\n * @returns {undefined}\n */\n\n\n function _checkPromises() {\n _checkPromises = _asyncToGenerator(\n /*#__PURE__*/\n regeneratorRuntime.mark(function _callee2(ret, promisesData) {\n var promResults;\n return regeneratorRuntime.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return Promise.all(promisesData.map(function (pd) {\n return pd[1].p;\n }));\n\n case 2:\n promResults = _context2.sent;\n _context2.next = 5;\n return Promise.all(promResults.map(\n /*#__PURE__*/\n function () {\n var _ref = _asyncToGenerator(\n /*#__PURE__*/\n regeneratorRuntime.mark(function _callee(promResult) {\n var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2;\n\n return regeneratorRuntime.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n newPromisesData = [];\n _promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0];\n _prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6];\n encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType);\n isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself\n // returns a `Typeson.Promise`\n\n if (!(keyPath && isTypesonPromise)) {\n _context.next = 11;\n break;\n }\n\n _context.next = 8;\n return encaps.p;\n\n case 8:\n encaps2 = _context.sent;\n parentObj[key] = encaps2;\n return _context.abrupt(\"return\", checkPromises(ret, newPromisesData));\n\n case 11:\n if (keyPath) {\n parentObj[key] = encaps;\n } else if (isTypesonPromise) {\n ret = encaps.p;\n } else {\n // If this is itself a `Typeson.Promise` (because the\n // original value supplied was a `Promise` or\n // because the supplied custom type value resolved\n // to one), returning it below will be fine since\n // a `Promise` is expected anyways given current\n // config (and if not a `Promise`, it will be ready\n // as the resolve value)\n ret = encaps;\n }\n\n return _context.abrupt(\"return\", checkPromises(ret, newPromisesData));\n\n case 13:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee);\n }));\n\n return function (_x3) {\n return _ref.apply(this, arguments);\n };\n }()));\n\n case 5:\n return _context2.abrupt(\"return\", ret);\n\n case 6:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2);\n }));\n return _checkPromises.apply(this, arguments);\n }\n\n function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) {\n Object.assign(stateObj, ownKeysObj);\n var vals = internalStateObjPropsToIgnore.map(function (prop) {\n var tmp = stateObj[prop];\n delete stateObj[prop];\n return tmp;\n }); // eslint-disable-next-line callback-return\n\n cb();\n internalStateObjPropsToIgnore.forEach(function (prop, i) {\n stateObj[prop] = vals[i];\n });\n }\n /**\n *\n * @param {string} keypath\n * @param {Any} value\n * @param {boolean} cyclic\n * @param {PlainObject} stateObj\n * @param {boolean} promisesData\n * @param {boolean} resolvingTypesonPromise\n * @param {string} detectedType\n * @returns {Any}\n */\n\n\n function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) {\n var ret;\n var observerData = {};\n\n var $typeof = _typeof(value);\n\n var runObserver = encapsulateObserver ? function (obj) {\n var type = detectedType || stateObj.type || Typeson.getJSONType(value);\n encapsulateObserver(Object.assign(obj || observerData, {\n keypath: keypath,\n value: value,\n cyclic: cyclic,\n stateObj: stateObj,\n promisesData: promisesData,\n resolvingTypesonPromise: resolvingTypesonPromise,\n awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise)\n }, {\n type: type\n }));\n } : null;\n\n if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) {\n if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) {\n if (stateObj.replaced) {\n ret = value;\n } else {\n ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver);\n }\n\n if (ret !== value) {\n observerData = {\n replaced: ret\n };\n }\n } else {\n ret = value;\n }\n\n if (runObserver) {\n runObserver();\n }\n\n return ret;\n }\n\n if (value === null) {\n if (runObserver) {\n runObserver();\n }\n\n return value;\n }\n\n if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') {\n // Options set to detect cyclic references and be able\n // to rewrite them.\n var refIndex = refObjs.indexOf(value);\n\n if (refIndex < 0) {\n if (cyclic === true) {\n refObjs.push(value);\n refKeys.push(keypath);\n }\n } else {\n types[keypath] = '#';\n\n if (runObserver) {\n runObserver({\n cyclicKeypath: refKeys[refIndex]\n });\n }\n\n return '#' + refKeys[refIndex];\n }\n }\n\n var isPlainObj = isPlainObject(value);\n var isArr = isArray(value);\n var replaced = // Running replace will cause infinite loop as will test\n // positive again\n (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object\n // replacers, don't try finding a replacer\n value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver);\n var clone;\n\n if (replaced !== value) {\n ret = replaced;\n observerData = {\n replaced: replaced\n };\n } else {\n // eslint-disable-next-line no-lonely-if\n if (keypath === '' && hasConstructorOf(value, TypesonPromise)) {\n promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]);\n ret = value;\n } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') {\n clone = new Array(value.length);\n observerData = {\n clone: clone\n };\n } else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') {\n clone = {};\n\n if (stateObj.addLength) {\n clone.length = value.length;\n }\n\n observerData = {\n clone: clone\n };\n } else {\n ret = value; // Only clone vanilla objects and arrays\n }\n }\n\n if (runObserver) {\n runObserver();\n }\n\n if (opts.iterateNone) {\n return clone || ret;\n }\n\n if (!clone) {\n return ret;\n } // Iterate object or array\n\n\n if (stateObj.iterateIn) {\n var _loop = function _loop(key) {\n var ownKeysObj = {\n ownKeys: hasOwn$1.call(value, key)\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n };\n\n // eslint-disable-next-line guard-for-in\n for (var key in value) {\n _loop(key);\n }\n\n if (runObserver) {\n runObserver({\n endIterateIn: true,\n end: true\n });\n }\n } else {\n // Note: Non-indexes on arrays won't survive stringify so\n // somewhat wasteful for arrays, but so too is iterating\n // all numeric indexes on sparse arrays when not wanted\n // or filtering own keys for positive integers\n keys(value).forEach(function (key) {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n var ownKeysObj = {\n ownKeys: true\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n });\n\n if (runObserver) {\n runObserver({\n endIterateOwn: true,\n end: true\n });\n }\n } // Iterate array for non-own numeric properties (we can't\n // replace the prior loop though as it iterates non-integer\n // keys)\n\n\n if (stateObj.iterateUnsetNumeric) {\n var vl = value.length;\n\n var _loop2 = function _loop2(i) {\n if (!(i in value)) {\n // No need to escape numeric\n var kp = keypath + (keypath ? '.' : '') + i;\n var ownKeysObj = {\n ownKeys: false\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]);\n } else if (val !== undefined) {\n clone[i] = val;\n }\n });\n }\n };\n\n for (var i = 0; i < vl; i++) {\n _loop2(i);\n }\n\n if (runObserver) {\n runObserver({\n endIterateUnsetNumeric: true,\n end: true\n });\n }\n }\n\n return clone;\n }\n /**\n *\n * @param {string} keypath\n * @param {Any} value\n * @param {PlainObject} stateObj\n * @param {GenericArray} promisesData\n * @param {boolean} plainObject\n * @param {boolean} resolvingTypesonPromise\n * @param {function} [runObserver]\n * @returns {*}\n */\n\n\n function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) {\n // Encapsulate registered types\n var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers;\n var i = replacers.length;\n\n while (i--) {\n var replacer = replacers[i];\n\n if (replacer.test(value, stateObj)) {\n var type = replacer.type;\n\n if (that.revivers[type]) {\n // Record the type only if a corresponding reviver\n // exists. This is to support specs where only\n // replacement is done.\n // For example, ensuring deep cloning of the object,\n // or replacing a type to its equivalent without\n // the need to revive it.\n var existing = types[keypath]; // type can comprise an array of types (see test\n // \"should support intermediate types\")\n\n types[keypath] = existing ? [type].concat(existing) : type;\n }\n\n Object.assign(stateObj, {\n type: type,\n replaced: true\n });\n\n if ((sync || !replacer.replaceAsync) && !replacer.replace) {\n if (runObserver) {\n runObserver({\n typeDetected: true\n });\n }\n\n return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n\n if (runObserver) {\n runObserver({\n replacing: true\n });\n } // Now, also traverse the result in case it contains its\n // own types to replace\n\n\n var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync';\n return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n }\n\n return value;\n }\n\n return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() // If this is a synchronous request for stringification, yet\n // a promise is the result, we don't want to resolve leading\n // to an async result, so we return an array to avoid\n // ambiguity\n : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {*} obj\n * @param {object} stateObj\n * @param {object} opts\n * @returns {*}\n */\n\n }, {\n key: \"encapsulateSync\",\n value: function encapsulateSync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n * @param {*} obj\n * @param {object} stateObj\n * @param {object} opts\n * @returns {*}\n */\n\n }, {\n key: \"encapsulateAsync\",\n value: function encapsulateAsync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n * Revive an encapsulated object.\n * This method is used internally by `Typeson.parse()`.\n * @param {object} obj - Object to revive. If it has `$types` member, the\n * properties that are listed there will be replaced with its true type\n * instead of just plain objects.\n * @param {object} opts\n * @throws TypeError If mismatch between sync/async type and result\n * @returns {Promise|*} If async, returns a Promise that resolves to `*`\n */\n\n }, {\n key: \"revive\",\n value: function revive(obj, opts) {\n var types = obj && obj.$types; // No type info added. Revival not needed.\n\n if (!types) {\n return obj;\n } // Object happened to have own `$types` property but with\n // no actual types, so we unescape and return that object\n\n\n if (types === true) {\n return obj.$;\n }\n\n opts = _objectSpread2({\n sync: true\n }, this.options, {}, opts);\n var _opts3 = opts,\n sync = _opts3.sync;\n var keyPathResolutions = [];\n var stateObj = {};\n var ignore$Types = true; // Special when root object is not a trivial Object, it will\n // be encapsulated in `$`. It will also be encapsulated in\n // `$` if it has its own `$` property to avoid ambiguity\n\n if (types.$ && isPlainObject(types.$)) {\n obj = obj.$;\n types = types.$;\n ignore$Types = false;\n }\n\n var that = this;\n /**\n * @callback RevivalReducer\n * @param {Any} value\n * @param {string} type\n * @returns {Any}\n */\n\n /**\n *\n * @param {string} type\n * @param {Any} val\n * @returns {[type]} [description]\n */\n\n function executeReviver(type, val) {\n var _ref2 = that.revivers[type] || [],\n _ref3 = _slicedToArray(_ref2, 1),\n reviver = _ref3[0];\n\n if (!reviver) {\n throw new Error('Unregistered type: ' + type);\n } // Only `sync` expected here, as problematic async would\n // be missing both `reviver` and `reviverAsync`, and\n // encapsulation shouldn't have added types, so\n // should have made an early exit\n\n\n if (sync && !('revive' in reviver)) {\n // Just return value as is\n return val;\n }\n\n return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj);\n }\n /**\n *\n * @returns {void|TypesonPromise}\n */\n\n\n function revivePlainObjects() {\n // const references = [];\n // const reviveTypes = [];\n var plainObjectTypes = [];\n Object.entries(types).forEach(function (_ref4) {\n var _ref5 = _slicedToArray(_ref4, 2),\n keypath = _ref5[0],\n type = _ref5[1];\n\n if (type === '#') {\n /*\n references.push({\n keypath,\n reference: getByKeyPath(obj, keypath)\n });\n */\n return;\n }\n\n [].concat(type).forEach(function (type) {\n var _ref6 = that.revivers[type] || [null, {}],\n _ref7 = _slicedToArray(_ref6, 2),\n plain = _ref7[1].plain;\n\n if (!plain) {\n // reviveTypes.push({keypath, type});\n return;\n }\n\n plainObjectTypes.push({\n keypath: keypath,\n type: type\n });\n delete types[keypath]; // Avoid repeating\n });\n });\n\n if (!plainObjectTypes.length) {\n return undefined;\n } // console.log(plainObjectTypes.sort(nestedPathsFirst));\n\n /**\n * @typedef {PlainObject} PlainObjectType\n * @property {string} keypath\n * @property {string} type\n */\n\n\n return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) {\n var keypath = _ref8.keypath,\n type = _ref8.type;\n\n if (isThenable(possibleTypesonPromise)) {\n return possibleTypesonPromise.then(function (val) {\n return reducer(val, {\n keypath: keypath,\n type: type\n });\n });\n } // console.log('obj', JSON.stringify(keypath), obj);\n\n\n var val = getByKeyPath(obj, keypath);\n val = executeReviver(type, val);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n var newVal = setAtKeyPath(obj, keypath, v);\n\n if (newVal === v) {\n obj = newVal;\n }\n\n return undefined;\n });\n }\n\n var newVal = setAtKeyPath(obj, keypath, val);\n\n if (newVal === val) {\n obj = newVal;\n }\n\n return undefined;\n }, undefined // This argument must be explicit\n ); // references.forEach(({keypath, reference}) => {});\n // reviveTypes.sort(nestedPathsFirst).forEach(() => {});\n }\n\n var revivalPromises = [];\n /**\n *\n * @param {string} keypath\n * @param {Any} value\n * @param {?(Array|object)} target\n * @param {Array|object} [clone]\n * @param {string} [key]\n * @returns {Any}\n */\n\n function _revive(keypath, value, target, clone, key) {\n if (ignore$Types && keypath === '$types') {\n return undefined;\n }\n\n var type = types[keypath];\n var isArr = isArray(value);\n\n if (isArr || isPlainObject(value)) {\n var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array\n\n\n keys(value).forEach(function (k) {\n var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k);\n\n var set = function set(v) {\n if (hasConstructorOf(v, Undefined)) {\n _clone[k] = undefined;\n } else if (v !== undefined) {\n _clone[k] = v;\n }\n\n return v;\n };\n\n if (hasConstructorOf(val, TypesonPromise)) {\n revivalPromises.push(val.then(function (ret) {\n return set(ret);\n }));\n } else {\n set(val);\n }\n });\n value = _clone; // Try to resolve cyclic reference as soon as available\n\n while (keyPathResolutions.length) {\n var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4),\n _target = _keyPathResolutions$[0],\n keyPath = _keyPathResolutions$[1],\n _clone2 = _keyPathResolutions$[2],\n k = _keyPathResolutions$[3];\n\n var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or\n // `undefined`\n\n if (val !== undefined) {\n _clone2[k] = val;\n } else {\n break;\n }\n\n keyPathResolutions.splice(0, 1);\n }\n }\n\n if (!type) {\n return value;\n }\n\n if (type === '#') {\n var _ret = getByKeyPath(target, value.slice(1));\n\n if (_ret === undefined) {\n // Cyclic reference not yet available\n keyPathResolutions.push([target, value.slice(1), clone, key]);\n }\n\n return _ret;\n } // `type` can be an array here\n\n\n return [].concat(type).reduce(function reducer(val, typ) {\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n // TypesonPromise here too\n return reducer(v, typ);\n });\n }\n\n return executeReviver(typ, val);\n }, value);\n }\n /**\n *\n * @param {Any} retrn\n * @returns {undefined|Any}\n */\n\n\n function checkUndefined(retrn) {\n return hasConstructorOf(retrn, Undefined) ? undefined : retrn;\n }\n\n var possibleTypesonPromise = revivePlainObjects();\n var ret;\n\n if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) {\n ret = possibleTypesonPromise.then(function () {\n return obj;\n });\n } else {\n ret = _revive('', obj, null);\n\n if (revivalPromises.length) {\n // Ensure children resolved\n ret = TypesonPromise.resolve(ret).then(function (r) {\n return TypesonPromise.all([// May be a TypesonPromise or not\n r].concat(revivalPromises));\n }).then(function (_ref9) {\n var _ref10 = _slicedToArray(_ref9, 1),\n r = _ref10[0];\n\n return r;\n });\n }\n }\n\n return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {Any} obj\n * @param {object} opts\n * @returns {Any}\n */\n\n }, {\n key: \"reviveSync\",\n value: function reviveSync(obj, opts) {\n return this.revive(obj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n * @param {Any} obj\n * @param {object} opts\n * @returns {Promise} Resolves to `*`\n */\n\n }, {\n key: \"reviveAsync\",\n value: function reviveAsync(obj, opts) {\n return this.revive(obj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n * Register types.\n * For examples on how to use this method, see\n * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}.\n * @param {object.[]} typeSpecSets - Types and\n * their functions [test, encapsulate, revive];\n * @param {object} opts\n * @returns {Typeson}\n */\n\n }, {\n key: \"register\",\n value: function register(typeSpecSets, opts) {\n opts = opts || {};\n [].concat(typeSpecSets).forEach(function R(typeSpec) {\n var _this = this;\n\n // Allow arrays of arrays of arrays...\n if (isArray(typeSpec)) {\n return typeSpec.map(function (typSpec) {\n return R.call(_this, typSpec);\n });\n }\n\n typeSpec && keys(typeSpec).forEach(function (typeId) {\n if (typeId === '#') {\n throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects');\n } else if (Typeson.JSON_TYPES.includes(typeId)) {\n throw new TypeError('Plain JSON object types are reserved as type names');\n }\n\n var spec = typeSpec[typeId];\n var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers;\n var existingReplacer = replacers.filter(function (r) {\n return r.type === typeId;\n });\n\n if (existingReplacer.length) {\n // Remove existing spec and replace with this one.\n replacers.splice(replacers.indexOf(existingReplacer[0]), 1);\n delete this.revivers[typeId];\n delete this.types[typeId];\n }\n\n if (typeof spec === 'function') {\n // Support registering just a class without replacer/reviver\n var Class = spec;\n spec = {\n test: function test(x) {\n return x && x.constructor === Class;\n },\n replace: function replace(x) {\n return _objectSpread2({}, x);\n },\n revive: function revive(x) {\n return Object.assign(Object.create(Class.prototype), x);\n }\n };\n } else if (isArray(spec)) {\n var _spec = spec,\n _spec2 = _slicedToArray(_spec, 3),\n test = _spec2[0],\n replace = _spec2[1],\n revive = _spec2[2];\n\n spec = {\n test: test,\n replace: replace,\n revive: revive\n };\n }\n\n if (!spec || !spec.test) {\n return;\n }\n\n var replacerObj = {\n type: typeId,\n test: spec.test.bind(spec)\n };\n\n if (spec.replace) {\n replacerObj.replace = spec.replace.bind(spec);\n }\n\n if (spec.replaceAsync) {\n replacerObj.replaceAsync = spec.replaceAsync.bind(spec);\n }\n\n var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Infinity;\n\n if (spec.testPlainObjects) {\n this.plainObjectReplacers.splice(start, 0, replacerObj);\n } else {\n this.nonplainObjectReplacers.splice(start, 0, replacerObj);\n } // Todo: We might consider a testAsync type\n\n\n if (spec.revive || spec.reviveAsync) {\n var reviverObj = {};\n\n if (spec.revive) {\n reviverObj.revive = spec.revive.bind(spec);\n }\n\n if (spec.reviveAsync) {\n reviverObj.reviveAsync = spec.reviveAsync.bind(spec);\n }\n\n this.revivers[typeId] = [reviverObj, {\n plain: spec.testPlainObjects\n }];\n } // Record to be retrieved via public types property.\n\n\n this.types[typeId] = spec;\n }, this);\n }, this);\n return this;\n }\n }]);\n\n return Typeson;\n }();\n /**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * @class\n */\n\n\n var Undefined = function Undefined() {\n _classCallCheck(this, Undefined);\n }; // eslint-disable-line space-before-blocks\n\n\n Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values\n // To insist `undefined` should be added\n\n Typeson.Undefined = Undefined; // To support async encapsulation/stringification\n\n Typeson.Promise = TypesonPromise; // Some fundamental type-checking utilities\n\n Typeson.isThenable = isThenable;\n Typeson.toStringTag = toStringTag;\n Typeson.hasConstructorOf = hasConstructorOf;\n Typeson.isObject = isObject;\n Typeson.isPlainObject = isPlainObject;\n Typeson.isUserObject = isUserObject;\n Typeson.escapeKeyPathComponent = escapeKeyPathComponent;\n Typeson.unescapeKeyPathComponent = unescapeKeyPathComponent;\n Typeson.getByKeyPath = getByKeyPath;\n Typeson.getJSONType = getJSONType;\n Typeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object'];\n\n return Typeson;\n\n})));\n","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n}\n\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\n\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\n/**\n* @callback TypesonFulfilled\n* @returns {Promise|any}\n*/\n\n/**\n* @callback TypesonRejected\n* @returns {Promise|any}\n*/\n\n/**\n * @callback TypesonResolve\n * @param {any} value\n * @returns {Promise}\n */\n\n/**\n * @callback TypesonReject\n * @param {Error|any} error\n * @returns {Promise}\n */\n\n/**\n * @callback TypesonResolveReject\n * @param {TypesonResolve} typesonResolve\n * @param {TypesonReject} typesonReject\n * @returns {Promise}\n */\n\n/* eslint-disable block-spacing, space-before-function-paren,\n space-before-blocks, space-infix-ops, semi, promise/avoid-new,\n jsdoc/require-jsdoc */\n\n/**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * With ES6 classes, we may be able to simply use `class TypesonPromise\n * extends Promise` and add a string tag for detection.\n * @param {TypesonResolveReject} f\n */\nvar TypesonPromise = function TypesonPromise(f) {\n _classCallCheck(this, TypesonPromise);\n\n this.p = new Promise(f);\n};\n/* eslint-enable block-spacing, space-before-function-paren,\n space-before-blocks, space-infix-ops, semi, promise/avoid-new,\n jsdoc/require-jsdoc */\n// eslint-disable-next-line max-len\n// class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi\n\n\nTypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill\n\n/* istanbul ignore else */\n\nif (typeof Symbol !== 'undefined') {\n // Ensure `isUserObject` will return `false` for `TypesonPromise`\n TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise';\n}\n/**\n *\n * @param {TypesonFulfilled} [onFulfilled]\n * @param {TypesonRejected} [onRejected]\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.prototype.then = function (onFulfilled, onRejected) {\n var _this = this;\n\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n _this.p.then(function (res) {\n // eslint-disable-next-line promise/always-return\n typesonResolve(onFulfilled ? onFulfilled(res) : res);\n })[\"catch\"](function (res) {\n return onRejected ? onRejected(res) : Promise.reject(res);\n }).then(typesonResolve, typesonReject);\n });\n};\n/**\n *\n * @param {TypesonRejected} onRejected\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\n/**\n *\n * @param {any} v\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.resolve = function (v) {\n return new TypesonPromise(function (typesonResolve) {\n typesonResolve(v);\n });\n};\n/**\n *\n * @param {any} v\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.reject = function (v) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n typesonReject(v);\n });\n};\n\n['all', 'race'].forEach(function (meth) {\n /**\n *\n * @param {Promise[]} promArr\n * @returns {TypesonPromise}\n */\n TypesonPromise[meth] = function (promArr) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n Promise[meth](promArr.map(function (prom) {\n return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom;\n })).then(typesonResolve, typesonReject);\n });\n };\n});\n\nvar _ref = {},\n toStr = _ref.toString,\n hasOwn$1 = {}.hasOwnProperty,\n getProto = Object.getPrototypeOf,\n fnToString = hasOwn$1.toString;\n/**\n * Second argument not in use internally, but provided for utility.\n * @param {any} v\n * @param {boolean} catchCheck\n * @returns {boolean}\n */\n\nfunction isThenable(v, catchCheck) {\n return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v[\"catch\"] === 'function');\n}\n/**\n *\n * @param {any} val\n * @returns {string}\n */\n\n\nfunction toStringTag(val) {\n return toStr.call(val).slice(8, -1);\n}\n/**\n * This function is dependent on both constructors\n * being identical so any minimization is expected of both.\n * @param {any} a\n * @param {GenericFunction} b\n * @returns {boolean}\n */\n\n\nfunction hasConstructorOf(a, b) {\n if (!a || _typeof(a) !== 'object') {\n return false;\n }\n\n var proto = getProto(a);\n\n if (!proto) {\n return b === null;\n }\n\n var Ctor = hasOwn$1.call(proto, 'constructor') && proto.constructor;\n\n if (typeof Ctor !== 'function') {\n return b === null;\n }\n\n if (b === Ctor) {\n return true;\n }\n\n if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) {\n return true;\n }\n\n if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) {\n return true;\n }\n\n return false;\n}\n/**\n *\n * @param {any} val\n * @returns {boolean}\n */\n\n\nfunction isPlainObject(val) {\n // Mirrors jQuery's\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object);\n}\n/**\n *\n * @param {any} val\n * @returns {boolean}\n */\n\n\nfunction isUserObject(val) {\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object) || isUserObject(proto);\n}\n/**\n *\n * @param {any} v\n * @returns {boolean}\n */\n\n\nfunction isObject(v) {\n return v && _typeof(v) === 'object';\n}\n/**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\nfunction escapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~/g, '~0').replace(/\\./g, '~1');\n}\n/**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\nfunction unescapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~');\n}\n/**\n * @param {PlainObject|GenericArray} obj\n * @param {string} keyPath\n * @returns {any}\n */\n\n\nfunction getByKeyPath(obj, keyPath) {\n if (keyPath === '') {\n return obj;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1));\n }\n\n return obj[unescapeKeyPathComponent(keyPath)];\n}\n/**\n *\n * @param {PlainObject} obj\n * @param {string} keyPath\n * @param {any} value\n * @returns {any}\n */\n\n\nfunction setAtKeyPath(obj, keyPath, value) {\n if (keyPath === '') {\n return value;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return setAtKeyPath(innerObj, keyPath.slice(period + 1), value);\n }\n\n obj[unescapeKeyPathComponent(keyPath)] = value;\n return obj;\n}\n/**\n *\n * @param {external:JSON} value\n * @returns {\"null\"|\"array\"|\"undefined\"|\"boolean\"|\"number\"|\"string\"|\n * \"object\"|\"symbol\"}\n */\n\n\nfunction getJSONType(value) {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof(value);\n}\n\nfunction _await(value, then, direct) {\n if (direct) {\n return then ? then(value) : value;\n }\n\n if (!value || !value.then) {\n value = Promise.resolve(value);\n }\n\n return then ? value.then(then) : value;\n}\n\nvar keys = Object.keys,\n isArray = Array.isArray,\n hasOwn = {}.hasOwnProperty,\n internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric'];\n/**\n * Handle plain object revivers first so reference setting can use\n * revived type (e.g., array instead of object); assumes revived\n * has same structure or will otherwise break subsequent references.\n * @param {PlainObjectType} a\n * @param {PlainObjectType} b\n * @returns {1|-1|boolean}\n */\n\nfunction _async(f) {\n return function () {\n for (var args = [], i = 0; i < arguments.length; i++) {\n args[i] = arguments[i];\n }\n\n try {\n return Promise.resolve(f.apply(this, args));\n } catch (e) {\n return Promise.reject(e);\n }\n };\n}\n/**\n * @callback Tester\n * @param {any} value\n * @param {StateObject} stateobj\n * @returns {boolean}\n */\n\n/**\n* @callback Replacer\n* @param {any} value\n* @param {StateObject} stateObj\n* @returns {any} Should be JSON-stringifiable\n*/\n\n/**\n* @callback Reviver\n* @param {JSON} value\n* @param {StateObject} stateObj\n* @returns {any}\n*/\n\n/**\n* @typedef {PlainObject} TypesonOptions\n* @property {boolean} stringification Auto-set by `stringify`\n*/\n\n/**\n * An instance of this class can be used to call `stringify()` and `parse()`.\n * Typeson resolves cyclic references by default. Can also be extended to\n * support custom types using the register() method.\n *\n * @class\n * @param {{cyclic: boolean}} [options] - if cyclic (default true),\n * cyclic references will be handled gracefully.\n */\n\n\nfunction _invoke(body, then) {\n var result = body();\n\n if (result && result.then) {\n return result.then(then);\n }\n\n return then(result);\n}\n\nfunction nestedPathsFirst(a, b) {\n if (a.keypath === '') {\n return -1;\n }\n\n var as = a.keypath.match(/\\./g) || 0;\n var bs = b.keypath.match(/\\./g) || 0;\n\n if (as) {\n as = as.length;\n }\n\n if (bs) {\n bs = bs.length;\n }\n\n return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath;\n}\n\nvar Typeson = /*#__PURE__*/function () {\n /**\n * @param {TypesonOptions} options\n */\n function Typeson(options) {\n _classCallCheck(this, Typeson);\n\n this.options = options; // Replacers signature: replace (value). Returns falsy if not\n // replacing. Otherwise ['Date', value.getTime()]\n\n this.plainObjectReplacers = [];\n this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}].\n // Sample: [{'Date': value => new Date(value)}, {plain: false}]\n\n this.revivers = {};\n /** Types registered via `register()`. */\n\n this.types = {};\n }\n /**\n * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON\n */\n\n /**\n * @callback JSONReplacer\n * @param {\"\"|string} key\n * @param {JSON} value\n * @returns {number|string|boolean|null|PlainObject|undefined}\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter\n */\n\n /**\n * Serialize given object to Typeson.\n * Initial arguments work identical to those of `JSON.stringify`.\n * The `replacer` argument has nothing to do with our replacers.\n * @param {any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {TypesonOptions} opts\n * @returns {string|Promise} Promise resolves to a string\n */\n\n\n _createClass(Typeson, [{\n key: \"stringify\",\n value: function stringify(obj, replacer, space, opts) {\n opts = _objectSpread2(_objectSpread2(_objectSpread2({}, this.options), opts), {}, {\n stringification: true\n });\n var encapsulated = this.encapsulate(obj, null, opts);\n\n if (isArray(encapsulated)) {\n return JSON.stringify(encapsulated[0], replacer, space);\n }\n\n return encapsulated.then(function (res) {\n return JSON.stringify(res, replacer, space);\n });\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {TypesonOptions} opts\n * @returns {string}\n */\n\n }, {\n key: \"stringifySync\",\n value: function stringifySync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n *\n * @param {any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {TypesonOptions} opts\n * @returns {Promise}\n */\n\n }, {\n key: \"stringifyAsync\",\n value: function stringifyAsync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * @callback JSONReviver\n * @param {string} key\n * @param {JSON} value\n * @returns {JSON}\n */\n\n /**\n * Parse Typeson back into an obejct.\n * Initial arguments works identical to those of `JSON.parse()`.\n * @param {string} text\n * @param {JSONReviver} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {TypesonOptions} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parse\",\n value: function parse(text, reviver, opts) {\n opts = _objectSpread2(_objectSpread2(_objectSpread2({}, this.options), opts), {}, {\n parse: true\n });\n return this.revive(JSON.parse(text, reviver), opts);\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {string} text\n * @param {JSONReviver} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {TypesonOptions} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parseSync\",\n value: function parseSync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n * @param {string} text\n * @param {JSONReviver} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {TypesonOptions} opts\n * @returns {Promise} Resolves to `external:JSON`\n */\n\n }, {\n key: \"parseAsync\",\n value: function parseAsync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * @typedef {} StateObject\n */\n\n /**\n *\n * @param {any} obj\n * @param {StateObject} stateObj\n * @param {TypesonOptions} [opts={}]\n * @returns {string[]|false}\n */\n\n }, {\n key: \"specialTypeNames\",\n value: function specialTypeNames(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.returnTypeNames = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n *\n * @param {any} obj\n * @param {PlainObject} stateObj\n * @param {PlainObject} [opts={}]\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"rootTypeName\",\n value: function rootTypeName(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.iterateNone = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n * Encapsulate a complex object into a plain Object by replacing\n * registered types with plain objects representing the types data.\n *\n * This method is used internally by `Typeson.stringify()`.\n * @param {any} obj - Object to encapsulate.\n * @param {PlainObject} stateObj\n * @param {PlainObject} opts\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"encapsulate\",\n value: function encapsulate(obj, stateObj, opts) {\n /**\n *\n * @param {any} ret\n * @param {GenericArray} promisesData\n * @returns {Promise}\n */\n var checkPromises = _async(function (ret, promisesData) {\n return _await(Promise.all(promisesData.map(function (pd) {\n return pd[1].p;\n })), function (promResults) {\n return _await(Promise.all(promResults.map(_async(function (promResult) {\n var _exit = false;\n var newPromisesData = [];\n\n var _promisesData$splice = promisesData.splice(0, 1),\n _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1),\n prData = _promisesData$splice2[0];\n\n var _prData = _slicedToArray(prData, 7),\n keyPath = _prData[0],\n cyclic = _prData[2],\n stateObj = _prData[3],\n parentObj = _prData[4],\n key = _prData[5],\n detectedType = _prData[6];\n\n var encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType);\n\n var isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself\n // returns a `Typeson.Promise`\n\n return _invoke(function () {\n if (keyPath && isTypesonPromise) {\n return _await(encaps.p, function (encaps2) {\n parentObj[key] = encaps2;\n _exit = true;\n return checkPromises(ret, newPromisesData);\n });\n }\n }, function (_result) {\n if (_exit) return _result;\n\n if (keyPath) {\n parentObj[key] = encaps;\n } else if (isTypesonPromise) {\n ret = encaps.p;\n } else {\n // If this is itself a `Typeson.Promise` (because the\n // original value supplied was a `Promise` or\n // because the supplied custom type value resolved\n // to one), returning it below will be fine since\n // a `Promise` is expected anyways given current\n // config (and if not a `Promise`, it will be ready\n // as the resolve value)\n ret = encaps;\n }\n\n return checkPromises(ret, newPromisesData);\n });\n }))), function () {\n return ret;\n });\n });\n });\n /**\n * @typedef {PlainObject} OwnKeysObject\n * @property {boolean} ownKeys\n */\n\n /**\n * @callback BuiltinStateObjectPropertiesCallback\n * @returns {void}\n */\n\n /**\n *\n * @param {StateObject} stateObj\n * @param {OwnKeysObject} ownKeysObj\n * @param {BuiltinStateObjectPropertiesCallback} cb\n * @returns {undefined}\n */\n\n\n opts = _objectSpread2(_objectSpread2({\n sync: true\n }, this.options), opts);\n var _opts = opts,\n sync = _opts.sync;\n var that = this,\n types = {},\n refObjs = [],\n // For checking cyclic references\n refKeys = [],\n // For checking cyclic references\n promisesDataRoot = []; // Clone the object deeply while at the same time replacing any\n // special types or cyclic reference:\n\n var cyclic = 'cyclic' in opts ? opts.cyclic : true;\n var _opts2 = opts,\n encapsulateObserver = _opts2.encapsulateObserver;\n\n var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot);\n /**\n *\n * @param {any} ret\n * @returns {GenericArray|PlainObject|string|false}\n */\n\n\n function finish(ret) {\n // Add `$types` to result only if we ever bumped into a\n // special type (or special case where object has own `$types`)\n var typeNames = Object.values(types);\n\n if (opts.iterateNone) {\n if (typeNames.length) {\n return typeNames[0];\n }\n\n return Typeson.getJSONType(ret);\n }\n\n if (typeNames.length) {\n if (opts.returnTypeNames) {\n return _toConsumableArray(new Set(typeNames));\n } // Special if array (or a primitive) was serialized\n // because JSON would ignore custom `$types` prop on it\n\n\n if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its\n // own `$types` property (to avoid ambiguity)\n hasOwn.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: {\n $: types\n }\n };\n } else {\n ret.$types = types;\n } // No special types\n\n } else if (isObject(ret) && hasOwn.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: true\n };\n }\n\n if (opts.returnTypeNames) {\n return false;\n }\n\n return ret;\n }\n\n function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) {\n Object.assign(stateObj, ownKeysObj);\n var vals = internalStateObjPropsToIgnore.map(function (prop) {\n var tmp = stateObj[prop];\n delete stateObj[prop];\n return tmp;\n }); // eslint-disable-next-line node/callback-return\n\n cb();\n internalStateObjPropsToIgnore.forEach(function (prop, i) {\n stateObj[prop] = vals[i];\n });\n }\n /**\n *\n * @param {string} keypath\n * @param {any} value\n * @param {boolean} cyclic\n * @param {PlainObject} stateObj\n * @param {boolean} promisesData\n * @param {boolean} resolvingTypesonPromise\n * @param {string} detectedType\n * @returns {any}\n */\n\n\n function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) {\n var ret;\n var observerData = {};\n\n var $typeof = _typeof(value);\n\n var runObserver = encapsulateObserver ? function (obj) {\n var type = detectedType || stateObj.type || Typeson.getJSONType(value);\n encapsulateObserver(Object.assign(obj || observerData, {\n keypath: keypath,\n value: value,\n cyclic: cyclic,\n stateObj: stateObj,\n promisesData: promisesData,\n resolvingTypesonPromise: resolvingTypesonPromise,\n awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise)\n }, {\n type: type\n }));\n } : null;\n\n if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) {\n if (value === undefined || Number.isNaN(value) || value === Number.NEGATIVE_INFINITY || value === Number.POSITIVE_INFINITY) {\n ret = stateObj.replaced ? value : replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver);\n\n if (ret !== value) {\n observerData = {\n replaced: ret\n };\n }\n } else {\n ret = value;\n }\n\n if (runObserver) {\n runObserver();\n }\n\n return ret;\n }\n\n if (value === null) {\n if (runObserver) {\n runObserver();\n }\n\n return value;\n }\n\n if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') {\n // Options set to detect cyclic references and be able\n // to rewrite them.\n var refIndex = refObjs.indexOf(value);\n\n if (refIndex < 0) {\n if (cyclic === true) {\n refObjs.push(value);\n refKeys.push(keypath);\n }\n } else {\n types[keypath] = '#';\n\n if (runObserver) {\n runObserver({\n cyclicKeypath: refKeys[refIndex]\n });\n }\n\n return '#' + refKeys[refIndex];\n }\n }\n\n var isPlainObj = isPlainObject(value);\n var isArr = isArray(value);\n var replaced = // Running replace will cause infinite loop as will test\n // positive again\n (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object\n // replacers, don't try finding a replacer\n value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver);\n var clone;\n\n if (replaced !== value) {\n ret = replaced;\n observerData = {\n replaced: replaced\n };\n } else {\n // eslint-disable-next-line no-lonely-if\n if (keypath === '' && hasConstructorOf(value, TypesonPromise)) {\n promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]);\n ret = value;\n } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') {\n // eslint-disable-next-line unicorn/no-new-array -- Sparse\n clone = new Array(value.length);\n observerData = {\n clone: clone\n };\n } else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') {\n clone = {};\n\n if (stateObj.addLength) {\n clone.length = value.length;\n }\n\n observerData = {\n clone: clone\n };\n } else {\n ret = value; // Only clone vanilla objects and arrays\n }\n }\n\n if (runObserver) {\n runObserver();\n }\n\n if (opts.iterateNone) {\n return clone || ret;\n }\n\n if (!clone) {\n return ret;\n } // Iterate object or array\n\n\n if (stateObj.iterateIn) {\n var _loop = function _loop(key) {\n var ownKeysObj = {\n ownKeys: hasOwn.call(value, key)\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n };\n\n // eslint-disable-next-line guard-for-in\n for (var key in value) {\n _loop(key);\n }\n\n if (runObserver) {\n runObserver({\n endIterateIn: true,\n end: true\n });\n }\n } else {\n // Note: Non-indexes on arrays won't survive stringify so\n // somewhat wasteful for arrays, but so too is iterating\n // all numeric indexes on sparse arrays when not wanted\n // or filtering own keys for positive integers\n keys(value).forEach(function (key) {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n var ownKeysObj = {\n ownKeys: true\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n });\n\n if (runObserver) {\n runObserver({\n endIterateOwn: true,\n end: true\n });\n }\n } // Iterate array for non-own numeric properties (we can't\n // replace the prior loop though as it iterates non-integer\n // keys)\n\n\n if (stateObj.iterateUnsetNumeric) {\n var vl = value.length;\n\n var _loop2 = function _loop2(i) {\n if (!(i in value)) {\n // No need to escape numeric\n var kp = keypath + (keypath ? '.' : '') + i;\n var ownKeysObj = {\n ownKeys: false\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]);\n } else if (val !== undefined) {\n clone[i] = val;\n }\n });\n }\n };\n\n for (var i = 0; i < vl; i++) {\n _loop2(i);\n }\n\n if (runObserver) {\n runObserver({\n endIterateUnsetNumeric: true,\n end: true\n });\n }\n }\n\n return clone;\n }\n /**\n * @typedef {PlainObject} KeyPathEvent\n * @property {string} cyclicKeypath\n */\n\n /**\n * @typedef {PlainObject} EndIterateInEvent\n * @property {boolean} endIterateIn\n * @property {boolean} end\n */\n\n /**\n * @typedef {PlainObject} EndIterateUnsetNumericEvent\n * @property {boolean} endIterateUnsetNumeric\n * @property {boolean} end\n */\n\n /**\n * @typedef {PlainObject} TypeDetectedEvent\n * @property {boolean} typeDetected\n */\n\n /**\n * @typedef {PlainObject} ReplacingEvent\n * @property {boolean} replacing\n */\n\n /**\n * @callback Observer\n * @param {KeyPathEvent|EndIterateInEvent|EndIterateUnsetNumericEvent|\n * TypeDetectedEvent|ReplacingEvent} [event]\n * @returns {void}\n */\n\n /**\n *\n * @param {string} keypath\n * @param {any} value\n * @param {PlainObject} stateObj\n * @param {GenericArray} promisesData\n * @param {boolean} plainObject\n * @param {boolean} resolvingTypesonPromise\n * @param {Observer} [runObserver]\n * @returns {any}\n */\n\n\n function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) {\n // Encapsulate registered types\n var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers;\n var i = replacers.length;\n\n while (i--) {\n var replacer = replacers[i];\n\n if (replacer.test(value, stateObj)) {\n var type = replacer.type;\n\n if (that.revivers[type]) {\n // Record the type only if a corresponding reviver\n // exists. This is to support specs where only\n // replacement is done.\n // For example, ensuring deep cloning of the object,\n // or replacing a type to its equivalent without\n // the need to revive it.\n var existing = types[keypath]; // type can comprise an array of types (see test\n // \"should support intermediate types\")\n\n types[keypath] = existing ? [type].concat(existing) : type;\n }\n\n Object.assign(stateObj, {\n type: type,\n replaced: true\n });\n\n if ((sync || !replacer.replaceAsync) && !replacer.replace) {\n if (runObserver) {\n runObserver({\n typeDetected: true\n });\n }\n\n return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n\n if (runObserver) {\n runObserver({\n replacing: true\n });\n } // Now, also traverse the result in case it contains its\n // own types to replace\n\n\n var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync';\n return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n }\n\n return value;\n }\n\n return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() // If this is a synchronous request for stringification, yet\n // a promise is the result, we don't want to resolve leading\n // to an async result, so we return an array to avoid\n // ambiguity\n : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {any} obj\n * @param {StateObject} stateObj\n * @param {TypesonOptions} opts\n * @returns {any}\n */\n\n }, {\n key: \"encapsulateSync\",\n value: function encapsulateSync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n * @param {any} obj\n * @param {StateObject} stateObj\n * @param {TypesonOptions} opts\n * @returns {any}\n */\n\n }, {\n key: \"encapsulateAsync\",\n value: function encapsulateAsync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * Revive an encapsulated object.\n * This method is used internally by `Typeson.parse()`.\n * @param {PlainObject} obj - Object to revive. If it has `$types` member,\n * the properties that are listed there will be replaced with its true\n * type instead of just plain objects.\n * @param {TypesonOptions} opts\n * @throws TypeError If mismatch between sync/async type and result\n * @returns {Promise|any} If async, returns a Promise that resolves\n * to `any`.\n */\n\n }, {\n key: \"revive\",\n value: function revive(obj, opts) {\n var types = obj && obj.$types; // No type info added. Revival not needed.\n\n if (!types) {\n return obj;\n } // Object happened to have own `$types` property but with\n // no actual types, so we unescape and return that object\n\n\n if (types === true) {\n return obj.$;\n }\n\n opts = _objectSpread2(_objectSpread2({\n sync: true\n }, this.options), opts);\n var _opts3 = opts,\n sync = _opts3.sync;\n var keyPathResolutions = [];\n var stateObj = {};\n var ignore$Types = true; // Special when root object is not a trivial Object, it will\n // be encapsulated in `$`. It will also be encapsulated in\n // `$` if it has its own `$` property to avoid ambiguity\n\n if (types.$ && isPlainObject(types.$)) {\n obj = obj.$;\n types = types.$;\n ignore$Types = false;\n }\n\n var that = this;\n /**\n * @callback RevivalReducer\n * @param {any} value\n * @param {string} type\n * @returns {any}\n */\n\n /**\n *\n * @param {string} type\n * @param {any} val\n * @throws {Error}\n * @returns {any}\n */\n\n function executeReviver(type, val) {\n var _ref = that.revivers[type] || [],\n _ref2 = _slicedToArray(_ref, 1),\n reviver = _ref2[0];\n\n if (!reviver) {\n throw new Error('Unregistered type: ' + type);\n } // Only `sync` expected here, as problematic async would\n // be missing both `reviver` and `reviverAsync`, and\n // encapsulation shouldn't have added types, so\n // should have made an early exit\n\n\n if (sync && !('revive' in reviver)) {\n // Just return value as is\n return val;\n }\n\n return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj);\n }\n /**\n *\n * @returns {void|TypesonPromise}\n */\n\n\n function revivePlainObjects() {\n // const references = [];\n // const reviveTypes = [];\n var plainObjectTypes = [];\n Object.entries(types).forEach(function (_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n keypath = _ref4[0],\n type = _ref4[1];\n\n if (type === '#') {\n /*\n references.push({\n keypath,\n reference: getByKeyPath(obj, keypath)\n });\n */\n return;\n }\n\n [].concat(type).forEach(function (type) {\n var _ref5 = that.revivers[type] || [null, {}],\n _ref6 = _slicedToArray(_ref5, 2),\n plain = _ref6[1].plain;\n\n if (!plain) {\n // reviveTypes.push({keypath, type});\n return;\n }\n\n plainObjectTypes.push({\n keypath: keypath,\n type: type\n });\n delete types[keypath]; // Avoid repeating\n });\n });\n\n if (!plainObjectTypes.length) {\n return undefined;\n } // console.log(plainObjectTypes.sort(nestedPathsFirst));\n\n /**\n * @typedef {PlainObject} PlainObjectType\n * @property {string} keypath\n * @property {string} type\n */\n\n\n return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref7) {\n var keypath = _ref7.keypath,\n type = _ref7.type;\n\n if (isThenable(possibleTypesonPromise)) {\n return possibleTypesonPromise.then(function (val) {\n return reducer(val, {\n keypath: keypath,\n type: type\n });\n });\n } // console.log('obj', JSON.stringify(keypath), obj);\n\n\n var val = getByKeyPath(obj, keypath);\n val = executeReviver(type, val);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n var newVal = setAtKeyPath(obj, keypath, v);\n\n if (newVal === v) {\n obj = newVal;\n }\n\n return undefined;\n });\n }\n\n var newVal = setAtKeyPath(obj, keypath, val);\n\n if (newVal === val) {\n obj = newVal;\n }\n\n return undefined;\n }, undefined // This argument must be explicit\n ); // references.forEach(({keypath, reference}) => {});\n // reviveTypes.sort(nestedPathsFirst).forEach(() => {});\n }\n\n var revivalPromises = [];\n /**\n *\n * @param {string} keypath\n * @param {any} value\n * @param {?(GenericArray|PlainObject)} target\n * @param {GenericArray|PlainObject} [clone]\n * @param {string} [key]\n * @returns {any}\n */\n\n function _revive(keypath, value, target, clone, key) {\n if (ignore$Types && keypath === '$types') {\n return undefined;\n }\n\n var type = types[keypath];\n var isArr = isArray(value);\n\n if (isArr || isPlainObject(value)) {\n // eslint-disable-next-line unicorn/no-new-array -- Sparse\n var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array\n\n\n keys(value).forEach(function (k) {\n var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k);\n\n var set = function set(v) {\n if (hasConstructorOf(v, Undefined)) {\n _clone[k] = undefined;\n } else if (v !== undefined) {\n _clone[k] = v;\n }\n\n return v;\n };\n\n if (hasConstructorOf(val, TypesonPromise)) {\n revivalPromises.push(val.then(function (ret) {\n return set(ret);\n }));\n } else {\n set(val);\n }\n });\n value = _clone; // Try to resolve cyclic reference as soon as available\n\n while (keyPathResolutions.length) {\n var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4),\n _target = _keyPathResolutions$[0],\n keyPath = _keyPathResolutions$[1],\n _clone2 = _keyPathResolutions$[2],\n k = _keyPathResolutions$[3];\n\n var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or\n // `undefined`\n\n if (val !== undefined) {\n _clone2[k] = val;\n } else {\n break;\n }\n\n keyPathResolutions.splice(0, 1);\n }\n }\n\n if (!type) {\n return value;\n }\n\n if (type === '#') {\n var _ret = getByKeyPath(target, value.slice(1));\n\n if (_ret === undefined) {\n // Cyclic reference not yet available\n keyPathResolutions.push([target, value.slice(1), clone, key]);\n }\n\n return _ret;\n } // `type` can be an array here\n\n\n return [].concat(type).reduce(function reducer(val, typ) {\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n // TypesonPromise here too\n return reducer(v, typ);\n });\n }\n\n return executeReviver(typ, val);\n }, value);\n }\n /**\n *\n * @param {any} retrn\n * @returns {undefined|any}\n */\n\n\n function checkUndefined(retrn) {\n return hasConstructorOf(retrn, Undefined) ? undefined : retrn;\n }\n\n var possibleTypesonPromise = revivePlainObjects();\n var ret;\n\n if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) {\n ret = possibleTypesonPromise.then(function () {\n return obj;\n });\n } else {\n ret = _revive('', obj, null);\n\n if (revivalPromises.length) {\n // Ensure children resolved\n ret = TypesonPromise.resolve(ret).then(function (r) {\n return TypesonPromise.all([// May be a TypesonPromise or not\n r].concat(revivalPromises));\n }).then(function (_ref8) {\n var _ref9 = _slicedToArray(_ref8, 1),\n r = _ref9[0];\n\n return r;\n });\n }\n }\n\n return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {any} obj\n * @param {TypesonOptions} opts\n * @returns {any}\n */\n\n }, {\n key: \"reviveSync\",\n value: function reviveSync(obj, opts) {\n return this.revive(obj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n * @param {any} obj\n * @param {TypesonOptions} opts\n * @returns {Promise}\n */\n\n }, {\n key: \"reviveAsync\",\n value: function reviveAsync(obj, opts) {\n return this.revive(obj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * @typedef {Tester|Replacer|Reviver} Spec\n */\n\n /**\n * Register types.\n * For examples on how to use this method, see\n * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}.\n * @param {object[]} typeSpecSets -\n * Types and their functions [test, encapsulate, revive];\n * @param {TypesonOptions} opts\n * @returns {Typeson}\n */\n\n }, {\n key: \"register\",\n value: function register(typeSpecSets, opts) {\n opts = opts || {};\n [].concat(typeSpecSets).forEach(function R(typeSpec) {\n var _this = this;\n\n // Allow arrays of arrays of arrays...\n if (isArray(typeSpec)) {\n return typeSpec.map(function (typSpec) {\n return R.call(_this, typSpec);\n });\n }\n\n typeSpec && keys(typeSpec).forEach(function (typeId) {\n if (typeId === '#') {\n throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects');\n } else if (Typeson.JSON_TYPES.includes(typeId)) {\n throw new TypeError('Plain JSON object types are reserved as type names');\n }\n\n var spec = typeSpec[typeId];\n var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers;\n var existingReplacer = replacers.filter(function (r) {\n return r.type === typeId;\n });\n\n if (existingReplacer.length) {\n // Remove existing spec and replace with this one.\n replacers.splice(replacers.indexOf(existingReplacer[0]), 1);\n delete this.revivers[typeId];\n delete this.types[typeId];\n }\n\n if (typeof spec === 'function') {\n // Support registering just a class without replacer/reviver\n var Class = spec;\n spec = {\n test: function test(x) {\n return x && x.constructor === Class;\n },\n replace: function replace(x) {\n return _objectSpread2({}, x);\n },\n revive: function revive(x) {\n return Object.assign(Object.create(Class.prototype), x);\n }\n };\n } else if (isArray(spec)) {\n var _spec = spec,\n _spec2 = _slicedToArray(_spec, 3),\n test = _spec2[0],\n replace = _spec2[1],\n revive = _spec2[2];\n\n spec = {\n test: test,\n replace: replace,\n revive: revive\n };\n }\n\n if (!spec || !spec.test) {\n return;\n }\n\n var replacerObj = {\n type: typeId,\n test: spec.test.bind(spec)\n };\n\n if (spec.replace) {\n replacerObj.replace = spec.replace.bind(spec);\n }\n\n if (spec.replaceAsync) {\n replacerObj.replaceAsync = spec.replaceAsync.bind(spec);\n }\n\n var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Number.POSITIVE_INFINITY;\n\n if (spec.testPlainObjects) {\n this.plainObjectReplacers.splice(start, 0, replacerObj);\n } else {\n this.nonplainObjectReplacers.splice(start, 0, replacerObj);\n } // Todo: We might consider a testAsync type\n\n\n if (spec.revive || spec.reviveAsync) {\n var reviverObj = {};\n\n if (spec.revive) {\n reviverObj.revive = spec.revive.bind(spec);\n }\n\n if (spec.reviveAsync) {\n reviverObj.reviveAsync = spec.reviveAsync.bind(spec);\n }\n\n this.revivers[typeId] = [reviverObj, {\n plain: spec.testPlainObjects\n }];\n } // Record to be retrieved via public types property.\n\n\n this.types[typeId] = spec;\n }, this);\n }, this);\n return this;\n }\n }]);\n\n return Typeson;\n}();\n/**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * @class\n */\n\n\nvar Undefined = function Undefined() {\n _classCallCheck(this, Undefined);\n}; // eslint-disable-line space-before-blocks\n\n\nUndefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values\n// To insist `undefined` should be added\n\nTypeson.Undefined = Undefined; // To support async encapsulation/stringification\n\nTypeson.Promise = TypesonPromise; // Some fundamental type-checking utilities\n\nTypeson.isThenable = isThenable;\nTypeson.toStringTag = toStringTag;\nTypeson.hasConstructorOf = hasConstructorOf;\nTypeson.isObject = isObject;\nTypeson.isPlainObject = isPlainObject;\nTypeson.isUserObject = isUserObject;\nTypeson.escapeKeyPathComponent = escapeKeyPathComponent;\nTypeson.unescapeKeyPathComponent = unescapeKeyPathComponent;\nTypeson.getByKeyPath = getByKeyPath;\nTypeson.getJSONType = getJSONType;\nTypeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object'];\n\nexport default Typeson;\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.\n\nvar lookup = new Uint8Array(256);\n\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n/**\n * @param {ArrayBuffer} arraybuffer\n * @param {Integer} byteOffset\n * @param {Integer} lngth\n * @returns {string}\n */\n\n\nvar encode = function encode(arraybuffer, byteOffset, lngth) {\n if (lngth === null || lngth === undefined) {\n lngth = arraybuffer.byteLength; // Needed for Safari\n }\n\n var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari\n lngth);\n var len = bytes.length;\n var base64 = '';\n\n for (var _i = 0; _i < len; _i += 3) {\n base64 += chars[bytes[_i] >> 2];\n base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];\n base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];\n base64 += chars[bytes[_i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.slice(0, -1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.slice(0, -2) + '==';\n }\n\n return base64;\n};\n/**\n * @param {string} base64\n * @returns {ArrayBuffer}\n */\n\nvar decode = function decode(base64) {\n var len = base64.length;\n var bufferLength = base64.length * 0.75;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (var _i2 = 0; _i2 < len; _i2 += 4) {\n encoded1 = lookup[base64.charCodeAt(_i2)];\n encoded2 = lookup[base64.charCodeAt(_i2 + 1)];\n encoded3 = lookup[base64.charCodeAt(_i2 + 2)];\n encoded4 = lookup[base64.charCodeAt(_i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n\n return arraybuffer;\n};\n\nexport { decode, encode };\n","import Typeson from 'typeson';\n\nconst userObject = {\n userObject: {\n test (x, stateObj) { return Typeson.isUserObject(x); },\n replace (n) { return {...n}; },\n revive (s) { return s; }\n }\n};\n\nexport default userObject;\n","const arrayNonindexKeys = [\n {\n arrayNonindexKeys: {\n testPlainObjects: true,\n test (x, stateObj) {\n if (Array.isArray(x)) {\n if (\n // By avoiding serializing arrays into objects which\n // have only positive-integer keys, we reduce\n // size and improve revival performance; arrays with\n // non-index keys will be larger however\n Object.keys(x).some((k) => {\n // No need to check for `isNaN` or\n // `isNaN(Number.parseInt())` as `NaN` will be\n // treated as a string.\n // No need to do check as\n // `Number.parseInt(Number())` since scientific\n // notation will be pre-resolved if a number\n // was given, and it will otherwise be a string\n return String(Number.parseInt(k)) !== k;\n })\n ) {\n stateObj.iterateIn = 'object';\n stateObj.addLength = true;\n }\n return true;\n }\n return false;\n },\n replace (a, stateObj) {\n // Catch sparse undefined\n stateObj.iterateUnsetNumeric = true;\n return a;\n },\n revive (o) {\n if (Array.isArray(o)) {\n return o;\n }\n const arr = [];\n // No map here as may be a sparse array (including\n // with `length` set)\n // Todo: Reenable when Node `engines` >= 7\n // Object.entries(o).forEach(([key, val]) => {\n Object.keys(o).forEach((key) => {\n const val = o[key];\n arr[key] = val;\n });\n return arr;\n }\n }\n },\n {\n sparseUndefined: {\n test (x, stateObj) {\n return typeof x === 'undefined' && stateObj.ownKeys === false;\n },\n replace (n) { return 0; },\n revive (s) { return undefined; } // Will avoid adding anything\n }\n }\n];\n\nexport default arrayNonindexKeys;\n","// This does not preserve `undefined` in sparse arrays; see the `undefined`\n// or `sparse-undefined` preset\nimport Typeson from 'typeson';\n\nconst undef = {\n undef: {\n test (x, stateObj) {\n return typeof x === 'undefined' &&\n (stateObj.ownKeys || !('ownKeys' in stateObj));\n },\n replace (n) { return 0; },\n revive (s) {\n // Will add `undefined` (returning `undefined` would instead\n // avoid explicitly setting)\n return new Typeson.Undefined();\n }\n }\n};\n\nexport default undef;\n","// This module is for objectified primitives (such as `new Number(3)` or\n// `new String(\"foo\")`)\n/* eslint-disable no-new-wrappers, unicorn/new-for-builtins */\nimport Typeson from 'typeson';\n\nconst primitiveObjects = {\n // String Object (not primitive string which need no type spec)\n StringObject: {\n test (x) {\n return Typeson.toStringTag(x) === 'String' && typeof x === 'object';\n },\n replace (s) { return String(s); }, // convert to primitive string\n revive (s) { return new String(s); } // Revive to an objectified string\n },\n // Boolean Object (not primitive boolean which need no type spec)\n BooleanObject: {\n test (x) {\n return Typeson.toStringTag(x) === 'Boolean' &&\n typeof x === 'object';\n },\n replace (b) { return Boolean(b); }, // convert to primitive boolean\n revive (b) {\n // Revive to an objectified Boolean\n return new Boolean(b);\n }\n },\n // Number Object (not primitive number which need no type spec)\n NumberObject: {\n test (x) {\n return Typeson.toStringTag(x) === 'Number' && typeof x === 'object';\n },\n replace (n) { return Number(n); }, // convert to primitive number\n revive (n) { return new Number(n); } // Revive to an objectified number\n }\n};\n/* eslint-enable no-new-wrappers, unicorn/new-for-builtins */\n\nexport default primitiveObjects;\n","import nan from '../types/nan.js';\nimport infinity from '../types/infinity.js';\nimport NegativeInfinity from '../types/negative-infinity.js';\n\nconst specialNumbers = [\n nan,\n infinity,\n NegativeInfinity\n];\n\nexport default specialNumbers;\n","const nan = {\n nan: {\n test (x) { return Number.isNaN(x); },\n replace (n) { return 'NaN'; },\n revive (s) { return Number.NaN; }\n }\n};\n\nexport default nan;\n","const infinity = {\n infinity: {\n test (x) { return x === Number.POSITIVE_INFINITY; },\n replace (n) { return 'Infinity'; },\n revive (s) { return Number.POSITIVE_INFINITY; }\n }\n};\n\nexport default infinity;\n","const negativeInfinity = {\n negativeInfinity: {\n test (x) { return x === Number.NEGATIVE_INFINITY; },\n replace (n) { return '-Infinity'; },\n revive (s) { return Number.NEGATIVE_INFINITY; }\n }\n};\n\nexport default negativeInfinity;\n","import Typeson from 'typeson';\n\nconst date = {\n date: {\n test (x) { return Typeson.toStringTag(x) === 'Date'; },\n replace (dt) {\n const time = dt.getTime();\n if (Number.isNaN(time)) {\n return 'NaN';\n }\n return time;\n },\n revive (time) {\n if (time === 'NaN') {\n return new Date(Number.NaN);\n }\n return new Date(time);\n }\n }\n};\n\nexport default date;\n","import Typeson from 'typeson';\n\nconst regexp = {\n regexp: {\n test (x) { return Typeson.toStringTag(x) === 'RegExp'; },\n replace (rexp) {\n return {\n source: rexp.source,\n flags: (rexp.global ? 'g' : '') +\n (rexp.ignoreCase ? 'i' : '') +\n (rexp.multiline ? 'm' : '') +\n (rexp.sticky ? 'y' : '') +\n (rexp.unicode ? 'u' : '')\n };\n },\n revive ({source, flags}) { return new RegExp(source, flags); }\n }\n};\n\nexport default regexp;\n","import Typeson from 'typeson';\n\nconst map = {\n map: {\n test (x) { return Typeson.toStringTag(x) === 'Map'; },\n replace (mp) { return [...mp.entries()]; },\n revive (entries) { return new Map(entries); }\n }\n};\n\nexport default map;\n","import Typeson from 'typeson';\n\nconst set = {\n set: {\n test (x) { return Typeson.toStringTag(x) === 'Set'; },\n replace (st) {\n return [...st.values()];\n },\n revive (values) { return new Set(values); }\n }\n};\n\nexport default set;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst arraybuffer = {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(b);\n if (index > -1) {\n return {index};\n }\n stateObj.buffers.push(b);\n return encode(b);\n },\n revive (b64, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n if (typeof b64 === 'object') {\n return stateObj.buffers[b64.index];\n }\n const buffer = decode(b64);\n stateObj.buffers.push(buffer);\n return buffer;\n }\n }\n};\n\nexport default arraybuffer;\n\n// See also typed-arrays!\n","/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\n/* istanbul ignore next */\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst typedArrays = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n /* istanbul ignore if */\n if (!TypedArray) {\n return;\n }\n typedArrays[typeName.toLowerCase()] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length: l}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, length: l};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n length: l\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, length: len, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new TypedArray(buffer, byteOffset, len);\n }\n };\n});\n\nexport default typedArrays;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst dataview = {\n dataview: {\n test (x) { return Typeson.toStringTag(x) === 'DataView'; },\n replace ({buffer, byteOffset, byteLength}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, byteLength};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n byteLength\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, byteLength, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new DataView(buffer, byteOffset, byteLength);\n }\n }\n};\n\nexport default dataview;\n","import Typeson from 'typeson';\n\nconst IntlCollator = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.Collator); },\n replace (c) { return c.resolvedOptions(); },\n revive (options) { return new Intl.Collator(options.locale, options); }\n};\n\nconst IntlDateTimeFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.DateTimeFormat); },\n replace (dtf) { return dtf.resolvedOptions(); },\n revive (options) {\n return new Intl.DateTimeFormat(options.locale, options);\n }\n};\n\nconst IntlNumberFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.NumberFormat); },\n replace (nf) { return nf.resolvedOptions(); },\n revive (options) { return new Intl.NumberFormat(options.locale, options); }\n};\n\nconst intlTypes = {\n IntlCollator,\n IntlDateTimeFormat,\n IntlNumberFormat\n};\n\nexport default intlTypes;\n","/**\n * Not currently in use internally, but provided for parity.\n * @param {ArrayBuffer} buf\n * @returns {Uint8Array}\n */\nfunction arraybuffer2string (buf) {\n return new Uint8Array(buf).reduce(\n (s, byte) => s + String.fromCharCode(byte), ''\n );\n}\n\n/**\n *\n * @param {string} str\n * @returns {ArrayBuffer}\n */\nfunction string2arraybuffer (str) {\n /*\n // UTF-8 approaches\n const utf8 = unescape(encodeURIComponent(str));\n const arr = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n arr[i] = utf8.charCodeAt(i);\n }\n return arr.buffer;\n\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) utf8.push(charcode);\n else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6),\n 0x80 | (charcode & 0x3f));\n } else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(0xe0 | (charcode >> 12),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n // surrogate pair\n } else {\n i++;\n // UTF-16 encodes 0x10000-0x10FFFF by\n // subtracting 0x10000 and splitting the\n // 20 bits of 0x0-0xFFFFF into two halves\n charcode = 0x10000 + (((charcode & 0x3ff) << 10) |\n (str.charCodeAt(i) & 0x3ff));\n utf8.push(0xf0 | (charcode >> 18),\n 0x80 | ((charcode >> 12) & 0x3f),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n }\n }\n return utf8;\n */\n /*\n // Working UTF-16 options (equivalents)\n const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char\n const bufView = new Uint16Array(buf);\n for (let i = 0, strLen = str.length; i < strLen; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return buf;\n */\n\n const array = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n array[i] = str.charCodeAt(i); // & 0xff;\n }\n return array.buffer;\n}\nexport {arraybuffer2string, string2arraybuffer};\n","/* globals XMLHttpRequest, File, FileReader */\nimport Typeson from 'typeson';\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nconst file = {\n file: {\n test (x) { return Typeson.toStringTag(x) === 'File'; },\n replace (f) { // Sync\n const req = new XMLHttpRequest();\n req.overrideMimeType('text/plain; charset=x-user-defined');\n req.open('GET', URL.createObjectURL(f), false); // Sync\n req.send();\n\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad File access: ' + req.status);\n }\n return {\n type: f.type,\n stringContents: req.responseText,\n name: f.name,\n lastModified: f.lastModified\n };\n },\n revive ({name, type, stringContents, lastModified}) {\n return new File([string2arraybuffer(stringContents)], name, {\n type,\n lastModified\n });\n },\n replaceAsync (f) {\n return new Typeson.Promise(function (resolve, reject) {\n /*\n if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The File is closed'));\n return;\n }\n */\n const reader = new FileReader();\n reader.addEventListener('load', function () {\n resolve({\n type: f.type,\n stringContents: reader.result,\n name: f.name,\n lastModified: f.lastModified\n });\n });\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n reader.addEventListener('error', function () {\n reject(reader.error);\n });\n reader.readAsBinaryString(f);\n });\n }\n }\n};\n\nexport default file;\n","/* globals BigInt */\n\nconst bigint = {\n bigint: {\n test (x) {\n return typeof x === 'bigint';\n },\n replace (n) { return String(n); },\n revive (s) { return BigInt(s); }\n }\n};\n\nexport default bigint;\n","/* globals BigInt */\nimport Typeson from 'typeson';\n\nconst bigintObject = {\n bigintObject: {\n test (x) {\n return typeof x === 'object' && Typeson.hasConstructorOf(x, BigInt);\n },\n replace (n) { return String(n); },\n revive (s) {\n // Filed this to avoid error: https://github.com/eslint/eslint/issues/11810\n // eslint-disable-next-line no-new-object\n return new Object(BigInt(s));\n }\n }\n};\n\nexport default bigintObject;\n","/* globals crypto */\nimport Typeson from 'typeson';\n\nconst cryptokey = {\n cryptokey: {\n test (x) {\n return Typeson.toStringTag(x) === 'CryptoKey' && x.extractable;\n },\n replaceAsync (key) {\n return new Typeson.Promise((resolve, reject) => {\n // eslint-disable-next-line promise/catch-or-return\n crypto.subtle.exportKey('jwk', key).catch(\n /* eslint-disable promise/prefer-await-to-callbacks */\n // istanbul ignore next\n (err) => {\n /* eslint-enable promise/prefer-await-to-callbacks */\n // eslint-disable-next-line max-len\n // istanbul ignore next -- Our format should be valid and our key extractable\n reject(err);\n }\n // eslint-disable-next-line max-len\n // eslint-disable-next-line promise/always-return, promise/prefer-await-to-then\n ).then((jwk) => {\n resolve({\n jwk,\n algorithm: key.algorithm,\n usages: key.usages\n });\n });\n });\n },\n revive ({jwk, algorithm, usages}) {\n return crypto.subtle.importKey('jwk', jwk, algorithm, true, usages);\n }\n }\n};\n\nexport default cryptokey;\n","/* This preset includes types for the Structured Cloning Algorithm. */\n\nimport userObject from '../types/user-object.js';\nimport arrayNonindexKeys from './array-nonindex-keys.js';\nimport undef from '../types/undef.js';\nimport primitiveObjects from '../types/primitive-objects.js';\nimport specialNumbers from './special-numbers.js';\nimport date from '../types/date.js';\nimport regexp from '../types/regexp.js';\nimport map from '../types/map.js';\nimport set from '../types/set.js';\nimport arraybuffer from '../types/arraybuffer.js';\nimport typedArrays from '../types/typed-arrays.js';\nimport dataview from '../types/dataview.js';\nimport intlTypes from '../types/intl-types.js';\n\nimport imagedata from '../types/imagedata.js';\nimport imagebitmap from '../types/imagebitmap.js'; // Async return\nimport file from '../types/file.js';\nimport filelist from '../types/filelist.js';\nimport blob from '../types/blob.js';\nimport bigint from '../types/bigint.js';\nimport bigintObject from '../types/bigint-object.js';\n\nimport cryptokey from '../types/cryptokey.js';\n\nconst expObj = [\n // Todo: Might also register synchronous `ImageBitmap` and\n // `Blob`/`File`/`FileList`?\n // ES5\n userObject, // Processed last (non-builtin)\n\n undef,\n arrayNonindexKeys, primitiveObjects, specialNumbers,\n date, regexp,\n\n // Non-built-ins\n imagedata,\n imagebitmap, // Async return\n file,\n filelist,\n blob\n].concat(\n // ES2015 (ES6)\n /* istanbul ignore next */\n typeof Map === 'function' ? map : [],\n /* istanbul ignore next */\n typeof Set === 'function' ? set : [],\n /* istanbul ignore next */\n typeof ArrayBuffer === 'function' ? arraybuffer : [],\n /* istanbul ignore next */\n typeof Uint8Array === 'function' ? typedArrays : [],\n /* istanbul ignore next */\n typeof DataView === 'function' ? dataview : [],\n /* istanbul ignore next */\n typeof Intl !== 'undefined' ? intlTypes : [],\n /* istanbul ignore next */\n typeof crypto !== 'undefined' ? cryptokey : [],\n /* istanbul ignore next */\n typeof BigInt !== 'undefined' ? [bigint, bigintObject] : []\n);\nexport default expObj;\n","/* globals ImageData */\n// `ImageData` is browser / DOM specific (though `node-canvas` has it\n// available on `Canvas`).\n\nimport Typeson from 'typeson';\n\nconst imagedata = {\n imagedata: {\n test (x) { return Typeson.toStringTag(x) === 'ImageData'; },\n replace (d) {\n return {\n // Ensure `length` gets preserved for revival\n array: [...d.data],\n width: d.width,\n height: d.height\n };\n },\n revive (o) {\n return new ImageData(\n new Uint8ClampedArray(o.array), o.width, o.height\n );\n }\n }\n};\n\nexport default imagedata;\n","/* globals createImageBitmap */\n// `ImageBitmap` is browser / DOM specific. It also can only work\n// same-domain (or CORS)\n\nimport Typeson from 'typeson';\n\nconst imagebitmap = {\n imagebitmap: {\n test (x) {\n return Typeson.toStringTag(x) === 'ImageBitmap' ||\n // In Node, our polyfill sets the dataset on a canvas\n // element as JSDom no longer allows overriding toStringTag\n (x && x.dataset && x.dataset.toStringTag === 'ImageBitmap');\n },\n replace (bm) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n ctx.drawImage(bm, 0, 0);\n // Although `width` and `height` are part of `ImageBitMap`,\n // these will be auto-created for us when reviving with the\n // data URL (and they are not settable even if they weren't)\n // return {\n // width: bm.width, height: bm.height, dataURL: canvas.toDataURL()\n // };\n return canvas.toDataURL();\n },\n revive (o) {\n /*\n var req = new XMLHttpRequest();\n req.open('GET', o, false); // Sync\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad ImageBitmap access: ' + req.status);\n }\n req.send();\n return req.responseText;\n */\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.addEventListener('load', function () {\n ctx.drawImage(img, 0, 0);\n });\n img.src = o;\n // Works in contexts allowing an `ImageBitmap` (We might use\n // `OffscreenCanvas.transferToBitmap` when supported)\n return canvas;\n },\n reviveAsync (o) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.addEventListener('load', function () {\n ctx.drawImage(img, 0, 0);\n });\n img.src = o; // o.dataURL;\n return createImageBitmap(canvas); // Returns a promise\n }\n }\n};\n\nexport default imagebitmap;\n","import Typeson from 'typeson';\nimport file from './file.js';\n\nconst filelist = {\n file: file.file,\n filelist: {\n test (x) { return Typeson.toStringTag(x) === 'FileList'; },\n replace (fl) {\n const arr = [];\n for (let i = 0; i < fl.length; i++) {\n arr[i] = fl.item(i);\n }\n return arr;\n },\n revive (o) {\n /**\n * `FileList` polyfill.\n */\n class FileList {\n /**\n * Set private properties and length.\n */\n constructor () {\n // eslint-disable-next-line prefer-rest-params\n this._files = arguments[0];\n this.length = this._files.length;\n }\n /**\n * @param {Integer} index\n * @returns {File}\n */\n item (index) {\n return this._files[index];\n }\n /* eslint-disable class-methods-use-this */\n /**\n * @returns {\"FileList\"}\n */\n get [Symbol.toStringTag] () {\n /* eslint-enable class-methods-use-this */\n return 'FileList';\n }\n }\n return new FileList(o);\n }\n }\n};\n\nexport default filelist;\n","/* globals XMLHttpRequest, Blob, FileReader */\nimport Typeson from 'typeson';\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nconst blob = {\n blob: {\n test (x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace (b) { // Sync\n const req = new XMLHttpRequest();\n req.overrideMimeType('text/plain; charset=x-user-defined');\n req.open('GET', URL.createObjectURL(b), false); // Sync\n req.send();\n\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad Blob access: ' + req.status);\n }\n return {\n type: b.type,\n stringContents: req.responseText\n };\n },\n revive ({type, stringContents}) {\n return new Blob([string2arraybuffer(stringContents)], {type});\n },\n replaceAsync (b) {\n return new Typeson.Promise((resolve, reject) => {\n /*\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The Blob is closed'));\n return;\n }\n */\n const reader = new FileReader();\n reader.addEventListener('load', () => {\n resolve({\n type: b.type,\n stringContents: reader.result\n });\n });\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n reader.addEventListener('error', () => {\n reject(reader.error);\n });\n reader.readAsBinaryString(b);\n });\n }\n }\n};\n\nexport default blob;\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.\n\nvar lookup = new Uint8Array(256);\n\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.codePointAt(i)] = i;\n}\n/**\n * @param {ArrayBuffer} arraybuffer\n * @param {Integer} byteOffset\n * @param {Integer} lngth\n * @returns {string}\n */\n\n\nvar encode = function encode(arraybuffer, byteOffset, lngth) {\n if (lngth === null || lngth === undefined) {\n lngth = arraybuffer.byteLength; // Needed for Safari\n }\n\n var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari\n lngth);\n var len = bytes.length;\n var base64 = '';\n\n for (var _i = 0; _i < len; _i += 3) {\n base64 += chars[bytes[_i] >> 2];\n base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];\n base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];\n base64 += chars[bytes[_i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.slice(0, -1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.slice(0, -2) + '==';\n }\n\n return base64;\n};\n/**\n * @param {string} base64\n * @returns {ArrayBuffer}\n */\n\nvar decode = function decode(base64) {\n var len = base64.length;\n var bufferLength = base64.length * 0.75;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (var _i2 = 0; _i2 < len; _i2 += 4) {\n encoded1 = lookup[base64.codePointAt(_i2)];\n encoded2 = lookup[base64.codePointAt(_i2 + 1)];\n encoded3 = lookup[base64.codePointAt(_i2 + 2)];\n encoded4 = lookup[base64.codePointAt(_i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n\n return arraybuffer;\n};\n\nexport { decode, encode };\n","declare var global;\n\n/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst exportObj = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n if (TypedArray) {\n exportObj[typeName.toLowerCase()+\"2\"] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length}) {\n return {\n buffer,\n byteOffset,\n length\n };\n },\n revive (b64Obj) {\n const {buffer, byteOffset, length} = b64Obj;\n return new TypedArray(buffer, byteOffset, length);\n }\n };\n }\n});\n\nexport default exportObj;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nexport default {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b) {\n return encode(b, 0, b.byteLength);\n },\n revive (b64) {\n const buffer = decode(b64);\n return buffer;\n }\n }\n};\n\n// See also typed-arrays!\n","import Typeson from 'typeson';\nimport StructuredCloning from 'typeson-registry/dist/presets/structured-cloning';\nimport { encode as encodeB64, decode as decodeB64 } from 'base64-arraybuffer-es6';\nimport Dexie from 'dexie';\nimport { readBlobSync, readBlobAsync } from './helpers';\nimport typedArray from './tson-typed-array';\nimport arrayBuffer from './tson-arraybuffer';\n\nexport const TSON = new Typeson().register(StructuredCloning);\n\nconst readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\nlet blobsToAwait: any[] = [];\nlet blobsToAwaitPos = 0;\n\n// Need to patch encapsulateAsync as it does not work as of typeson 5.8.2\n// Also, current version of typespn-registry-1.0.0-alpha.21 does not\n// encapsulate/revive Blobs correctly (fails one of the unit tests in\n// this library (test 'export-format'))\nTSON.register([\n arrayBuffer,\n typedArray, {\n blob2: {\n test(x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace(b) {\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n throw new Error('The Blob is closed');\n }\n if (readBlobsSynchronously) {\n const data = readBlobSync(b, 'binary');\n const base64 = encodeB64(data, 0, data.byteLength);\n return {\n type: b.type,\n data: base64\n }\n } else {\n blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true.\n const result = {\n type: b.type,\n data: {start: blobsToAwaitPos, end: blobsToAwaitPos + b.size}\n }\n blobsToAwaitPos += b.size;\n return result;\n }\n },\n finalize(b, ba: ArrayBuffer) {\n b.data = encodeB64(ba, 0, ba.byteLength);\n },\n revive ({type, data}) {\n return new Blob([decodeB64(data)], {type});\n }\n }\n }\n]);\n\nTSON.mustFinalize = ()=>blobsToAwait.length > 0;\n\nTSON.finalize = async (items?: any[]) => {\n const allChunks = await readBlobAsync(new Blob(blobsToAwait), 'binary');\n if (items) {\n for (const item of items) {\n // Manually go through all \"blob\" types in the result\n // and lookup the data slice they point at.\n if (item.$types) {\n let types = item.$types;\n const arrayType = types.$;\n if (arrayType) types = types.$;\n for (let keyPath in types) {\n const typeName = types[keyPath];\n const typeSpec = TSON.types[typeName];\n if (typeSpec && typeSpec.finalize) {\n const b = Dexie.getByKeyPath(item, arrayType ? \"$.\" + keyPath : keyPath);\n typeSpec.finalize(b, allChunks.slice(b.start, b.end));\n }\n }\n }\n }\n }\n // Free up memory\n blobsToAwait = [];\n}\n","\nimport Dexie from 'dexie';\nimport { getSchemaString, extractDbSchema } from './helpers';\nimport { DexieExportedTable, DexieExportJsonStructure } from './json-structure';\nimport { TSON } from './tson';\n\nexport interface ExportOptions {\n noTransaction?: boolean;\n numRowsPerChunk?: number;\n prettyJson?: boolean;\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ExportProgress) => boolean;\n}\n\nexport interface ExportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nconst DEFAULT_ROWS_PER_CHUNK = 2000;\n\nexport async function exportDB(db: Dexie, options?: ExportOptions): Promise {\n options = options || {};\n const slices: (string | Blob)[] = [];\n const tables = db.tables.map(table => ({\n name: table.name,\n schema: getSchemaString(table),\n rowCount: 0\n }));\n const {prettyJson} = options!;\n const emptyExport: DexieExportJsonStructure = {\n formatName: \"dexie\",\n formatVersion: 1,\n data: {\n databaseName: db.name,\n databaseVersion: db.verno,\n tables: tables,\n data: []\n }\n };\n \n const {progressCallback} = options!;\n const progress: ExportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: NaN,\n totalTables: db.tables.length\n };\n\n try {\n if (options!.noTransaction) {\n await exportAll();\n } else {\n await db.transaction('r', db.tables, exportAll);\n }\n } finally {\n TSON.finalize(); // Free up mem if error has occurred\n }\n\n return new Blob(slices,{type: \"text/json\"});\n\n async function exportAll() {\n // Count rows:\n const tablesRowCounts = await Promise.all(db.tables.map(table => table.count()));\n tablesRowCounts.forEach((rowCount, i) => tables[i].rowCount = rowCount);\n progress.totalRows = tablesRowCounts.reduce((p,c)=>p+c);\n\n // Write first JSON slice\n const emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined);\n const posEndDataArray = emptyExportJson.lastIndexOf(']');\n const firstJsonSlice = emptyExportJson.substring(0, posEndDataArray);\n slices.push(firstJsonSlice);\n\n const filter = options!.filter;\n\n for (const {name: tableName} of tables) {\n const table = db.table(tableName);\n const {primKey} = table.schema;\n const inbound = !!primKey.keyPath;\n const LIMIT = options!.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK;\n const emptyTableExport: DexieExportedTable = inbound ? {\n tableName: table.name,\n inbound: true,\n rows: []\n } : {\n tableName: table.name,\n inbound: false,\n rows: []\n };\n let emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) {\n // Increase indentation according to this:\n // {\n // ...\n // data: [\n // ...\n // data: [\n // 123456<---- here\n // ] \n // ]\n // }\n emptyTableExportJson = emptyTableExportJson.split('\\n').join('\\n ');\n }\n const posEndRowsArray = emptyTableExportJson.lastIndexOf(']');\n slices.push(emptyTableExportJson.substring(0, posEndRowsArray));\n let lastKey: any = null;\n let lastNumRows = 0;\n let mayHaveMoreRows = true;\n while (mayHaveMoreRows) {\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const chunkedCollection = lastKey == null ?\n table.limit(LIMIT) :\n table.where(':id').above(lastKey).limit(LIMIT);\n\n const values = await chunkedCollection.toArray();\n\n if (values.length === 0) break;\n\n if (lastKey != null && lastNumRows > 0) {\n // Not initial chunk. Must add a comma:\n slices.push(\",\");\n if (prettyJson) {\n slices.push(\"\\n \");\n }\n }\n\n mayHaveMoreRows = values.length === LIMIT;\n \n if (inbound) {\n const filteredValues = filter ?\n values.filter(value => filter(tableName, value)) :\n values;\n\n const tsonValues = filteredValues.map(value => TSON.encapsulate(value));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonValues));\n }\n\n let json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = filteredValues.length;\n lastKey = values.length > 0 ?\n Dexie.getByKeyPath(values[values.length -1], primKey.keyPath as string) :\n null;\n } else {\n const keys = await chunkedCollection.primaryKeys();\n let keyvals = keys.map((key, i) => [key, values[i]]);\n if (filter) keyvals = keyvals.filter(([key, value]) => filter(tableName, value, key));\n\n const tsonTuples = keyvals.map(tuple => TSON.encapsulate(tuple));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonTuples));\n }\n\n let json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = keyvals.length;\n lastKey = keys.length > 0 ?\n keys[keys.length - 1] :\n null;\n }\n progress.completedRows += values.length;\n }\n slices.push(emptyTableExportJson.substr(posEndRowsArray)); // \"]}\"\n progress.completedTables += 1;\n if (progress.completedTables < progress.totalTables) {\n slices.push(\",\");\n }\n }\n slices.push(emptyExportJson.substr(posEndDataArray));\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n }\n}\n","export const VERSION = 1;\n\n/** Same as DexieExportJsonStructure but without the data.data array */\nexport interface DexieExportJsonMeta {\n formatName: 'dexie';\n formatVersion: typeof VERSION;\n data: {\n databaseName: string;\n databaseVersion: number;\n tables: Array<{\n name: string;\n schema: string;\n rowCount: number;\n }>;\n }\n}\n\nexport interface DexieExportJsonStructure extends DexieExportJsonMeta {\n formatName: 'dexie';\n formatVersion: typeof VERSION;\n data: {\n databaseName: string;\n databaseVersion: number;\n tables: Array<{\n name: string;\n schema: string;\n rowCount: number;\n }>;\n data: Array<{\n tableName: string;\n inbound: boolean;\n rows: any[];\n }>;\n }\n}\n\nexport type DexieExportedDatabase = DexieExportJsonStructure[\"data\"];\nexport type DexieExportedTable = DexieExportedDatabase[\"data\"][number];\n","module.exports = {Stream: function(){}};\n\n",";(function (clarinet) {\n \"use strict\";\n\n // non node-js needs to set clarinet debug on root\n var env =(typeof process === 'object' && process.env)\n ? process.env\n : self;\n\n clarinet.parser = function (opt) { return new CParser(opt);};\n clarinet.CParser = CParser;\n clarinet.CStream = CStream;\n clarinet.createStream = createStream;\n clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024;\n clarinet.DEBUG = (env.CDEBUG==='debug');\n clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info');\n clarinet.EVENTS =\n [ \"value\"\n , \"string\"\n , \"key\"\n , \"openobject\"\n , \"closeobject\"\n , \"openarray\"\n , \"closearray\"\n , \"error\"\n , \"end\"\n , \"ready\"\n ];\n\n var buffers = {\n textNode: undefined,\n numberNode: \"\"\n }\n , streamWraps = clarinet.EVENTS.filter(function (ev) {\n return ev !== \"error\" && ev !== \"end\";\n })\n , S = 0\n , Stream\n ;\n\n clarinet.STATE =\n { BEGIN : S++\n , VALUE : S++ // general stuff\n , OPEN_OBJECT : S++ // {\n , CLOSE_OBJECT : S++ // }\n , OPEN_ARRAY : S++ // [\n , CLOSE_ARRAY : S++ // ]\n , TEXT_ESCAPE : S++ // \\ stuff\n , STRING : S++ // \"\"\n , BACKSLASH : S++\n , END : S++ // No more stack\n , OPEN_KEY : S++ // , \"a\"\n , CLOSE_KEY : S++ // :\n , TRUE : S++ // r\n , TRUE2 : S++ // u\n , TRUE3 : S++ // e\n , FALSE : S++ // a\n , FALSE2 : S++ // l\n , FALSE3 : S++ // s\n , FALSE4 : S++ // e\n , NULL : S++ // u\n , NULL2 : S++ // l\n , NULL3 : S++ // l\n , NUMBER_DECIMAL_POINT : S++ // .\n , NUMBER_DIGIT : S++ // [0-9]\n };\n\n for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_;\n\n // switcharoo\n S = clarinet.STATE;\n\n const Char = {\n tab : 0x09, // \\t\n lineFeed : 0x0A, // \\n\n carriageReturn : 0x0D, // \\r\n space : 0x20, // \" \"\n\n doubleQuote : 0x22, // \"\n plus : 0x2B, // +\n comma : 0x2C, // ,\n minus : 0x2D, // -\n period : 0x2E, // .\n\n _0 : 0x30, // 0\n _9 : 0x39, // 9\n\n colon : 0x3A, // :\n\n E : 0x45, // E\n\n openBracket : 0x5B, // [\n backslash : 0x5C, // \\\n closeBracket : 0x5D, // ]\n\n a : 0x61, // a\n b : 0x62, // b\n e : 0x65, // e \n f : 0x66, // f\n l : 0x6C, // l\n n : 0x6E, // n\n r : 0x72, // r\n s : 0x73, // s\n t : 0x74, // t\n u : 0x75, // u\n\n openBrace : 0x7B, // {\n closeBrace : 0x7D, // }\n }\n\n if (!Object.create) {\n Object.create = function (o) {\n function f () { this[\"__proto__\"] = o; }\n f.prototype = o;\n return new f;\n };\n }\n\n if (!Object.getPrototypeOf) {\n Object.getPrototypeOf = function (o) {\n return o[\"__proto__\"];\n };\n }\n\n if (!Object.keys) {\n Object.keys = function (o) {\n var a = [];\n for (var i in o) if (o.hasOwnProperty(i)) a.push(i);\n return a;\n };\n }\n\n function checkBufferLength (parser) {\n var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10)\n , maxActual = 0\n ;\n for (var buffer in buffers) {\n var len = parser[buffer] === undefined ? 0 : parser[buffer].length;\n if (len > maxAllowed) {\n switch (buffer) {\n case \"text\":\n closeText(parser);\n break;\n\n default:\n error(parser, \"Max buffer length exceeded: \"+ buffer);\n }\n }\n maxActual = Math.max(maxActual, len);\n }\n parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual)\n + parser.position;\n }\n\n function clearBuffers (parser) {\n for (var buffer in buffers) {\n parser[buffer] = buffers[buffer];\n }\n }\n\n var stringTokenPattern = /[\\\\\"\\n]/g;\n\n function CParser (opt) {\n if (!(this instanceof CParser)) return new CParser (opt);\n\n var parser = this;\n clearBuffers(parser);\n parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH;\n parser.q = parser.c = parser.p = \"\";\n parser.opt = opt || {};\n parser.closed = parser.closedRoot = parser.sawRoot = false;\n parser.tag = parser.error = null;\n parser.state = S.BEGIN;\n parser.stack = new Array();\n // mostly just for error reporting\n parser.position = parser.column = 0;\n parser.line = 1;\n parser.slashed = false;\n parser.unicodeI = 0;\n parser.unicodeS = null;\n parser.depth = 0;\n emit(parser, \"onready\");\n }\n\n CParser.prototype =\n { end : function () { end(this); }\n , write : write\n , resume : function () { this.error = null; return this; }\n , close : function () { return this.write(null); }\n };\n\n try { Stream = require(\"stream\").Stream; }\n catch (ex) { Stream = function () {}; }\n\n function createStream (opt) { return new CStream(opt); }\n\n function CStream (opt) {\n if (!(this instanceof CStream)) return new CStream(opt);\n\n this._parser = new CParser(opt);\n this.writable = true;\n this.readable = true;\n\n //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error\n this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary\n this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read\n this.temp_buffs = { \"2\": new Buffer(2), \"3\": new Buffer(3), \"4\": new Buffer(4) }; // for rebuilding chars split before boundary is reached\n this.string = '';\n\n var me = this;\n Stream.apply(me);\n\n this._parser.onend = function () { me.emit(\"end\"); };\n this._parser.onerror = function (er) {\n me.emit(\"error\", er);\n me._parser.error = null;\n };\n\n streamWraps.forEach(function (ev) {\n Object.defineProperty(me, \"on\" + ev,\n { get : function () { return me._parser[\"on\" + ev]; }\n , set : function (h) {\n if (!h) {\n me.removeAllListeners(ev);\n me._parser[\"on\"+ev] = h;\n return h;\n }\n me.on(ev, h);\n }\n , enumerable : true\n , configurable : false\n });\n });\n }\n\n CStream.prototype = Object.create(Stream.prototype,\n { constructor: { value: CStream } });\n\n CStream.prototype.write = function (data) {\n data = new Buffer(data);\n for (var i = 0; i < data.length; i++) {\n var n = data[i];\n\n // check for carry over of a multi byte char split between data chunks\n // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration\n if (this.bytes_remaining > 0) {\n for (var j = 0; j < this.bytes_remaining; j++) {\n this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j];\n }\n this.string = this.temp_buffs[this.bytes_in_sequence].toString();\n this.bytes_in_sequence = this.bytes_remaining = 0;\n\n // move iterator forward by number of byte read during sequencing\n i = i + j - 1;\n\n // pass data to parser and move forward to parse rest of data\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n\n // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time\n if (this.bytes_remaining === 0 && n >= 128) {\n if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;\n if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;\n if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;\n if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split\n\n for (var k = 0; k <= (data.length - 1 - i); k++) {\n this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk\n }\n this.bytes_remaining = (i + this.bytes_in_sequence) - data.length;\n\n // immediately return as we need another chunk to sequence the character\n return true;\n } else {\n this.string = data.slice(i, (i + this.bytes_in_sequence)).toString();\n i = i + this.bytes_in_sequence - 1;\n\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n }\n\n // is there a range of characters that are immediately parsable?\n for (var p = i; p < data.length; p++) {\n if (data[p] >= 128) break;\n }\n this.string = data.slice(i, p).toString();\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n i = p - 1;\n\n // handle any remaining characters using multibyte logic\n continue;\n }\n };\n\n CStream.prototype.end = function (chunk) {\n if (chunk && chunk.length) this._parser.write(chunk.toString());\n this._parser.end();\n return true;\n };\n\n CStream.prototype.on = function (ev, handler) {\n var me = this;\n if (!me._parser[\"on\"+ev] && streamWraps.indexOf(ev) !== -1) {\n me._parser[\"on\"+ev] = function () {\n var args = arguments.length === 1 ? [arguments[0]]\n : Array.apply(null, arguments);\n args.splice(0, 0, ev);\n me.emit.apply(me, args);\n };\n }\n return Stream.prototype.on.call(me, ev, handler);\n };\n\n CStream.prototype.destroy = function () {\n clearBuffers(this._parser);\n this.emit(\"close\");\n };\n\n function emit(parser, event, data) {\n if(clarinet.INFO) console.log('-- emit', event, data);\n if (parser[event]) parser[event](data);\n }\n\n function emitNode(parser, event, data) {\n closeValue(parser);\n emit(parser, event, data);\n }\n\n function closeValue(parser, event) {\n parser.textNode = textopts(parser.opt, parser.textNode);\n if (parser.textNode !== undefined) {\n emit(parser, (event ? event : \"onvalue\"), parser.textNode);\n }\n parser.textNode = undefined;\n }\n\n function closeNumber(parser) {\n if (parser.numberNode)\n emit(parser, \"onvalue\", parseFloat(parser.numberNode));\n parser.numberNode = \"\";\n }\n\n function textopts (opt, text) {\n if (text === undefined) {\n return text;\n }\n if (opt.trim) text = text.trim();\n if (opt.normalize) text = text.replace(/\\s+/g, \" \");\n return text;\n }\n\n function error (parser, er) {\n closeValue(parser);\n er += \"\\nLine: \"+parser.line+\n \"\\nColumn: \"+parser.column+\n \"\\nChar: \"+parser.c;\n er = new Error(er);\n parser.error = er;\n emit(parser, \"onerror\", er);\n return parser;\n }\n\n function end(parser) {\n if (parser.state !== S.VALUE || parser.depth !== 0)\n error(parser, \"Unexpected end\");\n\n closeValue(parser);\n parser.c = \"\";\n parser.closed = true;\n emit(parser, \"onend\");\n CParser.call(parser, parser.opt);\n return parser;\n }\n\n function isWhitespace(c) {\n return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;\n }\n\n function write (chunk) {\n var parser = this;\n if (this.error) throw this.error;\n if (parser.closed) return error(parser,\n \"Cannot write after close. Assign an onready handler.\");\n if (chunk === null) return end(parser);\n var i = 0, c = chunk.charCodeAt(0), p = parser.p;\n if (clarinet.DEBUG) console.log('write -> [' + chunk + ']');\n while (c) {\n p = c;\n parser.c = c = chunk.charCodeAt(i++);\n // if chunk doesnt have next, like streaming char by char\n // this way we need to check if previous is really previous\n // if not we need to reset to what the parser says is the previous\n // from buffer\n if(p !== c ) parser.p = p;\n else p = parser.p;\n\n if(!c) break;\n\n if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]);\n parser.position ++;\n if (c === Char.lineFeed) {\n parser.line ++;\n parser.column = 0;\n } else parser.column ++;\n switch (parser.state) {\n\n case S.BEGIN:\n if (c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if (!isWhitespace(c))\n error(parser, \"Non-whitespace before {[.\");\n continue;\n\n case S.OPEN_KEY:\n case S.OPEN_OBJECT:\n if (isWhitespace(c)) continue;\n if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY);\n else {\n if(c === Char.closeBrace) {\n emit(parser, 'onopenobject');\n this.depth++;\n emit(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else parser.stack.push(S.CLOSE_OBJECT);\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else error(parser, \"Malformed object key should start with \\\"\");\n continue;\n\n case S.CLOSE_KEY:\n case S.CLOSE_OBJECT:\n if (isWhitespace(c)) continue;\n var event = (parser.state === S.CLOSE_KEY) ? 'key' : 'object';\n if(c === Char.colon) {\n if(parser.state === S.CLOSE_OBJECT) {\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser, 'onopenobject');\n this.depth++;\n } else closeValue(parser, 'onkey');\n parser.state = S.VALUE;\n } else if (c === Char.closeBrace) {\n emitNode(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if(c === Char.comma) {\n if(parser.state === S.CLOSE_OBJECT)\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser);\n parser.state = S.OPEN_KEY;\n } else error(parser, 'Bad object');\n continue;\n\n case S.OPEN_ARRAY: // after an array there always a value\n case S.VALUE:\n if (isWhitespace(c)) continue;\n if(parser.state===S.OPEN_ARRAY) {\n emit(parser, 'onopenarray');\n this.depth++;\n parser.state = S.VALUE;\n if(c === Char.closeBracket) {\n emit(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else {\n parser.stack.push(S.CLOSE_ARRAY);\n }\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if(c === Char.t) parser.state = S.TRUE;\n else if(c === Char.f) parser.state = S.FALSE;\n else if(c === Char.n) parser.state = S.NULL;\n else if(c === Char.minus) { // keep and continue\n parser.numberNode += \"-\";\n } else if(Char._0 <= c && c <= Char._9) {\n parser.numberNode += String.fromCharCode(c);\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, \"Bad value\");\n continue;\n\n case S.CLOSE_ARRAY:\n if(c === Char.comma) {\n parser.stack.push(S.CLOSE_ARRAY);\n closeValue(parser, 'onvalue');\n parser.state = S.VALUE;\n } else if (c === Char.closeBracket) {\n emitNode(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if (isWhitespace(c))\n continue;\n else error(parser, 'Bad array');\n continue;\n\n case S.STRING:\n if (parser.textNode === undefined) {\n parser.textNode = \"\";\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i-1\n , slashed = parser.slashed\n , unicodeI = parser.unicodeI\n ;\n STRING_BIGLOOP: while (true) {\n if (clarinet.DEBUG)\n console.log(i,c,clarinet.STATE[parser.state]\n ,slashed);\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n parser.unicodeS += String.fromCharCode(c);\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16));\n unicodeI = 0;\n starti = i-1;\n } else {\n unicodeI++;\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n if (!c) break STRING_BIGLOOP;\n }\n if (c === Char.doubleQuote && !slashed) {\n parser.state = parser.stack.pop() || S.VALUE;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n if (c === Char.backslash && !slashed) {\n slashed = true;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (!c) break;\n }\n if (slashed) {\n slashed = false;\n if (c === Char.n) { parser.textNode += '\\n'; }\n else if (c === Char.r) { parser.textNode += '\\r'; }\n else if (c === Char.t) { parser.textNode += '\\t'; }\n else if (c === Char.f) { parser.textNode += '\\f'; }\n else if (c === Char.b) { parser.textNode += '\\b'; }\n else if (c === Char.u) {\n // \\uxxxx. meh!\n unicodeI = 1;\n parser.unicodeS = '';\n } else {\n parser.textNode += String.fromCharCode(c);\n }\n c = chunk.charCodeAt(i++);\n parser.position++;\n starti = i-1;\n if (!c) break;\n else continue;\n }\n\n stringTokenPattern.lastIndex = i;\n var reResult = stringTokenPattern.exec(chunk);\n if (reResult === null) {\n i = chunk.length+1;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n i = reResult.index+1;\n c = chunk.charCodeAt(reResult.index);\n if (!c) {\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n }\n parser.slashed = slashed;\n parser.unicodeI = unicodeI;\n continue;\n\n case S.TRUE:\n if (c === Char.r) parser.state = S.TRUE2;\n else error(parser, 'Invalid true started with t'+ c);\n continue;\n\n case S.TRUE2:\n if (c === Char.u) parser.state = S.TRUE3;\n else error(parser, 'Invalid true started with tr'+ c);\n continue;\n\n case S.TRUE3:\n if(c === Char.e) {\n emit(parser, \"onvalue\", true);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid true started with tru'+ c);\n continue;\n\n case S.FALSE:\n if (c === Char.a) parser.state = S.FALSE2;\n else error(parser, 'Invalid false started with f'+ c);\n continue;\n\n case S.FALSE2:\n if (c === Char.l) parser.state = S.FALSE3;\n else error(parser, 'Invalid false started with fa'+ c);\n continue;\n\n case S.FALSE3:\n if (c === Char.s) parser.state = S.FALSE4;\n else error(parser, 'Invalid false started with fal'+ c);\n continue;\n\n case S.FALSE4:\n if (c === Char.e) {\n emit(parser, \"onvalue\", false);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid false started with fals'+ c);\n continue;\n\n case S.NULL:\n if (c === Char.u) parser.state = S.NULL2;\n else error(parser, 'Invalid null started with n'+ c);\n continue;\n\n case S.NULL2:\n if (c === Char.l) parser.state = S.NULL3;\n else error(parser, 'Invalid null started with nu'+ c);\n continue;\n\n case S.NULL3:\n if(c === Char.l) {\n emit(parser, \"onvalue\", null);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid null started with nul'+ c);\n continue;\n\n case S.NUMBER_DECIMAL_POINT:\n if(c === Char.period) {\n parser.numberNode += \".\";\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, 'Leading zero not followed by .');\n continue;\n\n case S.NUMBER_DIGIT:\n if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c);\n else if (c === Char.period) {\n if(parser.numberNode.indexOf('.')!==-1)\n error(parser, 'Invalid number has two dots');\n parser.numberNode += \".\";\n } else if (c === Char.e || c === Char.E) {\n if(parser.numberNode.indexOf('e')!==-1 ||\n parser.numberNode.indexOf('E')!==-1 )\n error(parser, 'Invalid number has two exponential');\n parser.numberNode += \"e\";\n } else if (c === Char.plus || c === Char.minus) {\n if(!(p === Char.e || p === Char.E))\n error(parser, 'Invalid symbol in number');\n parser.numberNode += String.fromCharCode(c);\n } else {\n closeNumber(parser);\n i--; // go back one\n parser.state = parser.stack.pop() || S.VALUE;\n }\n continue;\n\n default:\n error(parser, \"Unknown state: \" + parser.state);\n }\n }\n if (parser.position >= parser.bufferCheckPosition)\n checkBufferLength(parser);\n return parser;\n }\n\n})(typeof exports === \"undefined\" ? clarinet = {} : exports);\n","import clarinet from 'clarinet';\nimport { readBlobAsync, readBlobSync } from './helpers';\n\nexport interface JsonStream {\n pullAsync(numBytes: number): Promise>;\n pullSync(numBytes: number): Partial;\n done(): boolean;\n eof(): boolean;\n result: Partial;\n}\n\nexport function JsonStream(blob: Blob): JsonStream {\n let pos = 0;\n const parser = JsonParser(true);\n\n const rv = {\n async pullAsync(numBytes: number): Promise> {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = await readBlobAsync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n pullSync(numBytes: number): Partial {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = readBlobSync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n done() {\n return parser.done();\n },\n eof() {\n return pos >= blob.size;\n },\n result: {}\n }\n\n return rv;\n}\n\n\nexport function JsonParser (allowPartial: boolean) {\n const parser = (clarinet as any).parser();\n let level = 0;\n let result: any;\n const stack: any[][] = [];\n let obj: any;\n let key: string | null;\n let done = false;\n let array = false;\n\n parser.onopenobject = newKey => {\n const newObj = {};\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n key = newKey;\n array = false;\n ++level;\n }\n parser.onkey = newKey => key = newKey;\n parser.onvalue = value => array ? obj.push(value) : obj[key!] = value;\n parser.oncloseobject = ()=>{\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n parser.onopenarray = () => {\n const newObj = [];\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n array = true;\n key = null;\n ++level;\n }\n parser.onclosearray = () => {\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n\n return {\n write(jsonPart: string) {\n parser.write(jsonPart);\n return result;\n },\n done() {\n return done;\n }\n }\n}\n","import Dexie from 'dexie';\nimport { extractDbSchema } from './helpers';\nimport { DexieExportJsonMeta, DexieExportJsonStructure, VERSION } from './json-structure';\nimport { TSON } from './tson';\nimport { JsonStream } from './json-stream';\n\nexport interface StaticImportOptions {\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nexport interface ImportOptions extends StaticImportOptions {\n acceptMissingTables?: boolean;\n acceptVersionDiff?: boolean;\n acceptNameDiff?: boolean;\n acceptChangedPrimaryKey?: boolean;\n overwriteValues?: boolean;\n clearTablesBeforeImport?: boolean;\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nconst DEFAULT_KILOBYTES_PER_CHUNK = 1024;\n\nexport interface ImportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nexport async function importDB(exportedData: Blob | JsonStream, options?: StaticImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const stream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n const dbExport = stream.result.data!;\n const db = new Dexie(dbExport.databaseName);\n db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport));\n await importInto(db, stream, options);\n return db;\n}\n\nexport async function peakImportFile(exportedData: Blob): Promise {\n const stream = JsonStream(exportedData);\n while (!stream.eof()) {\n await stream.pullAsync(5 * 1024); // 5 k is normally enough for the headers. If not, it will just do another go.\n if (stream.result.data && stream.result.data!.data) {\n // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it.\n delete stream.result.data.data; // Don't return half-baked data array.\n break;\n }\n }\n return stream.result as DexieExportJsonMeta;\n}\n\nexport async function importInto(db: Dexie, exportedData: Blob | JsonStream, options?: ImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const jsonStream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n let dbExportFile = jsonStream.result;\n const readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\n const dbExport = dbExportFile.data!;\n\n if (!options!.acceptNameDiff && db.name !== dbExport.databaseName)\n throw new Error(`Name differs. Current database name is ${db.name} but export is ${dbExport.databaseName}`);\n if (!options!.acceptVersionDiff && db.verno !== dbExport.databaseVersion) {\n // Possible feature: Call upgraders in some isolated way if this happens... ?\n throw new Error(`Database version differs. Current database is in version ${db.verno} but export is ${dbExport.databaseVersion}`);\n }\n \n const { progressCallback } = options;\n const progress: ImportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: dbExport.tables.reduce((p, c) => p + c.rowCount, 0),\n totalTables: dbExport.tables.length\n };\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n\n if (options!.clearTablesBeforeImport) {\n for (const table of db.tables) {\n await table.clear();\n }\n }\n\n if (options.noTransaction) {\n await importAll();\n } else {\n await db.transaction('rw', db.tables, importAll);\n } \n\n async function importAll () {\n do {\n for (const tableExport of dbExport.data) {\n if (!tableExport.rows) break; // Need to pull more!\n if (!(tableExport.rows as any).incomplete && tableExport.rows.length === 0)\n continue;\n\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const tableName = tableExport.tableName;\n const table = db.table(tableName);\n const tableSchemaStr = dbExport.tables.filter(t => t.name === tableName)[0].schema;\n if (!table) {\n if (!options!.acceptMissingTables)\n throw new Error(`Exported table ${tableExport.tableName} is missing in installed database`);\n else\n continue;\n }\n if (!options!.acceptChangedPrimaryKey &&\n tableSchemaStr.split(',')[0] != table.schema.primKey.src) {\n throw new Error(`Primary key differs for table ${tableExport.tableName}. `);\n }\n\n const sourceRows = tableExport.rows\n \n // Our rows may be partial, so we need to ensure each one is completed before using it\n const rows: any[] = [];\n for(let i = 0; i < sourceRows.length; i++) {\n const obj = sourceRows[i];\n if (!obj.incomplete) {\n rows.push(TSON.revive(obj));\n } else {\n break;\n }\n }\n\n const filter = options!.filter;\n const filteredRows = filter ?\n tableExport.inbound ?\n rows.filter(value => filter(tableName, value)) :\n rows.filter(([key, value]) => filter(tableName, value, key)) :\n rows;\n const [keys, values] = tableExport.inbound ?\n [undefined, filteredRows] :\n [filteredRows.map(row=>row[0]), rows.map(row=>row[1])];\n\n if (options!.overwriteValues)\n await table.bulkPut(values, keys);\n else\n await table.bulkAdd(values, keys);\n \n progress.completedRows += rows.length;\n if (!(rows as any).incomplete) {\n progress.completedTables += 1;\n }\n sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance.\n }\n\n // Avoid unnescessary loops in \"for (const tableExport of dbExport.data)\" \n while (dbExport.data.length > 0 && dbExport.data[0].rows && !(dbExport.data[0].rows as any).incomplete) {\n // We've already imported all rows from the first table. Delete its occurrence\n dbExport.data.splice(0, 1); \n }\n if (!jsonStream.done() && !jsonStream.eof()) {\n // Pull some more (keeping transaction alive)\n if (readBlobsSynchronously) {\n // If we can pull from blob synchronically, we don't have to\n // keep transaction alive using Dexie.waitFor().\n // This will only be possible in workers.\n jsonStream.pullSync(CHUNK_SIZE);\n } else {\n await Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE));\n }\n } else break;\n } while (true)\n }\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n}\n\nasync function loadUntilWeGotEnoughData(exportedData: Blob | JsonStream, CHUNK_SIZE: number): Promise> {\n const stream = ('slice' in exportedData ?\n JsonStream(exportedData) :\n exportedData);\n\n while (!stream.eof()) {\n await stream.pullAsync(CHUNK_SIZE);\n\n if (stream.result.data && stream.result.data!.data)\n break;\n }\n const dbExportFile = stream.result;\n if (!dbExportFile || dbExportFile.formatName != \"dexie\")\n throw new Error(`Given file is not a dexie export`);\n if (dbExportFile.formatVersion! > VERSION) {\n throw new Error(`Format version ${dbExportFile.formatVersion} not supported`);\n }\n if (!dbExportFile.data!) {\n throw new Error(`No data in export file`);\n }\n if (!dbExportFile.data!.databaseName) {\n throw new Error(`Missing databaseName in export file`);\n }\n if (!dbExportFile.data!.databaseVersion) {\n throw new Error(`Missing databaseVersion in export file`);\n }\n if (!dbExportFile.data!.tables) {\n throw new Error(`Missing tables in export file`);\n }\n return stream; \n}\n","import Dexie from 'dexie';\nimport { ExportOptions, exportDB } from './export';\nimport { importDB, peakImportFile, ImportOptions, importInto, StaticImportOptions } from './import';\nimport { DexieExportJsonMeta } from './json-structure';\n\nexport { exportDB, ExportOptions};\nexport { importDB, importInto, peakImportFile, ImportOptions, DexieExportJsonMeta};\n\n//\n// Extend Dexie interface (typescript-wise)\n//\ndeclare module 'dexie' {\n // Extend methods on db\n interface Dexie {\n export(options?: ExportOptions): Promise;\n import(blob: Blob, options?: ImportOptions): Promise;\n }\n interface DexieConstructor {\n import(blob: Blob, options?: StaticImportOptions): Promise;\n }\n}\n\n//\n// Extend Dexie interface (runtime wise)\n//\n\nDexie.prototype.export = function (this: Dexie, options?: ExportOptions) {\n return exportDB(this, options);\n};\nDexie.prototype.import = function (this: Dexie, blob: Blob, options?: ImportOptions) {\n return importInto(this, blob, options);\n};\nDexie.import = (blob: Blob, options?: StaticImportOptions) => importDB(blob, options);\n\nexport default ()=>{\n throw new Error(\"This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options.\")\n};\n"],"names":["this","_typeof","obj","Symbol","iterator","constructor","prototype","_classCallCheck","instance","Constructor","TypeError","_defineProperties","target","props","i","length","descriptor","enumerable","configurable","writable","Object","defineProperty","key","_defineProperty","value","ownKeys","object","enumerableOnly","keys","getOwnPropertySymbols","symbols","filter","sym","getOwnPropertyDescriptor","push","apply","_objectSpread2","arguments","source","forEach","getOwnPropertyDescriptors","defineProperties","_slicedToArray","arr","_arrayWithHoles","Array","isArray","_iterableToArrayLimit","_arr","_n","_d","_e","undefined","_s","_i","next","done","err","_unsupportedIterableToArray","_nonIterableRest","_toConsumableArray","_arrayWithoutHoles","_arrayLikeToArray","_iterableToArray","iter","from","_nonIterableSpread","o","minLen","n","toString","call","slice","name","test","len","arr2","TypesonPromise","f","p","Promise","__typeson__type__","toStringTag","then","onFulfilled","onRejected","_this","typesonResolve","typesonReject","res","reject","resolve","v","meth","promArr","map","prom","toStr","hasOwn$1","hasOwnProperty","getProto","getPrototypeOf","fnToString","isThenable","catchCheck","isObject","val","hasConstructorOf","a","b","proto","Ctor","isPlainObject","escapeKeyPathComponent","keyPathComponent","replace","unescapeKeyPathComponent","getByKeyPath","keyPath","period","indexOf","innerObj","setAtKeyPath","_await","direct","hasOwn","internalStateObjPropsToIgnore","_async","args","e","nestedPathsFirst","keypath","as","match","bs","Typeson","options","plainObjectReplacers","nonplainObjectReplacers","revivers","types","_createClass","protoProps","staticProps","stringify","replacer","space","opts","stringification","encapsulated","encapsulate","JSON","stringifySync","throwOnBadSyncType","sync","stringifyAsync","parse","text","reviver","revive","parseSync","parseAsync","specialTypeNames","stateObj","returnTypeNames","rootTypeName","iterateNone","checkPromises","ret","promisesData","all","pd","promResults","promResult","_exit","newPromisesData","_promisesData$splice2","splice","_prData","cyclic","parentObj","detectedType","encaps","_encapsulate","isTypesonPromise","_invoke","body","result","encaps2","_result","that","refObjs","refKeys","promisesDataRoot","encapsulateObserver","finish","typeNames","values","getJSONType","Set","$types","$","_adaptBuiltinStateObjectProperties","ownKeysObj","cb","assign","vals","prop","tmp","resolvingTypesonPromise","observerData","$typeof","runObserver","type","awaitingTypesonPromise","includes","Number","isNaN","NEGATIVE_INFINITY","POSITIVE_INFINITY","replaced","iterateIn","iterateUnsetNumeric","refIndex","cyclicKeypath","clone","isPlainObj","isArr","ArrayBuffer","addLength","_loop","kp","Boolean","endIterateIn","end","endIterateOwn","vl","_loop2","endIterateUnsetNumeric","plainObject","replacers","existing","concat","replaceAsync","replacing","typeDetected","encapsulateSync","encapsulateAsync","keyPathResolutions","ignore$Types","executeReviver","Error","reviveAsync","revivalPromises","checkUndefined","retrn","Undefined","possibleTypesonPromise","revivePlainObjects","plainObjectTypes","entries","_ref3","_ref4","plain","sort","reduce","reducer","_ref7","newVal","_revive","_clone","k","set","_keyPathResolutions$","_target","_clone2","_ret","typ","r","_ref8","reviveSync","register","typeSpecSets","R","typeSpec","typSpec","typeId","JSON_TYPES","spec","testPlainObjects","existingReplacer","Class","x","create","_spec2","replacerObj","bind","start","fallback","reviverObj","isUserObject","userObject","s","arrayNonindexKeys","some","String","parseInt","sparseUndefined","undef","primitiveObjects","StringObject","BooleanObject","NumberObject","specialNumbers","nan","NaN","infinity","negativeInfinity","date","dt","time","getTime","Date","regexp","rexp","flags","global","ignoreCase","multiline","sticky","unicode","RegExp","mp","Map","st","chars","lookup","Uint8Array","charCodeAt","encode","arraybuffer","byteOffset","lngth","byteLength","bytes","base64","decode","encoded1","encoded2","encoded3","encoded4","bufferLength","_i2","buffers","index","b64","buffer","_global","self","typedArrays","typeName","arrType","TypedArray","toLowerCase","l","encoded","b64Obj","dataview","DataView","intlTypes","IntlCollator","Intl","Collator","c","resolvedOptions","locale","IntlDateTimeFormat","DateTimeFormat","dtf","IntlNumberFormat","NumberFormat","nf","string2arraybuffer","str","array","file","req","XMLHttpRequest","overrideMimeType","open","URL","createObjectURL","send","status","stringContents","responseText","lastModified","File","reader","FileReader","addEventListener","error","readAsBinaryString","bigint","BigInt","bigintObject","cryptokey","extractable","crypto","subtle","exportKey","jwk","algorithm","usages","importKey","imagedata","d","data","width","height","ImageData","Uint8ClampedArray","imagebitmap","dataset","bm","canvas","document","createElement","getContext","drawImage","toDataURL","ctx","img","src","createImageBitmap","filelist","fl","item","_files","blob","Blob","StructuredCloning","typedArray","encodeB64","decodeB64","Dexie","require$$0","clarinet"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAA;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AAuDA;IACO,SAAS,SAAS,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,EAAE,SAAS,EAAE;IAC7D,IAAI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AM,EAAE;IAC9B,wBAAA,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IAClD,qBAAA;IACD,oBAAA,OAAA,CAAA,CAAA,aAAO,MAAM,CAAC,CAAA;;;;IACf;;IClMD;IACA;IACA;AAEAA,6BAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,OAAuB,EAAA;IACrE,IAAA,OAAO,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACjC,CAAC,CAAC;AACFA,6BAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,IAAU,EAAE,OAAuB,EAAA;QACjF,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IACzC,CAAC,CAAC;AACFA,6BAAK,CAAC,MAAM,GAAG,UAAC,IAAU,EAAE,OAA6B,EAAA,EAAK,OAAA,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA,EAAA,CAAC;AAEtF,4BAAe,CAAA,YAAA;IACb,IAAA,MAAM,IAAI,KAAK,CAAC,kHAAkH,CAAC,CAAA;IACrI,CAAC;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/addons/dexie-export-import/dist/dexie-export-import.mjs b/addons/dexie-export-import/dist/dexie-export-import.mjs new file mode 100644 index 000000000..64bdd9b72 --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.mjs @@ -0,0 +1,3441 @@ +/* ========================================================================== + * dexie-export-import.js + * ========================================================================== + * + * Dexie addon for exporting and importing databases to / from Blobs. + * + * By David Fahlander, david.fahlander@gmail.com, + * + * ========================================================================== + * + * Version 4.0.7, Wed Oct 18 2023 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + * + */ + +import Dexie from 'dexie'; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, 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 }; + } +} + +function getSchemaString(table) { + var primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes); + return primKeyAndIndexes.map(function (index) { return index.src; }).join(','); +} +function extractDbSchema(exportedDb) { + var schema = {}; + for (var _i = 0, _a = exportedDb.tables; _i < _a.length; _i++) { + var table = _a[_i]; + schema[table.name] = table.schema; + } + return schema; +} +function readBlobAsync(blob, type) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onabort = function (ev) { return reject(new Error("file read aborted")); }; + reader.onerror = function (ev) { return reject(ev.target.error); }; + reader.onload = function (ev) { return resolve(ev.target.result); }; + if (type === 'binary') + reader.readAsArrayBuffer(blob); + else + reader.readAsText(blob); + }); +} +function readBlobSync(blob, type) { + if (typeof FileReaderSync === 'undefined') { + throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.'); + } + var reader = new FileReaderSync(); // Requires worker environment + var data = type === 'binary' ? + reader.readAsArrayBuffer(blob) : + reader.readAsText(blob); + return data; +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; +} + +var typeson = createCommonjsModule(function (module, exports) { +(function (global, factory) { + module.exports = factory() ; +}(commonjsGlobal, (function () { + function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } + } + + function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; + } + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; + } + + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; + } + + function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } + } + + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); + } + + function _iterableToArrayLimit(arr, i) { + if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { + return; + } + + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); + } + + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + + /** + * We keep this function minimized so if using two instances of this + * library, where one is minimized and one is not, it will still work + * with `hasConstructorOf`. + * With ES6 classes, we may be able to simply use `class TypesonPromise + * extends Promise` and add a string tag for detection. + * @param {function} f + */ + // eslint-disable-next-line max-len + // eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new + var TypesonPromise = function TypesonPromise(f) { + _classCallCheck(this, TypesonPromise); + + this.p = new Promise(f); + }; // eslint-disable-next-line max-len + // class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi + + + TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill + + /* istanbul ignore else */ + + if (typeof Symbol !== 'undefined') { + // Ensure `isUserObject` will return `false` for `TypesonPromise` + TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise'; + } + /** + * + * @param {function} [onFulfilled] + * @param {function} [onRejected] + * @returns {TypesonPromise} + */ + + + TypesonPromise.prototype.then = function (onFulfilled, onRejected) { + var _this = this; + + return new TypesonPromise(function (typesonResolve, typesonReject) { + // eslint-disable-next-line promise/catch-or-return + _this.p.then(function (res) { + // eslint-disable-next-line promise/always-return + typesonResolve(onFulfilled ? onFulfilled(res) : res); + })["catch"](function (res) { + return onRejected ? onRejected(res) : Promise.reject(res); + }).then(typesonResolve, typesonReject); + }); + }; + /** + * + * @param {function} onRejected + * @returns {TypesonPromise} + */ + + + TypesonPromise.prototype["catch"] = function (onRejected) { + return this.then(null, onRejected); + }; + /** + * + * @param {Any} v + * @returns {TypesonPromise} + */ + + + TypesonPromise.resolve = function (v) { + return new TypesonPromise(function (typesonResolve) { + typesonResolve(v); + }); + }; + /** + * + * @param {Any} v + * @returns {TypesonPromise} + */ + + + TypesonPromise.reject = function (v) { + return new TypesonPromise(function (typesonResolve, typesonReject) { + typesonReject(v); + }); + }; + + ['all', 'race'].forEach(function (meth) { + /** + * + * @param {Promise[]} promArr + * @returns {TypesonPromise} + */ + TypesonPromise[meth] = function (promArr) { + return new TypesonPromise(function (typesonResolve, typesonReject) { + // eslint-disable-next-line promise/catch-or-return + Promise[meth](promArr.map(function (prom) { + return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom; + })).then(typesonResolve, typesonReject); + }); + }; + }); + + var _ref = {}, + toStr = _ref.toString, + hasOwn = {}.hasOwnProperty, + getProto = Object.getPrototypeOf, + fnToString = hasOwn.toString; + /** + * Second argument not in use internally, but provided for utility. + * @param {Any} v + * @param {boolean} catchCheck + * @returns {boolean} + */ + + function isThenable(v, catchCheck) { + return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v["catch"] === 'function'); + } + /** + * + * @param {Any} val + * @returns {string} + */ + + + function toStringTag(val) { + return toStr.call(val).slice(8, -1); + } + /** + * This function is dependent on both constructors + * being identical so any minimization is expected of both. + * @param {Any} a + * @param {function} b + * @returns {boolean} + */ + + + function hasConstructorOf(a, b) { + if (!a || _typeof(a) !== 'object') { + return false; + } + + var proto = getProto(a); + + if (!proto) { + return b === null; + } + + var Ctor = hasOwn.call(proto, 'constructor') && proto.constructor; + + if (typeof Ctor !== 'function') { + return b === null; + } + + if (b === Ctor) { + return true; + } + + if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) { + return true; + } + + if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) { + return true; + } + + return false; + } + /** + * + * @param {Any} val + * @returns {boolean} + */ + + + function isPlainObject(val) { + // Mirrors jQuery's + if (!val || toStringTag(val) !== 'Object') { + return false; + } + + var proto = getProto(val); + + if (!proto) { + // `Object.create(null)` + return true; + } + + return hasConstructorOf(val, Object); + } + /** + * + * @param {Any} val + * @returns {boolean} + */ + + + function isUserObject(val) { + if (!val || toStringTag(val) !== 'Object') { + return false; + } + + var proto = getProto(val); + + if (!proto) { + // `Object.create(null)` + return true; + } + + return hasConstructorOf(val, Object) || isUserObject(proto); + } + /** + * + * @param {Any} v + * @returns {boolean} + */ + + + function isObject(v) { + return v && _typeof(v) === 'object'; + } + /** + * + * @param {string} keyPathComponent + * @returns {string} + */ + + + function escapeKeyPathComponent(keyPathComponent) { + return keyPathComponent.replace(/~/g, '~0').replace(/\./g, '~1'); + } + /** + * + * @param {string} keyPathComponent + * @returns {string} + */ + + + function unescapeKeyPathComponent(keyPathComponent) { + return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~'); + } + /** + * @param {PlainObject|GenericArray} obj + * @param {string} keyPath + * @returns {Any} + */ + + + function getByKeyPath(obj, keyPath) { + if (keyPath === '') { + return obj; + } + + var period = keyPath.indexOf('.'); + + if (period > -1) { + var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; + return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1)); + } + + return obj[unescapeKeyPathComponent(keyPath)]; + } + /** + * + * @param {PlainObject} obj + * @param {string} keyPath + * @param {Any} value + * @returns {Any} + */ + + + function setAtKeyPath(obj, keyPath, value) { + if (keyPath === '') { + return value; + } + + var period = keyPath.indexOf('.'); + + if (period > -1) { + var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))]; + return setAtKeyPath(innerObj, keyPath.slice(period + 1), value); + } + + obj[unescapeKeyPathComponent(keyPath)] = value; + return obj; + } + /** + * + * @param {external:JSON} value + * @returns {"null"|"array"|"undefined"|"boolean"|"number"|"string"| + * "object"|"symbol"} + */ + + + function getJSONType(value) { + return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof(value); + } + + var keys = Object.keys, + isArray = Array.isArray, + hasOwn$1 = {}.hasOwnProperty, + internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric']; + /** + * Handle plain object revivers first so reference setting can use + * revived type (e.g., array instead of object); assumes revived + * has same structure or will otherwise break subsequent references. + * @param {PlainObjectType} a + * @param {PlainObjectType} b + * @returns {1|-1|boolean} + */ + + function nestedPathsFirst(a, b) { + if (a.keypath === '') { + return -1; + } + + var as = a.keypath.match(/\./g) || 0; + var bs = b.keypath.match(/\./g) || 0; + + if (as) { + as = as.length; + } + + if (bs) { + bs = bs.length; + } + + return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath; + } + /** + * An instance of this class can be used to call `stringify()` and `parse()`. + * Typeson resolves cyclic references by default. Can also be extended to + * support custom types using the register() method. + * + * @class + * @param {{cyclic: boolean}} [options] - if cyclic (default true), + * cyclic references will be handled gracefully. + */ + + + var Typeson = + /*#__PURE__*/ + function () { + function Typeson(options) { + _classCallCheck(this, Typeson); + + this.options = options; // Replacers signature: replace (value). Returns falsy if not + // replacing. Otherwise ['Date', value.getTime()] + + this.plainObjectReplacers = []; + this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}]. + // Sample: [{'Date': value => new Date(value)}, {plain: false}] + + this.revivers = {}; + /** Types registered via `register()`. */ + + this.types = {}; + } + /** + * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON + */ + + /** + * @callback JSONReplacer + * @param {""|string} key + * @param {JSON} value + * @returns {number|string|boolean|null|PlainObject|undefined} + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter + */ + + /** + * Serialize given object to Typeson. + * Initial arguments work identical to those of `JSON.stringify`. + * The `replacer` argument has nothing to do with our replacers. + * @param {Any} obj + * @param {JSONReplacer|string[]} replacer + * @param {number|string} space + * @param {object} opts + * @returns {string|Promise} Promise resolves to a string + */ + + + _createClass(Typeson, [{ + key: "stringify", + value: function stringify(obj, replacer, space, opts) { + opts = _objectSpread2({}, this.options, {}, opts, { + stringification: true + }); + var encapsulated = this.encapsulate(obj, null, opts); + + if (isArray(encapsulated)) { + return JSON.stringify(encapsulated[0], replacer, space); + } + + return encapsulated.then(function (res) { + return JSON.stringify(res, replacer, space); + }); + } + /** + * Also sync but throws on non-sync result. + * @param {Any} obj + * @param {JSONReplacer|string[]} replacer + * @param {number|string} space + * @param {object} opts + * @returns {string} + */ + + }, { + key: "stringifySync", + value: function stringifySync(obj, replacer, space, opts) { + return this.stringify(obj, replacer, space, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * + * @param {Any} obj + * @param {JSONReplacer|string[]} replacer + * @param {number|string} space + * @param {object} opts + * @returns {Promise} + */ + + }, { + key: "stringifyAsync", + value: function stringifyAsync(obj, replacer, space, opts) { + return this.stringify(obj, replacer, space, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * Parse Typeson back into an obejct. + * Initial arguments works identical to those of `JSON.parse()`. + * @param {string} text + * @param {function} reviver This JSON reviver has nothing to do with + * our revivers. + * @param {object} opts + * @returns {external:JSON} + */ + + }, { + key: "parse", + value: function parse(text, reviver, opts) { + opts = _objectSpread2({}, this.options, {}, opts, { + parse: true + }); + return this.revive(JSON.parse(text, reviver), opts); + } + /** + * Also sync but throws on non-sync result. + * @param {string} text + * @param {function} reviver This JSON reviver has nothing to do with + * our revivers. + * @param {object} opts + * @returns {external:JSON} + */ + + }, { + key: "parseSync", + value: function parseSync(text, reviver, opts) { + return this.parse(text, reviver, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * @param {string} text + * @param {function} reviver This JSON reviver has nothing to do with + * our revivers. + * @param {object} opts + * @returns {Promise} Resolves to `external:JSON` + */ + + }, { + key: "parseAsync", + value: function parseAsync(text, reviver, opts) { + return this.parse(text, reviver, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * + * @param {Any} obj + * @param {object} stateObj + * @param {object} [opts={}] + * @returns {string[]|false} + */ + + }, { + key: "specialTypeNames", + value: function specialTypeNames(obj, stateObj) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + opts.returnTypeNames = true; + return this.encapsulate(obj, stateObj, opts); + } + /** + * + * @param {Any} obj + * @param {PlainObject} stateObj + * @param {PlainObject} [opts={}] + * @returns {Promise|GenericArray|PlainObject|string|false} + */ + + }, { + key: "rootTypeName", + value: function rootTypeName(obj, stateObj) { + var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + opts.iterateNone = true; + return this.encapsulate(obj, stateObj, opts); + } + /** + * Encapsulate a complex object into a plain Object by replacing + * registered types with plain objects representing the types data. + * + * This method is used internally by `Typeson.stringify()`. + * @param {Any} obj - Object to encapsulate. + * @param {PlainObject} stateObj + * @param {PlainObject} opts + * @returns {Promise|GenericArray|PlainObject|string|false} + */ + + }, { + key: "encapsulate", + value: function encapsulate(obj, stateObj, opts) { + opts = _objectSpread2({ + sync: true + }, this.options, {}, opts); + var _opts = opts, + sync = _opts.sync; + var that = this, + types = {}, + refObjs = [], + // For checking cyclic references + refKeys = [], + // For checking cyclic references + promisesDataRoot = []; // Clone the object deeply while at the same time replacing any + // special types or cyclic reference: + + var cyclic = 'cyclic' in opts ? opts.cyclic : true; + var _opts2 = opts, + encapsulateObserver = _opts2.encapsulateObserver; + + var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot); + /** + * + * @param {Any} ret + * @returns {GenericArray|PlainObject|string|false} + */ + + + function finish(ret) { + // Add `$types` to result only if we ever bumped into a + // special type (or special case where object has own `$types`) + var typeNames = Object.values(types); + + if (opts.iterateNone) { + if (typeNames.length) { + return typeNames[0]; + } + + return Typeson.getJSONType(ret); + } + + if (typeNames.length) { + if (opts.returnTypeNames) { + return _toConsumableArray(new Set(typeNames)); + } // Special if array (or a primitive) was serialized + // because JSON would ignore custom `$types` prop on it + + + if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its + // own `$types` property (to avoid ambiguity) + hasOwn$1.call(ret, '$types')) { + ret = { + $: ret, + $types: { + $: types + } + }; + } else { + ret.$types = types; + } // No special types + + } else if (isObject(ret) && hasOwn$1.call(ret, '$types')) { + ret = { + $: ret, + $types: true + }; + } + + if (opts.returnTypeNames) { + return false; + } + + return ret; + } + /** + * + * @param {Any} ret + * @param {GenericArray} promisesData + * @returns {Promise} + */ + + + function checkPromises(_x, _x2) { + return _checkPromises.apply(this, arguments); + } + /** + * + * @param {object} stateObj + * @param {object} ownKeysObj + * @param {function} cb + * @returns {undefined} + */ + + + function _checkPromises() { + _checkPromises = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee2(ret, promisesData) { + var promResults; + return regeneratorRuntime.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return Promise.all(promisesData.map(function (pd) { + return pd[1].p; + })); + + case 2: + promResults = _context2.sent; + _context2.next = 5; + return Promise.all(promResults.map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(promResult) { + var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2; + + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + newPromisesData = []; + _promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0]; + _prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6]; + encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType); + isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself + // returns a `Typeson.Promise` + + if (!(keyPath && isTypesonPromise)) { + _context.next = 11; + break; + } + + _context.next = 8; + return encaps.p; + + case 8: + encaps2 = _context.sent; + parentObj[key] = encaps2; + return _context.abrupt("return", checkPromises(ret, newPromisesData)); + + case 11: + if (keyPath) { + parentObj[key] = encaps; + } else if (isTypesonPromise) { + ret = encaps.p; + } else { + // If this is itself a `Typeson.Promise` (because the + // original value supplied was a `Promise` or + // because the supplied custom type value resolved + // to one), returning it below will be fine since + // a `Promise` is expected anyways given current + // config (and if not a `Promise`, it will be ready + // as the resolve value) + ret = encaps; + } + + return _context.abrupt("return", checkPromises(ret, newPromisesData)); + + case 13: + case "end": + return _context.stop(); + } + } + }, _callee); + })); + + return function (_x3) { + return _ref.apply(this, arguments); + }; + }())); + + case 5: + return _context2.abrupt("return", ret); + + case 6: + case "end": + return _context2.stop(); + } + } + }, _callee2); + })); + return _checkPromises.apply(this, arguments); + } + + function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) { + Object.assign(stateObj, ownKeysObj); + var vals = internalStateObjPropsToIgnore.map(function (prop) { + var tmp = stateObj[prop]; + delete stateObj[prop]; + return tmp; + }); // eslint-disable-next-line callback-return + + cb(); + internalStateObjPropsToIgnore.forEach(function (prop, i) { + stateObj[prop] = vals[i]; + }); + } + /** + * + * @param {string} keypath + * @param {Any} value + * @param {boolean} cyclic + * @param {PlainObject} stateObj + * @param {boolean} promisesData + * @param {boolean} resolvingTypesonPromise + * @param {string} detectedType + * @returns {Any} + */ + + + function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) { + var ret; + var observerData = {}; + + var $typeof = _typeof(value); + + var runObserver = encapsulateObserver ? function (obj) { + var type = detectedType || stateObj.type || Typeson.getJSONType(value); + encapsulateObserver(Object.assign(obj || observerData, { + keypath: keypath, + value: value, + cyclic: cyclic, + stateObj: stateObj, + promisesData: promisesData, + resolvingTypesonPromise: resolvingTypesonPromise, + awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise) + }, { + type: type + })); + } : null; + + if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) { + if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) { + if (stateObj.replaced) { + ret = value; + } else { + ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver); + } + + if (ret !== value) { + observerData = { + replaced: ret + }; + } + } else { + ret = value; + } + + if (runObserver) { + runObserver(); + } + + return ret; + } + + if (value === null) { + if (runObserver) { + runObserver(); + } + + return value; + } + + if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') { + // Options set to detect cyclic references and be able + // to rewrite them. + var refIndex = refObjs.indexOf(value); + + if (refIndex < 0) { + if (cyclic === true) { + refObjs.push(value); + refKeys.push(keypath); + } + } else { + types[keypath] = '#'; + + if (runObserver) { + runObserver({ + cyclicKeypath: refKeys[refIndex] + }); + } + + return '#' + refKeys[refIndex]; + } + } + + var isPlainObj = isPlainObject(value); + var isArr = isArray(value); + var replaced = // Running replace will cause infinite loop as will test + // positive again + (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object + // replacers, don't try finding a replacer + value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver); + var clone; + + if (replaced !== value) { + ret = replaced; + observerData = { + replaced: replaced + }; + } else { + // eslint-disable-next-line no-lonely-if + if (keypath === '' && hasConstructorOf(value, TypesonPromise)) { + promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]); + ret = value; + } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') { + clone = new Array(value.length); + observerData = { + clone: clone + }; + } else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') { + clone = {}; + + if (stateObj.addLength) { + clone.length = value.length; + } + + observerData = { + clone: clone + }; + } else { + ret = value; // Only clone vanilla objects and arrays + } + } + + if (runObserver) { + runObserver(); + } + + if (opts.iterateNone) { + return clone || ret; + } + + if (!clone) { + return ret; + } // Iterate object or array + + + if (stateObj.iterateIn) { + var _loop = function _loop(key) { + var ownKeysObj = { + ownKeys: hasOwn$1.call(value, key) + }; + + _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { + var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key); + + var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); + + if (hasConstructorOf(val, TypesonPromise)) { + promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); + } else if (val !== undefined) { + clone[key] = val; + } + }); + }; + + // eslint-disable-next-line guard-for-in + for (var key in value) { + _loop(key); + } + + if (runObserver) { + runObserver({ + endIterateIn: true, + end: true + }); + } + } else { + // Note: Non-indexes on arrays won't survive stringify so + // somewhat wasteful for arrays, but so too is iterating + // all numeric indexes on sparse arrays when not wanted + // or filtering own keys for positive integers + keys(value).forEach(function (key) { + var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key); + var ownKeysObj = { + ownKeys: true + }; + + _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { + var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); + + if (hasConstructorOf(val, TypesonPromise)) { + promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]); + } else if (val !== undefined) { + clone[key] = val; + } + }); + }); + + if (runObserver) { + runObserver({ + endIterateOwn: true, + end: true + }); + } + } // Iterate array for non-own numeric properties (we can't + // replace the prior loop though as it iterates non-integer + // keys) + + + if (stateObj.iterateUnsetNumeric) { + var vl = value.length; + + var _loop2 = function _loop2(i) { + if (!(i in value)) { + // No need to escape numeric + var kp = keypath + (keypath ? '.' : '') + i; + var ownKeysObj = { + ownKeys: false + }; + + _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () { + var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise); + + if (hasConstructorOf(val, TypesonPromise)) { + promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]); + } else if (val !== undefined) { + clone[i] = val; + } + }); + } + }; + + for (var i = 0; i < vl; i++) { + _loop2(i); + } + + if (runObserver) { + runObserver({ + endIterateUnsetNumeric: true, + end: true + }); + } + } + + return clone; + } + /** + * + * @param {string} keypath + * @param {Any} value + * @param {PlainObject} stateObj + * @param {GenericArray} promisesData + * @param {boolean} plainObject + * @param {boolean} resolvingTypesonPromise + * @param {function} [runObserver] + * @returns {*} + */ + + + function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) { + // Encapsulate registered types + var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers; + var i = replacers.length; + + while (i--) { + var replacer = replacers[i]; + + if (replacer.test(value, stateObj)) { + var type = replacer.type; + + if (that.revivers[type]) { + // Record the type only if a corresponding reviver + // exists. This is to support specs where only + // replacement is done. + // For example, ensuring deep cloning of the object, + // or replacing a type to its equivalent without + // the need to revive it. + var existing = types[keypath]; // type can comprise an array of types (see test + // "should support intermediate types") + + types[keypath] = existing ? [type].concat(existing) : type; + } + + Object.assign(stateObj, { + type: type, + replaced: true + }); + + if ((sync || !replacer.replaceAsync) && !replacer.replace) { + if (runObserver) { + runObserver({ + typeDetected: true + }); + } + + return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type); + } + + if (runObserver) { + runObserver({ + replacing: true + }); + } // Now, also traverse the result in case it contains its + // own types to replace + + + var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync'; + return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type); + } + } + + return value; + } + + return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Sync method requested but async result obtained'); + }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Async method requested but sync result obtained'); + }() // If this is a synchronous request for stringification, yet + // a promise is the result, we don't want to resolve leading + // to an async result, so we return an array to avoid + // ambiguity + : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret)); + } + /** + * Also sync but throws on non-sync result. + * @param {*} obj + * @param {object} stateObj + * @param {object} opts + * @returns {*} + */ + + }, { + key: "encapsulateSync", + value: function encapsulateSync(obj, stateObj, opts) { + return this.encapsulate(obj, stateObj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * @param {*} obj + * @param {object} stateObj + * @param {object} opts + * @returns {*} + */ + + }, { + key: "encapsulateAsync", + value: function encapsulateAsync(obj, stateObj, opts) { + return this.encapsulate(obj, stateObj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * Revive an encapsulated object. + * This method is used internally by `Typeson.parse()`. + * @param {object} obj - Object to revive. If it has `$types` member, the + * properties that are listed there will be replaced with its true type + * instead of just plain objects. + * @param {object} opts + * @throws TypeError If mismatch between sync/async type and result + * @returns {Promise|*} If async, returns a Promise that resolves to `*` + */ + + }, { + key: "revive", + value: function revive(obj, opts) { + var types = obj && obj.$types; // No type info added. Revival not needed. + + if (!types) { + return obj; + } // Object happened to have own `$types` property but with + // no actual types, so we unescape and return that object + + + if (types === true) { + return obj.$; + } + + opts = _objectSpread2({ + sync: true + }, this.options, {}, opts); + var _opts3 = opts, + sync = _opts3.sync; + var keyPathResolutions = []; + var stateObj = {}; + var ignore$Types = true; // Special when root object is not a trivial Object, it will + // be encapsulated in `$`. It will also be encapsulated in + // `$` if it has its own `$` property to avoid ambiguity + + if (types.$ && isPlainObject(types.$)) { + obj = obj.$; + types = types.$; + ignore$Types = false; + } + + var that = this; + /** + * @callback RevivalReducer + * @param {Any} value + * @param {string} type + * @returns {Any} + */ + + /** + * + * @param {string} type + * @param {Any} val + * @returns {[type]} [description] + */ + + function executeReviver(type, val) { + var _ref2 = that.revivers[type] || [], + _ref3 = _slicedToArray(_ref2, 1), + reviver = _ref3[0]; + + if (!reviver) { + throw new Error('Unregistered type: ' + type); + } // Only `sync` expected here, as problematic async would + // be missing both `reviver` and `reviverAsync`, and + // encapsulation shouldn't have added types, so + // should have made an early exit + + + if (sync && !('revive' in reviver)) { + // Just return value as is + return val; + } + + return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj); + } + /** + * + * @returns {void|TypesonPromise} + */ + + + function revivePlainObjects() { + // const references = []; + // const reviveTypes = []; + var plainObjectTypes = []; + Object.entries(types).forEach(function (_ref4) { + var _ref5 = _slicedToArray(_ref4, 2), + keypath = _ref5[0], + type = _ref5[1]; + + if (type === '#') { + /* + references.push({ + keypath, + reference: getByKeyPath(obj, keypath) + }); + */ + return; + } + + [].concat(type).forEach(function (type) { + var _ref6 = that.revivers[type] || [null, {}], + _ref7 = _slicedToArray(_ref6, 2), + plain = _ref7[1].plain; + + if (!plain) { + // reviveTypes.push({keypath, type}); + return; + } + + plainObjectTypes.push({ + keypath: keypath, + type: type + }); + delete types[keypath]; // Avoid repeating + }); + }); + + if (!plainObjectTypes.length) { + return undefined; + } // console.log(plainObjectTypes.sort(nestedPathsFirst)); + + /** + * @typedef {PlainObject} PlainObjectType + * @property {string} keypath + * @property {string} type + */ + + + return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) { + var keypath = _ref8.keypath, + type = _ref8.type; + + if (isThenable(possibleTypesonPromise)) { + return possibleTypesonPromise.then(function (val) { + return reducer(val, { + keypath: keypath, + type: type + }); + }); + } // console.log('obj', JSON.stringify(keypath), obj); + + + var val = getByKeyPath(obj, keypath); + val = executeReviver(type, val); + + if (hasConstructorOf(val, TypesonPromise)) { + return val.then(function (v) { + var newVal = setAtKeyPath(obj, keypath, v); + + if (newVal === v) { + obj = newVal; + } + + return undefined; + }); + } + + var newVal = setAtKeyPath(obj, keypath, val); + + if (newVal === val) { + obj = newVal; + } + + return undefined; + }, undefined // This argument must be explicit + ); // references.forEach(({keypath, reference}) => {}); + // reviveTypes.sort(nestedPathsFirst).forEach(() => {}); + } + + var revivalPromises = []; + /** + * + * @param {string} keypath + * @param {Any} value + * @param {?(Array|object)} target + * @param {Array|object} [clone] + * @param {string} [key] + * @returns {Any} + */ + + function _revive(keypath, value, target, clone, key) { + if (ignore$Types && keypath === '$types') { + return undefined; + } + + var type = types[keypath]; + var isArr = isArray(value); + + if (isArr || isPlainObject(value)) { + var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array + + + keys(value).forEach(function (k) { + var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k); + + var set = function set(v) { + if (hasConstructorOf(v, Undefined)) { + _clone[k] = undefined; + } else if (v !== undefined) { + _clone[k] = v; + } + + return v; + }; + + if (hasConstructorOf(val, TypesonPromise)) { + revivalPromises.push(val.then(function (ret) { + return set(ret); + })); + } else { + set(val); + } + }); + value = _clone; // Try to resolve cyclic reference as soon as available + + while (keyPathResolutions.length) { + var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4), + _target = _keyPathResolutions$[0], + keyPath = _keyPathResolutions$[1], + _clone2 = _keyPathResolutions$[2], + k = _keyPathResolutions$[3]; + + var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or + // `undefined` + + if (val !== undefined) { + _clone2[k] = val; + } else { + break; + } + + keyPathResolutions.splice(0, 1); + } + } + + if (!type) { + return value; + } + + if (type === '#') { + var _ret = getByKeyPath(target, value.slice(1)); + + if (_ret === undefined) { + // Cyclic reference not yet available + keyPathResolutions.push([target, value.slice(1), clone, key]); + } + + return _ret; + } // `type` can be an array here + + + return [].concat(type).reduce(function reducer(val, typ) { + if (hasConstructorOf(val, TypesonPromise)) { + return val.then(function (v) { + // TypesonPromise here too + return reducer(v, typ); + }); + } + + return executeReviver(typ, val); + }, value); + } + /** + * + * @param {Any} retrn + * @returns {undefined|Any} + */ + + + function checkUndefined(retrn) { + return hasConstructorOf(retrn, Undefined) ? undefined : retrn; + } + + var possibleTypesonPromise = revivePlainObjects(); + var ret; + + if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) { + ret = possibleTypesonPromise.then(function () { + return obj; + }); + } else { + ret = _revive('', obj, null); + + if (revivalPromises.length) { + // Ensure children resolved + ret = TypesonPromise.resolve(ret).then(function (r) { + return TypesonPromise.all([// May be a TypesonPromise or not + r].concat(revivalPromises)); + }).then(function (_ref9) { + var _ref10 = _slicedToArray(_ref9, 1), + r = _ref10[0]; + + return r; + }); + } + } + + return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Sync method requested but async result obtained'); + }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () { + throw new TypeError('Async method requested but sync result obtained'); + }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret)); + } + /** + * Also sync but throws on non-sync result. + * @param {Any} obj + * @param {object} opts + * @returns {Any} + */ + + }, { + key: "reviveSync", + value: function reviveSync(obj, opts) { + return this.revive(obj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: true + })); + } + /** + * @param {Any} obj + * @param {object} opts + * @returns {Promise} Resolves to `*` + */ + + }, { + key: "reviveAsync", + value: function reviveAsync(obj, opts) { + return this.revive(obj, _objectSpread2({ + throwOnBadSyncType: true + }, opts, { + sync: false + })); + } + /** + * Register types. + * For examples on how to use this method, see + * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}. + * @param {object.[]} typeSpecSets - Types and + * their functions [test, encapsulate, revive]; + * @param {object} opts + * @returns {Typeson} + */ + + }, { + key: "register", + value: function register(typeSpecSets, opts) { + opts = opts || {}; + [].concat(typeSpecSets).forEach(function R(typeSpec) { + var _this = this; + + // Allow arrays of arrays of arrays... + if (isArray(typeSpec)) { + return typeSpec.map(function (typSpec) { + return R.call(_this, typSpec); + }); + } + + typeSpec && keys(typeSpec).forEach(function (typeId) { + if (typeId === '#') { + throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects'); + } else if (Typeson.JSON_TYPES.includes(typeId)) { + throw new TypeError('Plain JSON object types are reserved as type names'); + } + + var spec = typeSpec[typeId]; + var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers; + var existingReplacer = replacers.filter(function (r) { + return r.type === typeId; + }); + + if (existingReplacer.length) { + // Remove existing spec and replace with this one. + replacers.splice(replacers.indexOf(existingReplacer[0]), 1); + delete this.revivers[typeId]; + delete this.types[typeId]; + } + + if (typeof spec === 'function') { + // Support registering just a class without replacer/reviver + var Class = spec; + spec = { + test: function test(x) { + return x && x.constructor === Class; + }, + replace: function replace(x) { + return _objectSpread2({}, x); + }, + revive: function revive(x) { + return Object.assign(Object.create(Class.prototype), x); + } + }; + } else if (isArray(spec)) { + var _spec = spec, + _spec2 = _slicedToArray(_spec, 3), + test = _spec2[0], + replace = _spec2[1], + revive = _spec2[2]; + + spec = { + test: test, + replace: replace, + revive: revive + }; + } + + if (!spec || !spec.test) { + return; + } + + var replacerObj = { + type: typeId, + test: spec.test.bind(spec) + }; + + if (spec.replace) { + replacerObj.replace = spec.replace.bind(spec); + } + + if (spec.replaceAsync) { + replacerObj.replaceAsync = spec.replaceAsync.bind(spec); + } + + var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Infinity; + + if (spec.testPlainObjects) { + this.plainObjectReplacers.splice(start, 0, replacerObj); + } else { + this.nonplainObjectReplacers.splice(start, 0, replacerObj); + } // Todo: We might consider a testAsync type + + + if (spec.revive || spec.reviveAsync) { + var reviverObj = {}; + + if (spec.revive) { + reviverObj.revive = spec.revive.bind(spec); + } + + if (spec.reviveAsync) { + reviverObj.reviveAsync = spec.reviveAsync.bind(spec); + } + + this.revivers[typeId] = [reviverObj, { + plain: spec.testPlainObjects + }]; + } // Record to be retrieved via public types property. + + + this.types[typeId] = spec; + }, this); + }, this); + return this; + } + }]); + + return Typeson; + }(); + /** + * We keep this function minimized so if using two instances of this + * library, where one is minimized and one is not, it will still work + * with `hasConstructorOf`. + * @class + */ + + + var Undefined = function Undefined() { + _classCallCheck(this, Undefined); + }; // eslint-disable-line space-before-blocks + + + Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values + // To insist `undefined` should be added + + Typeson.Undefined = Undefined; // To support async encapsulation/stringification + + Typeson.Promise = TypesonPromise; // Some fundamental type-checking utilities + + Typeson.isThenable = isThenable; + Typeson.toStringTag = toStringTag; + Typeson.hasConstructorOf = hasConstructorOf; + Typeson.isObject = isObject; + Typeson.isPlainObject = isPlainObject; + Typeson.isUserObject = isUserObject; + Typeson.escapeKeyPathComponent = escapeKeyPathComponent; + Typeson.unescapeKeyPathComponent = unescapeKeyPathComponent; + Typeson.getByKeyPath = getByKeyPath; + Typeson.getJSONType = getJSONType; + Typeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object']; + + return Typeson; + +}))); +}); + +var structuredCloning = createCommonjsModule(function (module, exports) { +!function(e,t){module.exports=t();}(commonjsGlobal,(function(){function _typeof$1(e){return (_typeof$1="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck$1(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties$1(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);re.length)&&(t=e.length);for(var r=0,n=new Array(t);r-1){var n=e[unescapeKeyPathComponent(t.slice(0,r))];return void 0===n?void 0:getByKeyPath(n,t.slice(r+1))}return e[unescapeKeyPathComponent(t)]}function setAtKeyPath(e,t,r){if(""===t)return r;var n=t.indexOf(".");return n>-1?setAtKeyPath(e[unescapeKeyPathComponent(t.slice(0,n))],t.slice(n+1),r):(e[unescapeKeyPathComponent(t)]=r,e)}function _await(e,t,r){return r?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}var o=Object.keys,a=Array.isArray,c={}.hasOwnProperty,u=["type","replaced","iterateIn","iterateUnsetNumeric"];function _async(e){return function(){for(var t=[],r=0;rn?-1:rt.keypath}var s=function(){function Typeson(e){_classCallCheck(this,Typeson),this.options=e,this.plainObjectReplacers=[],this.nonplainObjectReplacers=[],this.revivers={},this.types={};}return function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),e}(Typeson,[{key:"stringify",value:function stringify(e,t,r,n){n=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),n),{},{stringification:!0});var i=this.encapsulate(e,null,n);return a(i)?JSON.stringify(i[0],t,r):i.then((function(e){return JSON.stringify(e,t,r)}))}},{key:"stringifySync",value:function stringifySync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!0}))}},{key:"stringifyAsync",value:function stringifyAsync(e,t,r,n){return this.stringify(e,t,r,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},n),{},{sync:!1}))}},{key:"parse",value:function parse(e,t,r){return r=_objectSpread2(_objectSpread2(_objectSpread2({},this.options),r),{},{parse:!0}),this.revive(JSON.parse(e,t),r)}},{key:"parseSync",value:function parseSync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!0}))}},{key:"parseAsync",value:function parseAsync(e,t,r){return this.parse(e,t,_objectSpread2(_objectSpread2({throwOnBadSyncType:!0},r),{},{sync:!1}))}},{key:"specialTypeNames",value:function specialTypeNames(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.returnTypeNames=!0,this.encapsulate(e,t,r)}},{key:"rootTypeName",value:function rootTypeName(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.iterateNone=!0,this.encapsulate(e,t,r)}},{key:"encapsulate",value:function encapsulate(t,r,n){var i=_async((function(t,r){return _await(Promise.all(r.map((function(e){return e[1].p}))),(function(n){return _await(Promise.all(n.map(_async((function(n){var o=!1,a=[],c=_slicedToArray(r.splice(0,1),1),u=_slicedToArray(c[0],7),s=u[0],f=u[2],l=u[3],p=u[4],y=u[5],v=u[6],b=_encapsulate(s,n,f,l,a,!0,v),d=hasConstructorOf(b,e);return function _invoke(e,t){var r=e();return r&&r.then?r.then(t):t(r)}((function(){if(s&&d)return _await(b.p,(function(e){return p[y]=e,o=!0,i(t,a)}))}),(function(e){return o?e:(s?p[y]=b:t=d?b.p:b,i(t,a))}))})))),(function(){return t}))}))})),s=(n=_objectSpread2(_objectSpread2({sync:!0},this.options),n)).sync,f=this,l={},p=[],y=[],v=[],b=!("cyclic"in n)||n.cyclic,d=n.encapsulateObserver,h=_encapsulate("",t,b,r||{},v);function finish(e){var t=Object.values(l);if(n.iterateNone)return t.length?t[0]:Typeson.getJSONType(e);if(t.length){if(n.returnTypeNames)return _toConsumableArray(new Set(t));e&&isPlainObject(e)&&!c.call(e,"$types")?e.$types=l:e={$:e,$types:{$:l}};}else isObject(e)&&c.call(e,"$types")&&(e={$:e,$types:!0});return !n.returnTypeNames&&e}function _adaptBuiltinStateObjectProperties(e,t,r){Object.assign(e,t);var n=u.map((function(t){var r=e[t];return delete e[t],r}));r(),u.forEach((function(t,r){e[t]=n[r];}));}function _encapsulate(t,r,i,u,s,v,b){var h,g={},m=_typeof(r),O=d?function(n){var o=b||u.type||Typeson.getJSONType(r);d(Object.assign(n||g,{keypath:t,value:r,cyclic:i,stateObj:u,promisesData:s,resolvingTypesonPromise:v,awaitingTypesonPromise:hasConstructorOf(r,e)},{type:o}));}:null;if(["string","boolean","number","undefined"].includes(m))return void 0===r||Number.isNaN(r)||r===Number.NEGATIVE_INFINITY||r===Number.POSITIVE_INFINITY?(h=u.replaced?r:replace(t,r,u,s,!1,v,O))!==r&&(g={replaced:h}):h=r,O&&O(),h;if(null===r)return O&&O(),r;if(i&&!u.iterateIn&&!u.iterateUnsetNumeric&&r&&"object"===_typeof(r)){var _=p.indexOf(r);if(!(_<0))return l[t]="#",O&&O({cyclicKeypath:y[_]}),"#"+y[_];!0===i&&(p.push(r),y.push(t));}var j,S=isPlainObject(r),T=a(r),w=(S||T)&&(!f.plainObjectReplacers.length||u.replaced)||u.iterateIn?r:replace(t,r,u,s,S||T,null,O);if(w!==r?(h=w,g={replaced:w}):""===t&&hasConstructorOf(r,e)?(s.push([t,r,i,u,void 0,void 0,u.type]),h=r):T&&"object"!==u.iterateIn||"array"===u.iterateIn?(j=new Array(r.length),g={clone:j}):(["function","symbol"].includes(_typeof(r))||"toJSON"in r||hasConstructorOf(r,e)||hasConstructorOf(r,Promise)||hasConstructorOf(r,ArrayBuffer))&&!S&&"object"!==u.iterateIn?h=r:(j={},u.addLength&&(j.length=r.length),g={clone:j}),O&&O(),n.iterateNone)return j||h;if(!j)return h;if(u.iterateIn){var A=function _loop(n){var o={ownKeys:c.call(r,n)};_adaptBuiltinStateObjectProperties(u,o,(function(){var o=t+(t?".":"")+escapeKeyPathComponent(n),a=_encapsulate(o,r[n],Boolean(i),u,s,v);hasConstructorOf(a,e)?s.push([o,a,Boolean(i),u,j,n,u.type]):void 0!==a&&(j[n]=a);}));};for(var P in r)A(P);O&&O({endIterateIn:!0,end:!0});}else o(r).forEach((function(n){var o=t+(t?".":"")+escapeKeyPathComponent(n);_adaptBuiltinStateObjectProperties(u,{ownKeys:!0},(function(){var t=_encapsulate(o,r[n],Boolean(i),u,s,v);hasConstructorOf(t,e)?s.push([o,t,Boolean(i),u,j,n,u.type]):void 0!==t&&(j[n]=t);}));})),O&&O({endIterateOwn:!0,end:!0});if(u.iterateUnsetNumeric){for(var I=r.length,C=function _loop2(n){if(!(n in r)){var o=t+(t?".":"")+n;_adaptBuiltinStateObjectProperties(u,{ownKeys:!1},(function(){var t=_encapsulate(o,void 0,Boolean(i),u,s,v);hasConstructorOf(t,e)?s.push([o,t,Boolean(i),u,j,n,u.type]):void 0!==t&&(j[n]=t);}));}},N=0;N>2],o+=O[(3&n[a])<<4|n[a+1]>>4],o+=O[(15&n[a+1])<<2|n[a+2]>>6],o+=O[63&n[a+2]];return i%3==2?o=o.slice(0,-1)+"=":i%3==1&&(o=o.slice(0,-2)+"=="),o},T=function decode(e){var t,r,n,i,o=e.length,a=.75*e.length,c=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);for(var u=new ArrayBuffer(a),s=new Uint8Array(u),f=0;f>4,s[c++]=(15&r)<<4|n>>2,s[c++]=(3&n)<<6|63&i;return u},w={arraybuffer:{test:function test(e){return "ArrayBuffer"===s.toStringTag(e)},replace:function replace(e,t){t.buffers||(t.buffers=[]);var r=t.buffers.indexOf(e);return r>-1?{index:r}:(t.buffers.push(e),S(e))},revive:function revive(e,t){if(t.buffers||(t.buffers=[]),"object"===_typeof$1(e))return t.buffers[e.index];var r=T(e);return t.buffers.push(r),r}}},A="undefined"==typeof self?commonjsGlobal:self,P={};["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array"].forEach((function(e){var t=e,r=A[t];r&&(P[e.toLowerCase()]={test:function test(e){return s.toStringTag(e)===t},replace:function replace(e,t){var r=e.buffer,n=e.byteOffset,i=e.length;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(r);return o>-1?{index:o,byteOffset:n,length:i}:(t.buffers.push(r),{encoded:S(r),byteOffset:n,length:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var n,i=e.byteOffset,o=e.length,a=e.encoded,c=e.index;return "index"in e?n=t.buffers[c]:(n=T(a),t.buffers.push(n)),new r(n,i,o)}});}));var I={dataview:{test:function test(e){return "DataView"===s.toStringTag(e)},replace:function replace(e,t){var r=e.buffer,n=e.byteOffset,i=e.byteLength;t.buffers||(t.buffers=[]);var o=t.buffers.indexOf(r);return o>-1?{index:o,byteOffset:n,byteLength:i}:(t.buffers.push(r),{encoded:S(r),byteOffset:n,byteLength:i})},revive:function revive(e,t){t.buffers||(t.buffers=[]);var r,n=e.byteOffset,i=e.byteLength,o=e.encoded,a=e.index;return "index"in e?r=t.buffers[a]:(r=T(o),t.buffers.push(r)),new DataView(r,n,i)}}},C={IntlCollator:{test:function test(e){return s.hasConstructorOf(e,Intl.Collator)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.Collator(e.locale,e)}},IntlDateTimeFormat:{test:function test(e){return s.hasConstructorOf(e,Intl.DateTimeFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.DateTimeFormat(e.locale,e)}},IntlNumberFormat:{test:function test(e){return s.hasConstructorOf(e,Intl.NumberFormat)},replace:function replace(e){return e.resolvedOptions()},revive:function revive(e){return new Intl.NumberFormat(e.locale,e)}}};function string2arraybuffer(e){for(var t=new Uint8Array(e.length),r=0;r> 2]; + base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4]; + base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6]; + base64 += chars[bytes[_i + 2] & 63]; + } + + if (len % 3 === 2) { + base64 = base64.slice(0, -1) + '='; + } else if (len % 3 === 1) { + base64 = base64.slice(0, -2) + '=='; + } + + return base64; +}; +/** + * @param {string} base64 + * @returns {ArrayBuffer} + */ + +var decode = function decode(base64) { + var len = base64.length; + var bufferLength = base64.length * 0.75; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (var _i2 = 0; _i2 < len; _i2 += 4) { + encoded1 = lookup[base64.codePointAt(_i2)]; + encoded2 = lookup[base64.codePointAt(_i2 + 1)]; + encoded3 = lookup[base64.codePointAt(_i2 + 2)]; + encoded4 = lookup[base64.codePointAt(_i2 + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + + return arraybuffer; +}; + +/* eslint-env browser, node */ +var _global = typeof self === 'undefined' ? global : self; +var exportObj = {}; +[ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array' +].forEach(function (typeName) { + var arrType = typeName; + var TypedArray = _global[arrType]; + if (TypedArray) { + exportObj[typeName.toLowerCase() + "2"] = { + test: function (x) { return typeson.toStringTag(x) === arrType; }, + replace: function (_a) { + var buffer = _a.buffer, byteOffset = _a.byteOffset, length = _a.length; + return { + buffer: buffer, + byteOffset: byteOffset, + length: length + }; + }, + revive: function (b64Obj) { + var buffer = b64Obj.buffer, byteOffset = b64Obj.byteOffset, length = b64Obj.length; + return new TypedArray(buffer, byteOffset, length); + } + }; + } +}); + +var arrayBuffer = { + arraybuffer: { + test: function (x) { return typeson.toStringTag(x) === 'ArrayBuffer'; }, + replace: function (b) { + return encode(b, 0, b.byteLength); + }, + revive: function (b64) { + var buffer = decode(b64); + return buffer; + } + } +}; +// See also typed-arrays! + +var TSON = new typeson().register(structuredCloning); +var readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only. +var blobsToAwait = []; +var blobsToAwaitPos = 0; +// Need to patch encapsulateAsync as it does not work as of typeson 5.8.2 +// Also, current version of typespn-registry-1.0.0-alpha.21 does not +// encapsulate/revive Blobs correctly (fails one of the unit tests in +// this library (test 'export-format')) +TSON.register([ + arrayBuffer, + exportObj, { + blob2: { + test: function (x) { return typeson.toStringTag(x) === 'Blob'; }, + replace: function (b) { + if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob + throw new Error('The Blob is closed'); + } + if (readBlobsSynchronously) { + var data = readBlobSync(b, 'binary'); + var base64 = encode(data, 0, data.byteLength); + return { + type: b.type, + data: base64 + }; + } + else { + blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true. + var result = { + type: b.type, + data: { start: blobsToAwaitPos, end: blobsToAwaitPos + b.size } + }; + blobsToAwaitPos += b.size; + return result; + } + }, + finalize: function (b, ba) { + b.data = encode(ba, 0, ba.byteLength); + }, + revive: function (_a) { + var type = _a.type, data = _a.data; + return new Blob([decode(data)], { type: type }); + } + } + } +]); +TSON.mustFinalize = function () { return blobsToAwait.length > 0; }; +TSON.finalize = function (items) { return __awaiter(void 0, void 0, void 0, function () { + var allChunks, _i, items_1, item, types, arrayType, keyPath, typeName, typeSpec, b; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, readBlobAsync(new Blob(blobsToAwait), 'binary')]; + case 1: + allChunks = _a.sent(); + if (items) { + for (_i = 0, items_1 = items; _i < items_1.length; _i++) { + item = items_1[_i]; + // Manually go through all "blob" types in the result + // and lookup the data slice they point at. + if (item.$types) { + types = item.$types; + arrayType = types.$; + if (arrayType) + types = types.$; + for (keyPath in types) { + typeName = types[keyPath]; + typeSpec = TSON.types[typeName]; + if (typeSpec && typeSpec.finalize) { + b = Dexie.getByKeyPath(item, arrayType ? "$." + keyPath : keyPath); + typeSpec.finalize(b, allChunks.slice(b.start, b.end)); + } + } + } + } + } + // Free up memory + blobsToAwait = []; + return [2 /*return*/]; + } + }); +}); }; + +var DEFAULT_ROWS_PER_CHUNK = 2000; +function exportDB(db, options) { + return __awaiter(this, void 0, void 0, function () { + function exportAll() { + return __awaiter(this, void 0, void 0, function () { + var tablesRowCounts, emptyExportJson, posEndDataArray, firstJsonSlice, filter, _loop_1, _i, tables_1, tableName; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all(db.tables.map(function (table) { return table.count(); }))]; + case 1: + tablesRowCounts = _a.sent(); + tablesRowCounts.forEach(function (rowCount, i) { return tables[i].rowCount = rowCount; }); + progress.totalRows = tablesRowCounts.reduce(function (p, c) { return p + c; }); + emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined); + posEndDataArray = emptyExportJson.lastIndexOf(']'); + firstJsonSlice = emptyExportJson.substring(0, posEndDataArray); + slices.push(firstJsonSlice); + filter = options.filter; + _loop_1 = function (tableName) { + var table, primKey, inbound, LIMIT, emptyTableExport, emptyTableExportJson, posEndRowsArray, lastKey, lastNumRows, mayHaveMoreRows, _loop_2, state_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + table = db.table(tableName); + primKey = table.schema.primKey; + inbound = !!primKey.keyPath; + LIMIT = options.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK; + emptyTableExport = inbound ? { + tableName: table.name, + inbound: true, + rows: [] + } : { + tableName: table.name, + inbound: false, + rows: [] + }; + emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined); + if (prettyJson) { + // Increase indentation according to this: + // { + // ... + // data: [ + // ... + // data: [ + // 123456<---- here + // ] + // ] + // } + emptyTableExportJson = emptyTableExportJson.split('\n').join('\n '); + } + posEndRowsArray = emptyTableExportJson.lastIndexOf(']'); + slices.push(emptyTableExportJson.substring(0, posEndRowsArray)); + lastKey = null; + lastNumRows = 0; + mayHaveMoreRows = true; + _loop_2 = function () { + var chunkedCollection, values, filteredValues, tsonValues, json, keys, keyvals, tsonTuples, json; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + chunkedCollection = lastKey == null ? + table.limit(LIMIT) : + table.where(':id').above(lastKey).limit(LIMIT); + return [4 /*yield*/, chunkedCollection.toArray()]; + case 1: + values = _c.sent(); + if (values.length === 0) + return [2 /*return*/, "break"]; + if (lastKey != null && lastNumRows > 0) { + // Not initial chunk. Must add a comma: + slices.push(","); + if (prettyJson) { + slices.push("\n "); + } + } + mayHaveMoreRows = values.length === LIMIT; + if (!inbound) return [3 /*break*/, 4]; + filteredValues = filter ? + values.filter(function (value) { return filter(tableName, value); }) : + values; + tsonValues = filteredValues.map(function (value) { return TSON.encapsulate(value); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 3]; + return [4 /*yield*/, Dexie.waitFor(TSON.finalize(tsonValues))]; + case 2: + _c.sent(); + _c.label = 3; + case 3: + json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = filteredValues.length; + lastKey = values.length > 0 ? + Dexie.getByKeyPath(values[values.length - 1], primKey.keyPath) : + null; + return [3 /*break*/, 8]; + case 4: return [4 /*yield*/, chunkedCollection.primaryKeys()]; + case 5: + keys = _c.sent(); + keyvals = keys.map(function (key, i) { return [key, values[i]]; }); + if (filter) + keyvals = keyvals.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }); + tsonTuples = keyvals.map(function (tuple) { return TSON.encapsulate(tuple); }); + if (!TSON.mustFinalize()) return [3 /*break*/, 7]; + return [4 /*yield*/, Dexie.waitFor(TSON.finalize(tsonTuples))]; + case 6: + _c.sent(); + _c.label = 7; + case 7: + json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined); + if (prettyJson) + json = json.split('\n').join('\n '); + // By generating a blob here, we give web platform the opportunity to store the contents + // on disk and release RAM. + slices.push(new Blob([json.substring(1, json.length - 1)])); + lastNumRows = keyvals.length; + lastKey = keys.length > 0 ? + keys[keys.length - 1] : + null; + _c.label = 8; + case 8: + progress.completedRows += values.length; + return [2 /*return*/]; + } + }); + }; + _b.label = 1; + case 1: + if (!mayHaveMoreRows) return [3 /*break*/, 3]; + return [5 /*yield**/, _loop_2()]; + case 2: + state_1 = _b.sent(); + if (state_1 === "break") + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + slices.push(emptyTableExportJson.substr(posEndRowsArray)); // "]}" + progress.completedTables += 1; + if (progress.completedTables < progress.totalTables) { + slices.push(","); + } + return [2 /*return*/]; + } + }); + }; + _i = 0, tables_1 = tables; + _a.label = 2; + case 2: + if (!(_i < tables_1.length)) return [3 /*break*/, 5]; + tableName = tables_1[_i].name; + return [5 /*yield**/, _loop_1(tableName)]; + case 3: + _a.sent(); + _a.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + slices.push(emptyExportJson.substr(posEndDataArray)); + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); + } + var slices, tables, prettyJson, emptyExport, progressCallback, progress; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; + slices = []; + tables = db.tables.map(function (table) { return ({ + name: table.name, + schema: getSchemaString(table), + rowCount: 0 + }); }); + prettyJson = options.prettyJson; + emptyExport = { + formatName: "dexie", + formatVersion: 1, + data: { + databaseName: db.name, + databaseVersion: db.verno, + tables: tables, + data: [] + } + }; + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: NaN, + totalTables: db.tables.length + }; + _a.label = 1; + case 1: + _a.trys.push([1, , 6, 7]); + if (!options.noTransaction) return [3 /*break*/, 3]; + return [4 /*yield*/, exportAll()]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, db.transaction('r', db.tables, exportAll)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: return [3 /*break*/, 7]; + case 6: + TSON.finalize(); // Free up mem if error has occurred + return [7 /*endfinally*/]; + case 7: return [2 /*return*/, new Blob(slices, { type: "text/json" })]; + } + }); + }); +} + +var VERSION = 1; + +var fakeStream = {Stream: function(){}}; + +var clarinet_1 = createCommonjsModule(function (module, exports) { +(function (clarinet) { + + // non node-js needs to set clarinet debug on root + var env =(typeof process === 'object' && process.env) + ? process.env + : self; + + clarinet.parser = function (opt) { return new CParser(opt);}; + clarinet.CParser = CParser; + clarinet.CStream = CStream; + clarinet.createStream = createStream; + clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024; + clarinet.DEBUG = (env.CDEBUG==='debug'); + clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info'); + clarinet.EVENTS = + [ "value" + , "string" + , "key" + , "openobject" + , "closeobject" + , "openarray" + , "closearray" + , "error" + , "end" + , "ready" + ]; + + var buffers = { + textNode: undefined, + numberNode: "" + } + , streamWraps = clarinet.EVENTS.filter(function (ev) { + return ev !== "error" && ev !== "end"; + }) + , S = 0 + , Stream + ; + + clarinet.STATE = + { BEGIN : S++ + , VALUE : S++ // general stuff + , OPEN_OBJECT : S++ // { + , CLOSE_OBJECT : S++ // } + , OPEN_ARRAY : S++ // [ + , CLOSE_ARRAY : S++ // ] + , TEXT_ESCAPE : S++ // \ stuff + , STRING : S++ // "" + , BACKSLASH : S++ + , END : S++ // No more stack + , OPEN_KEY : S++ // , "a" + , CLOSE_KEY : S++ // : + , TRUE : S++ // r + , TRUE2 : S++ // u + , TRUE3 : S++ // e + , FALSE : S++ // a + , FALSE2 : S++ // l + , FALSE3 : S++ // s + , FALSE4 : S++ // e + , NULL : S++ // u + , NULL2 : S++ // l + , NULL3 : S++ // l + , NUMBER_DECIMAL_POINT : S++ // . + , NUMBER_DIGIT : S++ // [0-9] + }; + + for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_; + + // switcharoo + S = clarinet.STATE; + + const Char = { + tab : 0x09, // \t + lineFeed : 0x0A, // \n + carriageReturn : 0x0D, // \r + space : 0x20, // " " + + doubleQuote : 0x22, // " + plus : 0x2B, // + + comma : 0x2C, // , + minus : 0x2D, // - + period : 0x2E, // . + + _0 : 0x30, // 0 + _9 : 0x39, // 9 + + colon : 0x3A, // : + + E : 0x45, // E + + openBracket : 0x5B, // [ + backslash : 0x5C, // \ + closeBracket : 0x5D, // ] + + a : 0x61, // a + b : 0x62, // b + e : 0x65, // e + f : 0x66, // f + l : 0x6C, // l + n : 0x6E, // n + r : 0x72, // r + s : 0x73, // s + t : 0x74, // t + u : 0x75, // u + + openBrace : 0x7B, // { + closeBrace : 0x7D, // } + }; + + if (!Object.create) { + Object.create = function (o) { + function f () { this["__proto__"] = o; } + f.prototype = o; + return new f; + }; + } + + if (!Object.getPrototypeOf) { + Object.getPrototypeOf = function (o) { + return o["__proto__"]; + }; + } + + if (!Object.keys) { + Object.keys = function (o) { + var a = []; + for (var i in o) if (o.hasOwnProperty(i)) a.push(i); + return a; + }; + } + + function checkBufferLength (parser) { + var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10) + , maxActual = 0 + ; + for (var buffer in buffers) { + var len = parser[buffer] === undefined ? 0 : parser[buffer].length; + if (len > maxAllowed) { + switch (buffer) { + case "text": + closeText(parser); + break; + + default: + error(parser, "Max buffer length exceeded: "+ buffer); + } + } + maxActual = Math.max(maxActual, len); + } + parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual) + + parser.position; + } + + function clearBuffers (parser) { + for (var buffer in buffers) { + parser[buffer] = buffers[buffer]; + } + } + + var stringTokenPattern = /[\\"\n]/g; + + function CParser (opt) { + if (!(this instanceof CParser)) return new CParser (opt); + + var parser = this; + clearBuffers(parser); + parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH; + parser.q = parser.c = parser.p = ""; + parser.opt = opt || {}; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.state = S.BEGIN; + parser.stack = new Array(); + // mostly just for error reporting + parser.position = parser.column = 0; + parser.line = 1; + parser.slashed = false; + parser.unicodeI = 0; + parser.unicodeS = null; + parser.depth = 0; + emit(parser, "onready"); + } + + CParser.prototype = + { end : function () { end(this); } + , write : write + , resume : function () { this.error = null; return this; } + , close : function () { return this.write(null); } + }; + + try { Stream = fakeStream.Stream; } + catch (ex) { Stream = function () {}; } + + function createStream (opt) { return new CStream(opt); } + + function CStream (opt) { + if (!(this instanceof CStream)) return new CStream(opt); + + this._parser = new CParser(opt); + this.writable = true; + this.readable = true; + + //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error + this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary + this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read + this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached + this.string = ''; + + var me = this; + Stream.apply(me); + + this._parser.onend = function () { me.emit("end"); }; + this._parser.onerror = function (er) { + me.emit("error", er); + me._parser.error = null; + }; + + streamWraps.forEach(function (ev) { + Object.defineProperty(me, "on" + ev, + { get : function () { return me._parser["on" + ev]; } + , set : function (h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on"+ev] = h; + return h; + } + me.on(ev, h); + } + , enumerable : true + , configurable : false + }); + }); + } + + CStream.prototype = Object.create(Stream.prototype, + { constructor: { value: CStream } }); + + CStream.prototype.write = function (data) { + data = new Buffer(data); + for (var i = 0; i < data.length; i++) { + var n = data[i]; + + // check for carry over of a multi byte char split between data chunks + // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration + if (this.bytes_remaining > 0) { + for (var j = 0; j < this.bytes_remaining; j++) { + this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j]; + } + this.string = this.temp_buffs[this.bytes_in_sequence].toString(); + this.bytes_in_sequence = this.bytes_remaining = 0; + + // move iterator forward by number of byte read during sequencing + i = i + j - 1; + + // pass data to parser and move forward to parse rest of data + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + + // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time + if (this.bytes_remaining === 0 && n >= 128) { + if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2; + if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3; + if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4; + if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split + + for (var k = 0; k <= (data.length - 1 - i); k++) { + this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk + } + this.bytes_remaining = (i + this.bytes_in_sequence) - data.length; + + // immediately return as we need another chunk to sequence the character + return true; + } else { + this.string = data.slice(i, (i + this.bytes_in_sequence)).toString(); + i = i + this.bytes_in_sequence - 1; + + this._parser.write(this.string); + this.emit("data", this.string); + continue; + } + } + + // is there a range of characters that are immediately parsable? + for (var p = i; p < data.length; p++) { + if (data[p] >= 128) break; + } + this.string = data.slice(i, p).toString(); + this._parser.write(this.string); + this.emit("data", this.string); + i = p - 1; + + // handle any remaining characters using multibyte logic + continue; + } + }; + + CStream.prototype.end = function (chunk) { + if (chunk && chunk.length) this._parser.write(chunk.toString()); + this._parser.end(); + return true; + }; + + CStream.prototype.on = function (ev, handler) { + var me = this; + if (!me._parser["on"+ev] && streamWraps.indexOf(ev) !== -1) { + me._parser["on"+ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] + : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + } + return Stream.prototype.on.call(me, ev, handler); + }; + + CStream.prototype.destroy = function () { + clearBuffers(this._parser); + this.emit("close"); + }; + + function emit(parser, event, data) { + if(clarinet.INFO) console.log('-- emit', event, data); + if (parser[event]) parser[event](data); + } + + function emitNode(parser, event, data) { + closeValue(parser); + emit(parser, event, data); + } + + function closeValue(parser, event) { + parser.textNode = textopts(parser.opt, parser.textNode); + if (parser.textNode !== undefined) { + emit(parser, (event ? event : "onvalue"), parser.textNode); + } + parser.textNode = undefined; + } + + function closeNumber(parser) { + if (parser.numberNode) + emit(parser, "onvalue", parseFloat(parser.numberNode)); + parser.numberNode = ""; + } + + function textopts (opt, text) { + if (text === undefined) { + return text; + } + if (opt.trim) text = text.trim(); + if (opt.normalize) text = text.replace(/\s+/g, " "); + return text; + } + + function error (parser, er) { + closeValue(parser); + er += "\nLine: "+parser.line+ + "\nColumn: "+parser.column+ + "\nChar: "+parser.c; + er = new Error(er); + parser.error = er; + emit(parser, "onerror", er); + return parser; + } + + function end(parser) { + if (parser.state !== S.VALUE || parser.depth !== 0) + error(parser, "Unexpected end"); + + closeValue(parser); + parser.c = ""; + parser.closed = true; + emit(parser, "onend"); + CParser.call(parser, parser.opt); + return parser; + } + + function isWhitespace(c) { + return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab; + } + + function write (chunk) { + var parser = this; + if (this.error) throw this.error; + if (parser.closed) return error(parser, + "Cannot write after close. Assign an onready handler."); + if (chunk === null) return end(parser); + var i = 0, c = chunk.charCodeAt(0), p = parser.p; + if (clarinet.DEBUG) console.log('write -> [' + chunk + ']'); + while (c) { + p = c; + parser.c = c = chunk.charCodeAt(i++); + // if chunk doesnt have next, like streaming char by char + // this way we need to check if previous is really previous + // if not we need to reset to what the parser says is the previous + // from buffer + if(p !== c ) parser.p = p; + else p = parser.p; + + if(!c) break; + + if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]); + parser.position ++; + if (c === Char.lineFeed) { + parser.line ++; + parser.column = 0; + } else parser.column ++; + switch (parser.state) { + + case S.BEGIN: + if (c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if (!isWhitespace(c)) + error(parser, "Non-whitespace before {[."); + continue; + + case S.OPEN_KEY: + case S.OPEN_OBJECT: + if (isWhitespace(c)) continue; + if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY); + else { + if(c === Char.closeBrace) { + emit(parser, 'onopenobject'); + this.depth++; + emit(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else parser.stack.push(S.CLOSE_OBJECT); + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else error(parser, "Malformed object key should start with \""); + continue; + + case S.CLOSE_KEY: + case S.CLOSE_OBJECT: + if (isWhitespace(c)) continue; + (parser.state === S.CLOSE_KEY) ? 'key' : 'object'; + if(c === Char.colon) { + if(parser.state === S.CLOSE_OBJECT) { + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser, 'onopenobject'); + this.depth++; + } else closeValue(parser, 'onkey'); + parser.state = S.VALUE; + } else if (c === Char.closeBrace) { + emitNode(parser, 'oncloseobject'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if(c === Char.comma) { + if(parser.state === S.CLOSE_OBJECT) + parser.stack.push(S.CLOSE_OBJECT); + closeValue(parser); + parser.state = S.OPEN_KEY; + } else error(parser, 'Bad object'); + continue; + + case S.OPEN_ARRAY: // after an array there always a value + case S.VALUE: + if (isWhitespace(c)) continue; + if(parser.state===S.OPEN_ARRAY) { + emit(parser, 'onopenarray'); + this.depth++; + parser.state = S.VALUE; + if(c === Char.closeBracket) { + emit(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + continue; + } else { + parser.stack.push(S.CLOSE_ARRAY); + } + } + if(c === Char.doubleQuote) parser.state = S.STRING; + else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT; + else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY; + else if(c === Char.t) parser.state = S.TRUE; + else if(c === Char.f) parser.state = S.FALSE; + else if(c === Char.n) parser.state = S.NULL; + else if(c === Char.minus) { // keep and continue + parser.numberNode += "-"; + } else if(Char._0 <= c && c <= Char._9) { + parser.numberNode += String.fromCharCode(c); + parser.state = S.NUMBER_DIGIT; + } else error(parser, "Bad value"); + continue; + + case S.CLOSE_ARRAY: + if(c === Char.comma) { + parser.stack.push(S.CLOSE_ARRAY); + closeValue(parser, 'onvalue'); + parser.state = S.VALUE; + } else if (c === Char.closeBracket) { + emitNode(parser, 'onclosearray'); + this.depth--; + parser.state = parser.stack.pop() || S.VALUE; + } else if (isWhitespace(c)) + continue; + else error(parser, 'Bad array'); + continue; + + case S.STRING: + if (parser.textNode === undefined) { + parser.textNode = ""; + } + + // thanks thejh, this is an about 50% performance improvement. + var starti = i-1 + , slashed = parser.slashed + , unicodeI = parser.unicodeI + ; + STRING_BIGLOOP: while (true) { + if (clarinet.DEBUG) + console.log(i,c,clarinet.STATE[parser.state] + ,slashed); + // zero means "no unicode active". 1-4 mean "parse some more". end after 4. + while (unicodeI > 0) { + parser.unicodeS += String.fromCharCode(c); + c = chunk.charCodeAt(i++); + parser.position++; + if (unicodeI === 4) { + // TODO this might be slow? well, probably not used too often anyway + parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16)); + unicodeI = 0; + starti = i-1; + } else { + unicodeI++; + } + // we can just break here: no stuff we skipped that still has to be sliced out or so + if (!c) break STRING_BIGLOOP; + } + if (c === Char.doubleQuote && !slashed) { + parser.state = parser.stack.pop() || S.VALUE; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + if (c === Char.backslash && !slashed) { + slashed = true; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + c = chunk.charCodeAt(i++); + parser.position++; + if (!c) break; + } + if (slashed) { + slashed = false; + if (c === Char.n) { parser.textNode += '\n'; } + else if (c === Char.r) { parser.textNode += '\r'; } + else if (c === Char.t) { parser.textNode += '\t'; } + else if (c === Char.f) { parser.textNode += '\f'; } + else if (c === Char.b) { parser.textNode += '\b'; } + else if (c === Char.u) { + // \uxxxx. meh! + unicodeI = 1; + parser.unicodeS = ''; + } else { + parser.textNode += String.fromCharCode(c); + } + c = chunk.charCodeAt(i++); + parser.position++; + starti = i-1; + if (!c) break; + else continue; + } + + stringTokenPattern.lastIndex = i; + var reResult = stringTokenPattern.exec(chunk); + if (reResult === null) { + i = chunk.length+1; + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + i = reResult.index+1; + c = chunk.charCodeAt(reResult.index); + if (!c) { + parser.textNode += chunk.substring(starti, i-1); + parser.position += i - 1 - starti; + break; + } + } + parser.slashed = slashed; + parser.unicodeI = unicodeI; + continue; + + case S.TRUE: + if (c === Char.r) parser.state = S.TRUE2; + else error(parser, 'Invalid true started with t'+ c); + continue; + + case S.TRUE2: + if (c === Char.u) parser.state = S.TRUE3; + else error(parser, 'Invalid true started with tr'+ c); + continue; + + case S.TRUE3: + if(c === Char.e) { + emit(parser, "onvalue", true); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid true started with tru'+ c); + continue; + + case S.FALSE: + if (c === Char.a) parser.state = S.FALSE2; + else error(parser, 'Invalid false started with f'+ c); + continue; + + case S.FALSE2: + if (c === Char.l) parser.state = S.FALSE3; + else error(parser, 'Invalid false started with fa'+ c); + continue; + + case S.FALSE3: + if (c === Char.s) parser.state = S.FALSE4; + else error(parser, 'Invalid false started with fal'+ c); + continue; + + case S.FALSE4: + if (c === Char.e) { + emit(parser, "onvalue", false); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid false started with fals'+ c); + continue; + + case S.NULL: + if (c === Char.u) parser.state = S.NULL2; + else error(parser, 'Invalid null started with n'+ c); + continue; + + case S.NULL2: + if (c === Char.l) parser.state = S.NULL3; + else error(parser, 'Invalid null started with nu'+ c); + continue; + + case S.NULL3: + if(c === Char.l) { + emit(parser, "onvalue", null); + parser.state = parser.stack.pop() || S.VALUE; + } else error(parser, 'Invalid null started with nul'+ c); + continue; + + case S.NUMBER_DECIMAL_POINT: + if(c === Char.period) { + parser.numberNode += "."; + parser.state = S.NUMBER_DIGIT; + } else error(parser, 'Leading zero not followed by .'); + continue; + + case S.NUMBER_DIGIT: + if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c); + else if (c === Char.period) { + if(parser.numberNode.indexOf('.')!==-1) + error(parser, 'Invalid number has two dots'); + parser.numberNode += "."; + } else if (c === Char.e || c === Char.E) { + if(parser.numberNode.indexOf('e')!==-1 || + parser.numberNode.indexOf('E')!==-1 ) + error(parser, 'Invalid number has two exponential'); + parser.numberNode += "e"; + } else if (c === Char.plus || c === Char.minus) { + if(!(p === Char.e || p === Char.E)) + error(parser, 'Invalid symbol in number'); + parser.numberNode += String.fromCharCode(c); + } else { + closeNumber(parser); + i--; // go back one + parser.state = parser.stack.pop() || S.VALUE; + } + continue; + + default: + error(parser, "Unknown state: " + parser.state); + } + } + if (parser.position >= parser.bufferCheckPosition) + checkBufferLength(parser); + return parser; + } + +})(exports); +}); + +function JsonStream(blob) { + var pos = 0; + var parser = JsonParser(true); + var rv = { + pullAsync: function (numBytes) { + return __awaiter(this, void 0, void 0, function () { + var slize, jsonPart, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + return [4 /*yield*/, readBlobAsync(slize, 'text')]; + case 1: + jsonPart = _a.sent(); + result = parser.write(jsonPart); + rv.result = result || {}; + return [2 /*return*/, result]; + } + }); + }); + }, + pullSync: function (numBytes) { + var slize = blob.slice(pos, pos + numBytes); + pos += numBytes; + var jsonPart = readBlobSync(slize, 'text'); + var result = parser.write(jsonPart); + rv.result = result || {}; + return result; + }, + done: function () { + return parser.done(); + }, + eof: function () { + return pos >= blob.size; + }, + result: {} + }; + return rv; +} +function JsonParser(allowPartial) { + var parser = clarinet_1.parser(); + var level = 0; + var result; + var stack = []; + var obj; + var key; + var done = false; + var array = false; + parser.onopenobject = function (newKey) { + var newObj = {}; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + key = newKey; + array = false; + ++level; + }; + parser.onkey = function (newKey) { return key = newKey; }; + parser.onvalue = function (value) { return array ? obj.push(value) : obj[key] = value; }; + parser.oncloseobject = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + parser.onopenarray = function () { + var newObj = []; + newObj.incomplete = true; + if (!result) + result = newObj; + if (obj) { + stack.push([key, obj, array]); + if (allowPartial) { + if (array) { + obj.push(newObj); + } + else { + obj[key] = newObj; + } + } + } + obj = newObj; + array = true; + key = null; + ++level; + }; + parser.onclosearray = function () { + var _a; + delete obj.incomplete; + key = null; + if (--level === 0) { + done = true; + } + else { + var completedObj = obj; + _a = stack.pop(), key = _a[0], obj = _a[1], array = _a[2]; + if (!allowPartial) { + if (array) { + obj.push(completedObj); + } + else { + obj[key] = completedObj; + } + } + } + }; + return { + write: function (jsonPart) { + parser.write(jsonPart); + return result; + }, + done: function () { + return done; + } + }; +} + +var DEFAULT_KILOBYTES_PER_CHUNK = 1024; +function importDB(exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + var CHUNK_SIZE, stream, dbExport, db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + stream = _a.sent(); + dbExport = stream.result.data; + db = new Dexie(dbExport.databaseName); + db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport)); + return [4 /*yield*/, importInto(db, stream, options)]; + case 2: + _a.sent(); + return [2 /*return*/, db]; + } + }); + }); +} +function peakImportFile(exportedData) { + return __awaiter(this, void 0, void 0, function () { + var stream; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = JsonStream(exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(5 * 1024)]; + case 2: + _a.sent(); // 5 k is normally enough for the headers. If not, it will just do another go. + if (stream.result.data && stream.result.data.data) { + // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it. + delete stream.result.data.data; // Don't return half-baked data array. + return [3 /*break*/, 3]; + } + return [3 /*break*/, 1]; + case 3: return [2 /*return*/, stream.result]; + } + }); + }); +} +function importInto(db, exportedData, options) { + return __awaiter(this, void 0, void 0, function () { + function importAll() { + return __awaiter(this, void 0, void 0, function () { + var _loop_1, _i, _a, tableExport, state_1; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _loop_1 = function (tableExport) { + var tableName, table, tableSchemaStr, sourceRows, rows, i, obj, filter, filteredRows, _c, keys, values; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + if (!tableExport.rows) + return [2 /*return*/, "break"]; // Need to pull more! + if (!tableExport.rows.incomplete && tableExport.rows.length === 0) + return [2 /*return*/, "continue"]; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + tableName = tableExport.tableName; + table = db.table(tableName); + tableSchemaStr = dbExport.tables.filter(function (t) { return t.name === tableName; })[0].schema; + if (!table) { + if (!options.acceptMissingTables) + throw new Error("Exported table ".concat(tableExport.tableName, " is missing in installed database")); + else + return [2 /*return*/, "continue"]; + } + if (!options.acceptChangedPrimaryKey && + tableSchemaStr.split(',')[0] != table.schema.primKey.src) { + throw new Error("Primary key differs for table ".concat(tableExport.tableName, ". ")); + } + sourceRows = tableExport.rows; + rows = []; + for (i = 0; i < sourceRows.length; i++) { + obj = sourceRows[i]; + if (!obj.incomplete) { + rows.push(TSON.revive(obj)); + } + else { + break; + } + } + filter = options.filter; + filteredRows = filter ? + tableExport.inbound ? + rows.filter(function (value) { return filter(tableName, value); }) : + rows.filter(function (_a) { + var key = _a[0], value = _a[1]; + return filter(tableName, value, key); + }) : + rows; + _c = tableExport.inbound ? + [undefined, filteredRows] : + [filteredRows.map(function (row) { return row[0]; }), rows.map(function (row) { return row[1]; })], keys = _c[0], values = _c[1]; + if (!options.overwriteValues) return [3 /*break*/, 2]; + return [4 /*yield*/, table.bulkPut(values, keys)]; + case 1: + _d.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, table.bulkAdd(values, keys)]; + case 3: + _d.sent(); + _d.label = 4; + case 4: + progress.completedRows += rows.length; + if (!rows.incomplete) { + progress.completedTables += 1; + } + sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance. + return [2 /*return*/]; + } + }); + }; + _i = 0, _a = dbExport.data; + _b.label = 1; + case 1: + if (!(_i < _a.length)) return [3 /*break*/, 4]; + tableExport = _a[_i]; + return [5 /*yield**/, _loop_1(tableExport)]; + case 2: + state_1 = _b.sent(); + if (state_1 === "break") + return [3 /*break*/, 4]; + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: + // Avoid unnescessary loops in "for (const tableExport of dbExport.data)" + while (dbExport.data.length > 0 && dbExport.data[0].rows && !dbExport.data[0].rows.incomplete) { + // We've already imported all rows from the first table. Delete its occurrence + dbExport.data.splice(0, 1); + } + if (!(!jsonStream.done() && !jsonStream.eof())) return [3 /*break*/, 8]; + if (!readBlobsSynchronously) return [3 /*break*/, 5]; + // If we can pull from blob synchronically, we don't have to + // keep transaction alive using Dexie.waitFor(). + // This will only be possible in workers. + jsonStream.pullSync(CHUNK_SIZE); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE))]; + case 6: + _b.sent(); + _b.label = 7; + case 7: return [3 /*break*/, 9]; + case 8: return [3 /*break*/, 10]; + case 9: + return [3 /*break*/, 0]; + case 10: return [2 /*return*/]; + } + }); + }); + } + var CHUNK_SIZE, jsonStream, dbExportFile, readBlobsSynchronously, dbExport, progressCallback, progress, _i, _a, table; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + options = options || {}; // All booleans defaults to false. + CHUNK_SIZE = options.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024); + return [4 /*yield*/, loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE)]; + case 1: + jsonStream = _b.sent(); + dbExportFile = jsonStream.result; + readBlobsSynchronously = 'FileReaderSync' in self; + dbExport = dbExportFile.data; + if (!options.acceptNameDiff && db.name !== dbExport.databaseName) + throw new Error("Name differs. Current database name is ".concat(db.name, " but export is ").concat(dbExport.databaseName)); + if (!options.acceptVersionDiff && db.verno !== dbExport.databaseVersion) { + // Possible feature: Call upgraders in some isolated way if this happens... ? + throw new Error("Database version differs. Current database is in version ".concat(db.verno, " but export is ").concat(dbExport.databaseVersion)); + } + progressCallback = options.progressCallback; + progress = { + done: false, + completedRows: 0, + completedTables: 0, + totalRows: dbExport.tables.reduce(function (p, c) { return p + c.rowCount; }, 0), + totalTables: dbExport.tables.length + }; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + if (!options.clearTablesBeforeImport) return [3 /*break*/, 5]; + _i = 0, _a = db.tables; + _b.label = 2; + case 2: + if (!(_i < _a.length)) return [3 /*break*/, 5]; + table = _a[_i]; + return [4 /*yield*/, table.clear()]; + case 3: + _b.sent(); + _b.label = 4; + case 4: + _i++; + return [3 /*break*/, 2]; + case 5: + if (!options.noTransaction) return [3 /*break*/, 7]; + return [4 /*yield*/, importAll()]; + case 6: + _b.sent(); + return [3 /*break*/, 9]; + case 7: return [4 /*yield*/, db.transaction('rw', db.tables, importAll)]; + case 8: + _b.sent(); + _b.label = 9; + case 9: + progress.done = true; + if (progressCallback) { + // Keep ongoing transaction private + Dexie.ignoreTransaction(function () { return progressCallback(progress); }); + } + return [2 /*return*/]; + } + }); + }); +} +function loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE) { + return __awaiter(this, void 0, void 0, function () { + var stream, dbExportFile; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + stream = ('slice' in exportedData ? + JsonStream(exportedData) : + exportedData); + _a.label = 1; + case 1: + if (!!stream.eof()) return [3 /*break*/, 3]; + return [4 /*yield*/, stream.pullAsync(CHUNK_SIZE)]; + case 2: + _a.sent(); + if (stream.result.data && stream.result.data.data) + return [3 /*break*/, 3]; + return [3 /*break*/, 1]; + case 3: + dbExportFile = stream.result; + if (!dbExportFile || dbExportFile.formatName != "dexie") + throw new Error("Given file is not a dexie export"); + if (dbExportFile.formatVersion > VERSION) { + throw new Error("Format version ".concat(dbExportFile.formatVersion, " not supported")); + } + if (!dbExportFile.data) { + throw new Error("No data in export file"); + } + if (!dbExportFile.data.databaseName) { + throw new Error("Missing databaseName in export file"); + } + if (!dbExportFile.data.databaseVersion) { + throw new Error("Missing databaseVersion in export file"); + } + if (!dbExportFile.data.tables) { + throw new Error("Missing tables in export file"); + } + return [2 /*return*/, stream]; + } + }); + }); +} + +// +// Extend Dexie interface (runtime wise) +// +Dexie.prototype.export = function (options) { + return exportDB(this, options); +}; +Dexie.prototype.import = function (blob, options) { + return importInto(this, blob, options); +}; +Dexie.import = function (blob, options) { return importDB(blob, options); }; +var dexieExportImport = (function () { + throw new Error("This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options."); +}); + +export { dexieExportImport as default, exportDB, importDB, importInto, peakImportFile }; +//# sourceMappingURL=dexie-export-import.mjs.map diff --git a/addons/dexie-export-import/dist/dexie-export-import.mjs.map b/addons/dexie-export-import/dist/dexie-export-import.mjs.map new file mode 100644 index 000000000..4a1fa8405 --- /dev/null +++ b/addons/dexie-export-import/dist/dexie-export-import.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie-export-import.mjs","sources":["../../../node_modules/.pnpm/tslib@2.3.1/node_modules/tslib/tslib.es6.js","../src/helpers.ts","../../../node_modules/.pnpm/typeson@5.18.2_core-js-bundle@3.27.2_regenerator-runtime@0.13.11/node_modules/typeson/dist/typeson.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/node_modules/typeson/dist/typeson-esm.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/user-object.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/presets/array-nonindex-keys.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/undef.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/primitive-objects.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/presets/special-numbers.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/nan.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/infinity.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/negative-infinity.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/date.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/regexp.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/map.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/set.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/arraybuffer.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/typed-arrays.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/dataview.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/intl-types.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/utils/stringArrayBuffer.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/file.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/bigint.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/bigint-object.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/cryptokey.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/presets/structured-cloning.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/imagedata.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/imagebitmap.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/filelist.js","../../../node_modules/.pnpm/typeson-registry@1.0.0-alpha.39/node_modules/typeson-registry/types/blob.js","../../../node_modules/.pnpm/base64-arraybuffer-es6@1.0.0/node_modules/base64-arraybuffer-es6/dist/base64-arraybuffer-es.js","../src/tson-typed-array.ts","../src/tson-arraybuffer.ts","../src/tson.ts","../src/export.ts","../src/json-structure.ts","../tools/build-configs/fake-stream.js","../../../node_modules/.pnpm/github.com+dfahlander+clarinet@d1dc89f7e67488b16ad98b2464d29a9b3bc6f5ef/node_modules/clarinet/clarinet.js","../src/json-stream.ts","../src/import.ts","../src/dexie-export-import.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","import Dexie from 'dexie';\nimport { DexieExportedDatabase } from './json-structure';\n\nexport function getSchemaString(table: Dexie.Table) {\n const primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes);\n return primKeyAndIndexes.map(index => index.src).join(',');\n}\n\nexport function extractDbSchema(exportedDb: DexieExportedDatabase) {\n const schema: {\n [tableName: string]: string;\n } = {};\n for (const table of exportedDb.tables) {\n schema[table.name] = table.schema;\n }\n return schema;\n}\n\n\n// Missing FileReaderSync type in standard typescript libs:\ninterface FileReaderSync {\n readAsArrayBuffer(blob: Blob): ArrayBuffer;\n readAsBinaryString(blob: Blob): string;\n readAsDataURL(blob: Blob): string;\n readAsText(blob: Blob, encoding?: string): string;\n}\ndeclare var FileReaderSync: {\n prototype: FileReaderSync;\n new(): FileReaderSync;\n};\n// -----------------------------------------------\n\nexport interface TypeMapper {\n binary: ArrayBuffer;\n text: string;\n}\n\nexport function readBlobAsync(blob: Blob, type: T): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onabort = ev => reject(new Error(\"file read aborted\"));\n reader.onerror = ev => reject((ev.target as any).error);\n reader.onload = ev => resolve((ev.target as any).result);\n if (type === 'binary')\n reader.readAsArrayBuffer(blob);\n else\n reader.readAsText(blob);\n });\n}\n\nexport function readBlobSync(blob: Blob, type: T): TypeMapper[T] {\n if (typeof FileReaderSync === 'undefined') {\n throw new Error('FileReaderSync missing. Reading blobs synchronously requires code to run from within a web worker. Use TSON.encapsulateAsync() to do it from the main thread.');\n }\n const reader = new FileReaderSync(); // Requires worker environment\n const data = type === 'binary' ?\n reader.readAsArrayBuffer(blob) :\n reader.readAsText(blob);\n\n return data as TypeMapper[T];\n}\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = global || self, global.Typeson = factory());\n}(this, (function () { 'use strict';\n\n function _typeof(obj) {\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n\n _next(undefined);\n });\n };\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n }\n\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n }\n\n function _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n }\n\n function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n\n function _iterableToArray(iter) {\n if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter);\n }\n\n function _iterableToArrayLimit(arr, i) {\n if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\")) {\n return;\n }\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance\");\n }\n\n function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n\n /**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * With ES6 classes, we may be able to simply use `class TypesonPromise\n * extends Promise` and add a string tag for detection.\n * @param {function} f\n */\n // eslint-disable-next-line max-len\n // eslint-disable-next-line block-spacing, space-before-function-paren, space-before-blocks, space-infix-ops, semi, promise/avoid-new\n var TypesonPromise = function TypesonPromise(f) {\n _classCallCheck(this, TypesonPromise);\n\n this.p = new Promise(f);\n }; // eslint-disable-next-line max-len\n // class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi\n\n\n TypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill\n\n /* istanbul ignore else */\n\n if (typeof Symbol !== 'undefined') {\n // Ensure `isUserObject` will return `false` for `TypesonPromise`\n TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise';\n }\n /**\n *\n * @param {function} [onFulfilled]\n * @param {function} [onRejected]\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.prototype.then = function (onFulfilled, onRejected) {\n var _this = this;\n\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n _this.p.then(function (res) {\n // eslint-disable-next-line promise/always-return\n typesonResolve(onFulfilled ? onFulfilled(res) : res);\n })[\"catch\"](function (res) {\n return onRejected ? onRejected(res) : Promise.reject(res);\n }).then(typesonResolve, typesonReject);\n });\n };\n /**\n *\n * @param {function} onRejected\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\n *\n * @param {Any} v\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.resolve = function (v) {\n return new TypesonPromise(function (typesonResolve) {\n typesonResolve(v);\n });\n };\n /**\n *\n * @param {Any} v\n * @returns {TypesonPromise}\n */\n\n\n TypesonPromise.reject = function (v) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n typesonReject(v);\n });\n };\n\n ['all', 'race'].forEach(function (meth) {\n /**\n *\n * @param {Promise[]} promArr\n * @returns {TypesonPromise}\n */\n TypesonPromise[meth] = function (promArr) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n Promise[meth](promArr.map(function (prom) {\n return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom;\n })).then(typesonResolve, typesonReject);\n });\n };\n });\n\n var _ref = {},\n toStr = _ref.toString,\n hasOwn = {}.hasOwnProperty,\n getProto = Object.getPrototypeOf,\n fnToString = hasOwn.toString;\n /**\n * Second argument not in use internally, but provided for utility.\n * @param {Any} v\n * @param {boolean} catchCheck\n * @returns {boolean}\n */\n\n function isThenable(v, catchCheck) {\n return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v[\"catch\"] === 'function');\n }\n /**\n *\n * @param {Any} val\n * @returns {string}\n */\n\n\n function toStringTag(val) {\n return toStr.call(val).slice(8, -1);\n }\n /**\n * This function is dependent on both constructors\n * being identical so any minimization is expected of both.\n * @param {Any} a\n * @param {function} b\n * @returns {boolean}\n */\n\n\n function hasConstructorOf(a, b) {\n if (!a || _typeof(a) !== 'object') {\n return false;\n }\n\n var proto = getProto(a);\n\n if (!proto) {\n return b === null;\n }\n\n var Ctor = hasOwn.call(proto, 'constructor') && proto.constructor;\n\n if (typeof Ctor !== 'function') {\n return b === null;\n }\n\n if (b === Ctor) {\n return true;\n }\n\n if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) {\n return true;\n }\n\n if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) {\n return true;\n }\n\n return false;\n }\n /**\n *\n * @param {Any} val\n * @returns {boolean}\n */\n\n\n function isPlainObject(val) {\n // Mirrors jQuery's\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object);\n }\n /**\n *\n * @param {Any} val\n * @returns {boolean}\n */\n\n\n function isUserObject(val) {\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object) || isUserObject(proto);\n }\n /**\n *\n * @param {Any} v\n * @returns {boolean}\n */\n\n\n function isObject(v) {\n return v && _typeof(v) === 'object';\n }\n /**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\n function escapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~/g, '~0').replace(/\\./g, '~1');\n }\n /**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\n function unescapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~');\n }\n /**\n * @param {PlainObject|GenericArray} obj\n * @param {string} keyPath\n * @returns {Any}\n */\n\n\n function getByKeyPath(obj, keyPath) {\n if (keyPath === '') {\n return obj;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1));\n }\n\n return obj[unescapeKeyPathComponent(keyPath)];\n }\n /**\n *\n * @param {PlainObject} obj\n * @param {string} keyPath\n * @param {Any} value\n * @returns {Any}\n */\n\n\n function setAtKeyPath(obj, keyPath, value) {\n if (keyPath === '') {\n return value;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return setAtKeyPath(innerObj, keyPath.slice(period + 1), value);\n }\n\n obj[unescapeKeyPathComponent(keyPath)] = value;\n return obj;\n }\n /**\n *\n * @param {external:JSON} value\n * @returns {\"null\"|\"array\"|\"undefined\"|\"boolean\"|\"number\"|\"string\"|\n * \"object\"|\"symbol\"}\n */\n\n\n function getJSONType(value) {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof(value);\n }\n\n var keys = Object.keys,\n isArray = Array.isArray,\n hasOwn$1 = {}.hasOwnProperty,\n internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric'];\n /**\n * Handle plain object revivers first so reference setting can use\n * revived type (e.g., array instead of object); assumes revived\n * has same structure or will otherwise break subsequent references.\n * @param {PlainObjectType} a\n * @param {PlainObjectType} b\n * @returns {1|-1|boolean}\n */\n\n function nestedPathsFirst(a, b) {\n if (a.keypath === '') {\n return -1;\n }\n\n var as = a.keypath.match(/\\./g) || 0;\n var bs = b.keypath.match(/\\./g) || 0;\n\n if (as) {\n as = as.length;\n }\n\n if (bs) {\n bs = bs.length;\n }\n\n return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath;\n }\n /**\n * An instance of this class can be used to call `stringify()` and `parse()`.\n * Typeson resolves cyclic references by default. Can also be extended to\n * support custom types using the register() method.\n *\n * @class\n * @param {{cyclic: boolean}} [options] - if cyclic (default true),\n * cyclic references will be handled gracefully.\n */\n\n\n var Typeson =\n /*#__PURE__*/\n function () {\n function Typeson(options) {\n _classCallCheck(this, Typeson);\n\n this.options = options; // Replacers signature: replace (value). Returns falsy if not\n // replacing. Otherwise ['Date', value.getTime()]\n\n this.plainObjectReplacers = [];\n this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}].\n // Sample: [{'Date': value => new Date(value)}, {plain: false}]\n\n this.revivers = {};\n /** Types registered via `register()`. */\n\n this.types = {};\n }\n /**\n * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON\n */\n\n /**\n * @callback JSONReplacer\n * @param {\"\"|string} key\n * @param {JSON} value\n * @returns {number|string|boolean|null|PlainObject|undefined}\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter\n */\n\n /**\n * Serialize given object to Typeson.\n * Initial arguments work identical to those of `JSON.stringify`.\n * The `replacer` argument has nothing to do with our replacers.\n * @param {Any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {object} opts\n * @returns {string|Promise} Promise resolves to a string\n */\n\n\n _createClass(Typeson, [{\n key: \"stringify\",\n value: function stringify(obj, replacer, space, opts) {\n opts = _objectSpread2({}, this.options, {}, opts, {\n stringification: true\n });\n var encapsulated = this.encapsulate(obj, null, opts);\n\n if (isArray(encapsulated)) {\n return JSON.stringify(encapsulated[0], replacer, space);\n }\n\n return encapsulated.then(function (res) {\n return JSON.stringify(res, replacer, space);\n });\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {Any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {object} opts\n * @returns {string}\n */\n\n }, {\n key: \"stringifySync\",\n value: function stringifySync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n *\n * @param {Any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {object} opts\n * @returns {Promise}\n */\n\n }, {\n key: \"stringifyAsync\",\n value: function stringifyAsync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n * Parse Typeson back into an obejct.\n * Initial arguments works identical to those of `JSON.parse()`.\n * @param {string} text\n * @param {function} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {object} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parse\",\n value: function parse(text, reviver, opts) {\n opts = _objectSpread2({}, this.options, {}, opts, {\n parse: true\n });\n return this.revive(JSON.parse(text, reviver), opts);\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {string} text\n * @param {function} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {object} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parseSync\",\n value: function parseSync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n * @param {string} text\n * @param {function} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {object} opts\n * @returns {Promise} Resolves to `external:JSON`\n */\n\n }, {\n key: \"parseAsync\",\n value: function parseAsync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n *\n * @param {Any} obj\n * @param {object} stateObj\n * @param {object} [opts={}]\n * @returns {string[]|false}\n */\n\n }, {\n key: \"specialTypeNames\",\n value: function specialTypeNames(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.returnTypeNames = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n *\n * @param {Any} obj\n * @param {PlainObject} stateObj\n * @param {PlainObject} [opts={}]\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"rootTypeName\",\n value: function rootTypeName(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.iterateNone = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n * Encapsulate a complex object into a plain Object by replacing\n * registered types with plain objects representing the types data.\n *\n * This method is used internally by `Typeson.stringify()`.\n * @param {Any} obj - Object to encapsulate.\n * @param {PlainObject} stateObj\n * @param {PlainObject} opts\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"encapsulate\",\n value: function encapsulate(obj, stateObj, opts) {\n opts = _objectSpread2({\n sync: true\n }, this.options, {}, opts);\n var _opts = opts,\n sync = _opts.sync;\n var that = this,\n types = {},\n refObjs = [],\n // For checking cyclic references\n refKeys = [],\n // For checking cyclic references\n promisesDataRoot = []; // Clone the object deeply while at the same time replacing any\n // special types or cyclic reference:\n\n var cyclic = 'cyclic' in opts ? opts.cyclic : true;\n var _opts2 = opts,\n encapsulateObserver = _opts2.encapsulateObserver;\n\n var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot);\n /**\n *\n * @param {Any} ret\n * @returns {GenericArray|PlainObject|string|false}\n */\n\n\n function finish(ret) {\n // Add `$types` to result only if we ever bumped into a\n // special type (or special case where object has own `$types`)\n var typeNames = Object.values(types);\n\n if (opts.iterateNone) {\n if (typeNames.length) {\n return typeNames[0];\n }\n\n return Typeson.getJSONType(ret);\n }\n\n if (typeNames.length) {\n if (opts.returnTypeNames) {\n return _toConsumableArray(new Set(typeNames));\n } // Special if array (or a primitive) was serialized\n // because JSON would ignore custom `$types` prop on it\n\n\n if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its\n // own `$types` property (to avoid ambiguity)\n hasOwn$1.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: {\n $: types\n }\n };\n } else {\n ret.$types = types;\n } // No special types\n\n } else if (isObject(ret) && hasOwn$1.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: true\n };\n }\n\n if (opts.returnTypeNames) {\n return false;\n }\n\n return ret;\n }\n /**\n *\n * @param {Any} ret\n * @param {GenericArray} promisesData\n * @returns {Promise}\n */\n\n\n function checkPromises(_x, _x2) {\n return _checkPromises.apply(this, arguments);\n }\n /**\n *\n * @param {object} stateObj\n * @param {object} ownKeysObj\n * @param {function} cb\n * @returns {undefined}\n */\n\n\n function _checkPromises() {\n _checkPromises = _asyncToGenerator(\n /*#__PURE__*/\n regeneratorRuntime.mark(function _callee2(ret, promisesData) {\n var promResults;\n return regeneratorRuntime.wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return Promise.all(promisesData.map(function (pd) {\n return pd[1].p;\n }));\n\n case 2:\n promResults = _context2.sent;\n _context2.next = 5;\n return Promise.all(promResults.map(\n /*#__PURE__*/\n function () {\n var _ref = _asyncToGenerator(\n /*#__PURE__*/\n regeneratorRuntime.mark(function _callee(promResult) {\n var newPromisesData, _promisesData$splice, _promisesData$splice2, prData, _prData, keyPath, cyclic, stateObj, parentObj, key, detectedType, encaps, isTypesonPromise, encaps2;\n\n return regeneratorRuntime.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n newPromisesData = [];\n _promisesData$splice = promisesData.splice(0, 1), _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1), prData = _promisesData$splice2[0];\n _prData = _slicedToArray(prData, 7), keyPath = _prData[0], cyclic = _prData[2], stateObj = _prData[3], parentObj = _prData[4], key = _prData[5], detectedType = _prData[6];\n encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType);\n isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself\n // returns a `Typeson.Promise`\n\n if (!(keyPath && isTypesonPromise)) {\n _context.next = 11;\n break;\n }\n\n _context.next = 8;\n return encaps.p;\n\n case 8:\n encaps2 = _context.sent;\n parentObj[key] = encaps2;\n return _context.abrupt(\"return\", checkPromises(ret, newPromisesData));\n\n case 11:\n if (keyPath) {\n parentObj[key] = encaps;\n } else if (isTypesonPromise) {\n ret = encaps.p;\n } else {\n // If this is itself a `Typeson.Promise` (because the\n // original value supplied was a `Promise` or\n // because the supplied custom type value resolved\n // to one), returning it below will be fine since\n // a `Promise` is expected anyways given current\n // config (and if not a `Promise`, it will be ready\n // as the resolve value)\n ret = encaps;\n }\n\n return _context.abrupt(\"return\", checkPromises(ret, newPromisesData));\n\n case 13:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee);\n }));\n\n return function (_x3) {\n return _ref.apply(this, arguments);\n };\n }()));\n\n case 5:\n return _context2.abrupt(\"return\", ret);\n\n case 6:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2);\n }));\n return _checkPromises.apply(this, arguments);\n }\n\n function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) {\n Object.assign(stateObj, ownKeysObj);\n var vals = internalStateObjPropsToIgnore.map(function (prop) {\n var tmp = stateObj[prop];\n delete stateObj[prop];\n return tmp;\n }); // eslint-disable-next-line callback-return\n\n cb();\n internalStateObjPropsToIgnore.forEach(function (prop, i) {\n stateObj[prop] = vals[i];\n });\n }\n /**\n *\n * @param {string} keypath\n * @param {Any} value\n * @param {boolean} cyclic\n * @param {PlainObject} stateObj\n * @param {boolean} promisesData\n * @param {boolean} resolvingTypesonPromise\n * @param {string} detectedType\n * @returns {Any}\n */\n\n\n function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) {\n var ret;\n var observerData = {};\n\n var $typeof = _typeof(value);\n\n var runObserver = encapsulateObserver ? function (obj) {\n var type = detectedType || stateObj.type || Typeson.getJSONType(value);\n encapsulateObserver(Object.assign(obj || observerData, {\n keypath: keypath,\n value: value,\n cyclic: cyclic,\n stateObj: stateObj,\n promisesData: promisesData,\n resolvingTypesonPromise: resolvingTypesonPromise,\n awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise)\n }, {\n type: type\n }));\n } : null;\n\n if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) {\n if (value === undefined || $typeof === 'number' && (isNaN(value) || value === -Infinity || value === Infinity)) {\n if (stateObj.replaced) {\n ret = value;\n } else {\n ret = replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver);\n }\n\n if (ret !== value) {\n observerData = {\n replaced: ret\n };\n }\n } else {\n ret = value;\n }\n\n if (runObserver) {\n runObserver();\n }\n\n return ret;\n }\n\n if (value === null) {\n if (runObserver) {\n runObserver();\n }\n\n return value;\n }\n\n if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') {\n // Options set to detect cyclic references and be able\n // to rewrite them.\n var refIndex = refObjs.indexOf(value);\n\n if (refIndex < 0) {\n if (cyclic === true) {\n refObjs.push(value);\n refKeys.push(keypath);\n }\n } else {\n types[keypath] = '#';\n\n if (runObserver) {\n runObserver({\n cyclicKeypath: refKeys[refIndex]\n });\n }\n\n return '#' + refKeys[refIndex];\n }\n }\n\n var isPlainObj = isPlainObject(value);\n var isArr = isArray(value);\n var replaced = // Running replace will cause infinite loop as will test\n // positive again\n (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object\n // replacers, don't try finding a replacer\n value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver);\n var clone;\n\n if (replaced !== value) {\n ret = replaced;\n observerData = {\n replaced: replaced\n };\n } else {\n // eslint-disable-next-line no-lonely-if\n if (keypath === '' && hasConstructorOf(value, TypesonPromise)) {\n promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]);\n ret = value;\n } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') {\n clone = new Array(value.length);\n observerData = {\n clone: clone\n };\n } else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') {\n clone = {};\n\n if (stateObj.addLength) {\n clone.length = value.length;\n }\n\n observerData = {\n clone: clone\n };\n } else {\n ret = value; // Only clone vanilla objects and arrays\n }\n }\n\n if (runObserver) {\n runObserver();\n }\n\n if (opts.iterateNone) {\n return clone || ret;\n }\n\n if (!clone) {\n return ret;\n } // Iterate object or array\n\n\n if (stateObj.iterateIn) {\n var _loop = function _loop(key) {\n var ownKeysObj = {\n ownKeys: hasOwn$1.call(value, key)\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n };\n\n // eslint-disable-next-line guard-for-in\n for (var key in value) {\n _loop(key);\n }\n\n if (runObserver) {\n runObserver({\n endIterateIn: true,\n end: true\n });\n }\n } else {\n // Note: Non-indexes on arrays won't survive stringify so\n // somewhat wasteful for arrays, but so too is iterating\n // all numeric indexes on sparse arrays when not wanted\n // or filtering own keys for positive integers\n keys(value).forEach(function (key) {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n var ownKeysObj = {\n ownKeys: true\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n });\n\n if (runObserver) {\n runObserver({\n endIterateOwn: true,\n end: true\n });\n }\n } // Iterate array for non-own numeric properties (we can't\n // replace the prior loop though as it iterates non-integer\n // keys)\n\n\n if (stateObj.iterateUnsetNumeric) {\n var vl = value.length;\n\n var _loop2 = function _loop2(i) {\n if (!(i in value)) {\n // No need to escape numeric\n var kp = keypath + (keypath ? '.' : '') + i;\n var ownKeysObj = {\n ownKeys: false\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]);\n } else if (val !== undefined) {\n clone[i] = val;\n }\n });\n }\n };\n\n for (var i = 0; i < vl; i++) {\n _loop2(i);\n }\n\n if (runObserver) {\n runObserver({\n endIterateUnsetNumeric: true,\n end: true\n });\n }\n }\n\n return clone;\n }\n /**\n *\n * @param {string} keypath\n * @param {Any} value\n * @param {PlainObject} stateObj\n * @param {GenericArray} promisesData\n * @param {boolean} plainObject\n * @param {boolean} resolvingTypesonPromise\n * @param {function} [runObserver]\n * @returns {*}\n */\n\n\n function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) {\n // Encapsulate registered types\n var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers;\n var i = replacers.length;\n\n while (i--) {\n var replacer = replacers[i];\n\n if (replacer.test(value, stateObj)) {\n var type = replacer.type;\n\n if (that.revivers[type]) {\n // Record the type only if a corresponding reviver\n // exists. This is to support specs where only\n // replacement is done.\n // For example, ensuring deep cloning of the object,\n // or replacing a type to its equivalent without\n // the need to revive it.\n var existing = types[keypath]; // type can comprise an array of types (see test\n // \"should support intermediate types\")\n\n types[keypath] = existing ? [type].concat(existing) : type;\n }\n\n Object.assign(stateObj, {\n type: type,\n replaced: true\n });\n\n if ((sync || !replacer.replaceAsync) && !replacer.replace) {\n if (runObserver) {\n runObserver({\n typeDetected: true\n });\n }\n\n return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n\n if (runObserver) {\n runObserver({\n replacing: true\n });\n } // Now, also traverse the result in case it contains its\n // own types to replace\n\n\n var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync';\n return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n }\n\n return value;\n }\n\n return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() // If this is a synchronous request for stringification, yet\n // a promise is the result, we don't want to resolve leading\n // to an async result, so we return an array to avoid\n // ambiguity\n : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {*} obj\n * @param {object} stateObj\n * @param {object} opts\n * @returns {*}\n */\n\n }, {\n key: \"encapsulateSync\",\n value: function encapsulateSync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n * @param {*} obj\n * @param {object} stateObj\n * @param {object} opts\n * @returns {*}\n */\n\n }, {\n key: \"encapsulateAsync\",\n value: function encapsulateAsync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n * Revive an encapsulated object.\n * This method is used internally by `Typeson.parse()`.\n * @param {object} obj - Object to revive. If it has `$types` member, the\n * properties that are listed there will be replaced with its true type\n * instead of just plain objects.\n * @param {object} opts\n * @throws TypeError If mismatch between sync/async type and result\n * @returns {Promise|*} If async, returns a Promise that resolves to `*`\n */\n\n }, {\n key: \"revive\",\n value: function revive(obj, opts) {\n var types = obj && obj.$types; // No type info added. Revival not needed.\n\n if (!types) {\n return obj;\n } // Object happened to have own `$types` property but with\n // no actual types, so we unescape and return that object\n\n\n if (types === true) {\n return obj.$;\n }\n\n opts = _objectSpread2({\n sync: true\n }, this.options, {}, opts);\n var _opts3 = opts,\n sync = _opts3.sync;\n var keyPathResolutions = [];\n var stateObj = {};\n var ignore$Types = true; // Special when root object is not a trivial Object, it will\n // be encapsulated in `$`. It will also be encapsulated in\n // `$` if it has its own `$` property to avoid ambiguity\n\n if (types.$ && isPlainObject(types.$)) {\n obj = obj.$;\n types = types.$;\n ignore$Types = false;\n }\n\n var that = this;\n /**\n * @callback RevivalReducer\n * @param {Any} value\n * @param {string} type\n * @returns {Any}\n */\n\n /**\n *\n * @param {string} type\n * @param {Any} val\n * @returns {[type]} [description]\n */\n\n function executeReviver(type, val) {\n var _ref2 = that.revivers[type] || [],\n _ref3 = _slicedToArray(_ref2, 1),\n reviver = _ref3[0];\n\n if (!reviver) {\n throw new Error('Unregistered type: ' + type);\n } // Only `sync` expected here, as problematic async would\n // be missing both `reviver` and `reviverAsync`, and\n // encapsulation shouldn't have added types, so\n // should have made an early exit\n\n\n if (sync && !('revive' in reviver)) {\n // Just return value as is\n return val;\n }\n\n return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj);\n }\n /**\n *\n * @returns {void|TypesonPromise}\n */\n\n\n function revivePlainObjects() {\n // const references = [];\n // const reviveTypes = [];\n var plainObjectTypes = [];\n Object.entries(types).forEach(function (_ref4) {\n var _ref5 = _slicedToArray(_ref4, 2),\n keypath = _ref5[0],\n type = _ref5[1];\n\n if (type === '#') {\n /*\n references.push({\n keypath,\n reference: getByKeyPath(obj, keypath)\n });\n */\n return;\n }\n\n [].concat(type).forEach(function (type) {\n var _ref6 = that.revivers[type] || [null, {}],\n _ref7 = _slicedToArray(_ref6, 2),\n plain = _ref7[1].plain;\n\n if (!plain) {\n // reviveTypes.push({keypath, type});\n return;\n }\n\n plainObjectTypes.push({\n keypath: keypath,\n type: type\n });\n delete types[keypath]; // Avoid repeating\n });\n });\n\n if (!plainObjectTypes.length) {\n return undefined;\n } // console.log(plainObjectTypes.sort(nestedPathsFirst));\n\n /**\n * @typedef {PlainObject} PlainObjectType\n * @property {string} keypath\n * @property {string} type\n */\n\n\n return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref8) {\n var keypath = _ref8.keypath,\n type = _ref8.type;\n\n if (isThenable(possibleTypesonPromise)) {\n return possibleTypesonPromise.then(function (val) {\n return reducer(val, {\n keypath: keypath,\n type: type\n });\n });\n } // console.log('obj', JSON.stringify(keypath), obj);\n\n\n var val = getByKeyPath(obj, keypath);\n val = executeReviver(type, val);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n var newVal = setAtKeyPath(obj, keypath, v);\n\n if (newVal === v) {\n obj = newVal;\n }\n\n return undefined;\n });\n }\n\n var newVal = setAtKeyPath(obj, keypath, val);\n\n if (newVal === val) {\n obj = newVal;\n }\n\n return undefined;\n }, undefined // This argument must be explicit\n ); // references.forEach(({keypath, reference}) => {});\n // reviveTypes.sort(nestedPathsFirst).forEach(() => {});\n }\n\n var revivalPromises = [];\n /**\n *\n * @param {string} keypath\n * @param {Any} value\n * @param {?(Array|object)} target\n * @param {Array|object} [clone]\n * @param {string} [key]\n * @returns {Any}\n */\n\n function _revive(keypath, value, target, clone, key) {\n if (ignore$Types && keypath === '$types') {\n return undefined;\n }\n\n var type = types[keypath];\n var isArr = isArray(value);\n\n if (isArr || isPlainObject(value)) {\n var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array\n\n\n keys(value).forEach(function (k) {\n var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k);\n\n var set = function set(v) {\n if (hasConstructorOf(v, Undefined)) {\n _clone[k] = undefined;\n } else if (v !== undefined) {\n _clone[k] = v;\n }\n\n return v;\n };\n\n if (hasConstructorOf(val, TypesonPromise)) {\n revivalPromises.push(val.then(function (ret) {\n return set(ret);\n }));\n } else {\n set(val);\n }\n });\n value = _clone; // Try to resolve cyclic reference as soon as available\n\n while (keyPathResolutions.length) {\n var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4),\n _target = _keyPathResolutions$[0],\n keyPath = _keyPathResolutions$[1],\n _clone2 = _keyPathResolutions$[2],\n k = _keyPathResolutions$[3];\n\n var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or\n // `undefined`\n\n if (val !== undefined) {\n _clone2[k] = val;\n } else {\n break;\n }\n\n keyPathResolutions.splice(0, 1);\n }\n }\n\n if (!type) {\n return value;\n }\n\n if (type === '#') {\n var _ret = getByKeyPath(target, value.slice(1));\n\n if (_ret === undefined) {\n // Cyclic reference not yet available\n keyPathResolutions.push([target, value.slice(1), clone, key]);\n }\n\n return _ret;\n } // `type` can be an array here\n\n\n return [].concat(type).reduce(function reducer(val, typ) {\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n // TypesonPromise here too\n return reducer(v, typ);\n });\n }\n\n return executeReviver(typ, val);\n }, value);\n }\n /**\n *\n * @param {Any} retrn\n * @returns {undefined|Any}\n */\n\n\n function checkUndefined(retrn) {\n return hasConstructorOf(retrn, Undefined) ? undefined : retrn;\n }\n\n var possibleTypesonPromise = revivePlainObjects();\n var ret;\n\n if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) {\n ret = possibleTypesonPromise.then(function () {\n return obj;\n });\n } else {\n ret = _revive('', obj, null);\n\n if (revivalPromises.length) {\n // Ensure children resolved\n ret = TypesonPromise.resolve(ret).then(function (r) {\n return TypesonPromise.all([// May be a TypesonPromise or not\n r].concat(revivalPromises));\n }).then(function (_ref9) {\n var _ref10 = _slicedToArray(_ref9, 1),\n r = _ref10[0];\n\n return r;\n });\n }\n }\n\n return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {Any} obj\n * @param {object} opts\n * @returns {Any}\n */\n\n }, {\n key: \"reviveSync\",\n value: function reviveSync(obj, opts) {\n return this.revive(obj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: true\n }));\n }\n /**\n * @param {Any} obj\n * @param {object} opts\n * @returns {Promise} Resolves to `*`\n */\n\n }, {\n key: \"reviveAsync\",\n value: function reviveAsync(obj, opts) {\n return this.revive(obj, _objectSpread2({\n throwOnBadSyncType: true\n }, opts, {\n sync: false\n }));\n }\n /**\n * Register types.\n * For examples on how to use this method, see\n * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}.\n * @param {object.[]} typeSpecSets - Types and\n * their functions [test, encapsulate, revive];\n * @param {object} opts\n * @returns {Typeson}\n */\n\n }, {\n key: \"register\",\n value: function register(typeSpecSets, opts) {\n opts = opts || {};\n [].concat(typeSpecSets).forEach(function R(typeSpec) {\n var _this = this;\n\n // Allow arrays of arrays of arrays...\n if (isArray(typeSpec)) {\n return typeSpec.map(function (typSpec) {\n return R.call(_this, typSpec);\n });\n }\n\n typeSpec && keys(typeSpec).forEach(function (typeId) {\n if (typeId === '#') {\n throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects');\n } else if (Typeson.JSON_TYPES.includes(typeId)) {\n throw new TypeError('Plain JSON object types are reserved as type names');\n }\n\n var spec = typeSpec[typeId];\n var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers;\n var existingReplacer = replacers.filter(function (r) {\n return r.type === typeId;\n });\n\n if (existingReplacer.length) {\n // Remove existing spec and replace with this one.\n replacers.splice(replacers.indexOf(existingReplacer[0]), 1);\n delete this.revivers[typeId];\n delete this.types[typeId];\n }\n\n if (typeof spec === 'function') {\n // Support registering just a class without replacer/reviver\n var Class = spec;\n spec = {\n test: function test(x) {\n return x && x.constructor === Class;\n },\n replace: function replace(x) {\n return _objectSpread2({}, x);\n },\n revive: function revive(x) {\n return Object.assign(Object.create(Class.prototype), x);\n }\n };\n } else if (isArray(spec)) {\n var _spec = spec,\n _spec2 = _slicedToArray(_spec, 3),\n test = _spec2[0],\n replace = _spec2[1],\n revive = _spec2[2];\n\n spec = {\n test: test,\n replace: replace,\n revive: revive\n };\n }\n\n if (!spec || !spec.test) {\n return;\n }\n\n var replacerObj = {\n type: typeId,\n test: spec.test.bind(spec)\n };\n\n if (spec.replace) {\n replacerObj.replace = spec.replace.bind(spec);\n }\n\n if (spec.replaceAsync) {\n replacerObj.replaceAsync = spec.replaceAsync.bind(spec);\n }\n\n var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Infinity;\n\n if (spec.testPlainObjects) {\n this.plainObjectReplacers.splice(start, 0, replacerObj);\n } else {\n this.nonplainObjectReplacers.splice(start, 0, replacerObj);\n } // Todo: We might consider a testAsync type\n\n\n if (spec.revive || spec.reviveAsync) {\n var reviverObj = {};\n\n if (spec.revive) {\n reviverObj.revive = spec.revive.bind(spec);\n }\n\n if (spec.reviveAsync) {\n reviverObj.reviveAsync = spec.reviveAsync.bind(spec);\n }\n\n this.revivers[typeId] = [reviverObj, {\n plain: spec.testPlainObjects\n }];\n } // Record to be retrieved via public types property.\n\n\n this.types[typeId] = spec;\n }, this);\n }, this);\n return this;\n }\n }]);\n\n return Typeson;\n }();\n /**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * @class\n */\n\n\n var Undefined = function Undefined() {\n _classCallCheck(this, Undefined);\n }; // eslint-disable-line space-before-blocks\n\n\n Undefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values\n // To insist `undefined` should be added\n\n Typeson.Undefined = Undefined; // To support async encapsulation/stringification\n\n Typeson.Promise = TypesonPromise; // Some fundamental type-checking utilities\n\n Typeson.isThenable = isThenable;\n Typeson.toStringTag = toStringTag;\n Typeson.hasConstructorOf = hasConstructorOf;\n Typeson.isObject = isObject;\n Typeson.isPlainObject = isPlainObject;\n Typeson.isUserObject = isUserObject;\n Typeson.escapeKeyPathComponent = escapeKeyPathComponent;\n Typeson.unescapeKeyPathComponent = unescapeKeyPathComponent;\n Typeson.getByKeyPath = getByKeyPath;\n Typeson.getJSONType = getJSONType;\n Typeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object'];\n\n return Typeson;\n\n})));\n","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n}\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n}\n\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n}\n\nfunction _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n}\n\nfunction _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n}\n\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nfunction _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n}\n\nfunction _iterableToArrayLimit(arr, i) {\n if (typeof Symbol === \"undefined\" || !(Symbol.iterator in Object(arr))) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\n\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n}\n\nfunction _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\n\n/**\n* @callback TypesonFulfilled\n* @returns {Promise|any}\n*/\n\n/**\n* @callback TypesonRejected\n* @returns {Promise|any}\n*/\n\n/**\n * @callback TypesonResolve\n * @param {any} value\n * @returns {Promise}\n */\n\n/**\n * @callback TypesonReject\n * @param {Error|any} error\n * @returns {Promise}\n */\n\n/**\n * @callback TypesonResolveReject\n * @param {TypesonResolve} typesonResolve\n * @param {TypesonReject} typesonReject\n * @returns {Promise}\n */\n\n/* eslint-disable block-spacing, space-before-function-paren,\n space-before-blocks, space-infix-ops, semi, promise/avoid-new,\n jsdoc/require-jsdoc */\n\n/**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * With ES6 classes, we may be able to simply use `class TypesonPromise\n * extends Promise` and add a string tag for detection.\n * @param {TypesonResolveReject} f\n */\nvar TypesonPromise = function TypesonPromise(f) {\n _classCallCheck(this, TypesonPromise);\n\n this.p = new Promise(f);\n};\n/* eslint-enable block-spacing, space-before-function-paren,\n space-before-blocks, space-infix-ops, semi, promise/avoid-new,\n jsdoc/require-jsdoc */\n// eslint-disable-next-line max-len\n// class TypesonPromise extends Promise {get[Symbol.toStringTag](){return 'TypesonPromise'};} // eslint-disable-line keyword-spacing, space-before-function-paren, space-before-blocks, block-spacing, semi\n\n\nTypesonPromise.__typeson__type__ = 'TypesonPromise'; // Note: core-js-bundle provides a `Symbol` polyfill\n\n/* istanbul ignore else */\n\nif (typeof Symbol !== 'undefined') {\n // Ensure `isUserObject` will return `false` for `TypesonPromise`\n TypesonPromise.prototype[Symbol.toStringTag] = 'TypesonPromise';\n}\n/**\n *\n * @param {TypesonFulfilled} [onFulfilled]\n * @param {TypesonRejected} [onRejected]\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.prototype.then = function (onFulfilled, onRejected) {\n var _this = this;\n\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n _this.p.then(function (res) {\n // eslint-disable-next-line promise/always-return\n typesonResolve(onFulfilled ? onFulfilled(res) : res);\n })[\"catch\"](function (res) {\n return onRejected ? onRejected(res) : Promise.reject(res);\n }).then(typesonResolve, typesonReject);\n });\n};\n/**\n *\n * @param {TypesonRejected} onRejected\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\n/**\n *\n * @param {any} v\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.resolve = function (v) {\n return new TypesonPromise(function (typesonResolve) {\n typesonResolve(v);\n });\n};\n/**\n *\n * @param {any} v\n * @returns {TypesonPromise}\n */\n\n\nTypesonPromise.reject = function (v) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n typesonReject(v);\n });\n};\n\n['all', 'race'].forEach(function (meth) {\n /**\n *\n * @param {Promise[]} promArr\n * @returns {TypesonPromise}\n */\n TypesonPromise[meth] = function (promArr) {\n return new TypesonPromise(function (typesonResolve, typesonReject) {\n // eslint-disable-next-line promise/catch-or-return\n Promise[meth](promArr.map(function (prom) {\n return prom && prom.constructor && prom.constructor.__typeson__type__ === 'TypesonPromise' ? prom.p : prom;\n })).then(typesonResolve, typesonReject);\n });\n };\n});\n\nvar _ref = {},\n toStr = _ref.toString,\n hasOwn$1 = {}.hasOwnProperty,\n getProto = Object.getPrototypeOf,\n fnToString = hasOwn$1.toString;\n/**\n * Second argument not in use internally, but provided for utility.\n * @param {any} v\n * @param {boolean} catchCheck\n * @returns {boolean}\n */\n\nfunction isThenable(v, catchCheck) {\n return isObject(v) && typeof v.then === 'function' && (!catchCheck || typeof v[\"catch\"] === 'function');\n}\n/**\n *\n * @param {any} val\n * @returns {string}\n */\n\n\nfunction toStringTag(val) {\n return toStr.call(val).slice(8, -1);\n}\n/**\n * This function is dependent on both constructors\n * being identical so any minimization is expected of both.\n * @param {any} a\n * @param {GenericFunction} b\n * @returns {boolean}\n */\n\n\nfunction hasConstructorOf(a, b) {\n if (!a || _typeof(a) !== 'object') {\n return false;\n }\n\n var proto = getProto(a);\n\n if (!proto) {\n return b === null;\n }\n\n var Ctor = hasOwn$1.call(proto, 'constructor') && proto.constructor;\n\n if (typeof Ctor !== 'function') {\n return b === null;\n }\n\n if (b === Ctor) {\n return true;\n }\n\n if (b !== null && fnToString.call(Ctor) === fnToString.call(b)) {\n return true;\n }\n\n if (typeof b === 'function' && typeof Ctor.__typeson__type__ === 'string' && Ctor.__typeson__type__ === b.__typeson__type__) {\n return true;\n }\n\n return false;\n}\n/**\n *\n * @param {any} val\n * @returns {boolean}\n */\n\n\nfunction isPlainObject(val) {\n // Mirrors jQuery's\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object);\n}\n/**\n *\n * @param {any} val\n * @returns {boolean}\n */\n\n\nfunction isUserObject(val) {\n if (!val || toStringTag(val) !== 'Object') {\n return false;\n }\n\n var proto = getProto(val);\n\n if (!proto) {\n // `Object.create(null)`\n return true;\n }\n\n return hasConstructorOf(val, Object) || isUserObject(proto);\n}\n/**\n *\n * @param {any} v\n * @returns {boolean}\n */\n\n\nfunction isObject(v) {\n return v && _typeof(v) === 'object';\n}\n/**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\nfunction escapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~/g, '~0').replace(/\\./g, '~1');\n}\n/**\n *\n * @param {string} keyPathComponent\n * @returns {string}\n */\n\n\nfunction unescapeKeyPathComponent(keyPathComponent) {\n return keyPathComponent.replace(/~1/g, '.').replace(/~0/g, '~');\n}\n/**\n * @param {PlainObject|GenericArray} obj\n * @param {string} keyPath\n * @returns {any}\n */\n\n\nfunction getByKeyPath(obj, keyPath) {\n if (keyPath === '') {\n return obj;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.slice(period + 1));\n }\n\n return obj[unescapeKeyPathComponent(keyPath)];\n}\n/**\n *\n * @param {PlainObject} obj\n * @param {string} keyPath\n * @param {any} value\n * @returns {any}\n */\n\n\nfunction setAtKeyPath(obj, keyPath, value) {\n if (keyPath === '') {\n return value;\n }\n\n var period = keyPath.indexOf('.');\n\n if (period > -1) {\n var innerObj = obj[unescapeKeyPathComponent(keyPath.slice(0, period))];\n return setAtKeyPath(innerObj, keyPath.slice(period + 1), value);\n }\n\n obj[unescapeKeyPathComponent(keyPath)] = value;\n return obj;\n}\n/**\n *\n * @param {external:JSON} value\n * @returns {\"null\"|\"array\"|\"undefined\"|\"boolean\"|\"number\"|\"string\"|\n * \"object\"|\"symbol\"}\n */\n\n\nfunction getJSONType(value) {\n return value === null ? 'null' : Array.isArray(value) ? 'array' : _typeof(value);\n}\n\nfunction _await(value, then, direct) {\n if (direct) {\n return then ? then(value) : value;\n }\n\n if (!value || !value.then) {\n value = Promise.resolve(value);\n }\n\n return then ? value.then(then) : value;\n}\n\nvar keys = Object.keys,\n isArray = Array.isArray,\n hasOwn = {}.hasOwnProperty,\n internalStateObjPropsToIgnore = ['type', 'replaced', 'iterateIn', 'iterateUnsetNumeric'];\n/**\n * Handle plain object revivers first so reference setting can use\n * revived type (e.g., array instead of object); assumes revived\n * has same structure or will otherwise break subsequent references.\n * @param {PlainObjectType} a\n * @param {PlainObjectType} b\n * @returns {1|-1|boolean}\n */\n\nfunction _async(f) {\n return function () {\n for (var args = [], i = 0; i < arguments.length; i++) {\n args[i] = arguments[i];\n }\n\n try {\n return Promise.resolve(f.apply(this, args));\n } catch (e) {\n return Promise.reject(e);\n }\n };\n}\n/**\n * @callback Tester\n * @param {any} value\n * @param {StateObject} stateobj\n * @returns {boolean}\n */\n\n/**\n* @callback Replacer\n* @param {any} value\n* @param {StateObject} stateObj\n* @returns {any} Should be JSON-stringifiable\n*/\n\n/**\n* @callback Reviver\n* @param {JSON} value\n* @param {StateObject} stateObj\n* @returns {any}\n*/\n\n/**\n* @typedef {PlainObject} TypesonOptions\n* @property {boolean} stringification Auto-set by `stringify`\n*/\n\n/**\n * An instance of this class can be used to call `stringify()` and `parse()`.\n * Typeson resolves cyclic references by default. Can also be extended to\n * support custom types using the register() method.\n *\n * @class\n * @param {{cyclic: boolean}} [options] - if cyclic (default true),\n * cyclic references will be handled gracefully.\n */\n\n\nfunction _invoke(body, then) {\n var result = body();\n\n if (result && result.then) {\n return result.then(then);\n }\n\n return then(result);\n}\n\nfunction nestedPathsFirst(a, b) {\n if (a.keypath === '') {\n return -1;\n }\n\n var as = a.keypath.match(/\\./g) || 0;\n var bs = b.keypath.match(/\\./g) || 0;\n\n if (as) {\n as = as.length;\n }\n\n if (bs) {\n bs = bs.length;\n }\n\n return as > bs ? -1 : as < bs ? 1 : a.keypath < b.keypath ? -1 : a.keypath > b.keypath;\n}\n\nvar Typeson = /*#__PURE__*/function () {\n /**\n * @param {TypesonOptions} options\n */\n function Typeson(options) {\n _classCallCheck(this, Typeson);\n\n this.options = options; // Replacers signature: replace (value). Returns falsy if not\n // replacing. Otherwise ['Date', value.getTime()]\n\n this.plainObjectReplacers = [];\n this.nonplainObjectReplacers = []; // Revivers: [{type => reviver}, {plain: boolean}].\n // Sample: [{'Date': value => new Date(value)}, {plain: false}]\n\n this.revivers = {};\n /** Types registered via `register()`. */\n\n this.types = {};\n }\n /**\n * @typedef {null|boolean|number|string|GenericArray|PlainObject} JSON\n */\n\n /**\n * @callback JSONReplacer\n * @param {\"\"|string} key\n * @param {JSON} value\n * @returns {number|string|boolean|null|PlainObject|undefined}\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The%20replacer%20parameter\n */\n\n /**\n * Serialize given object to Typeson.\n * Initial arguments work identical to those of `JSON.stringify`.\n * The `replacer` argument has nothing to do with our replacers.\n * @param {any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {TypesonOptions} opts\n * @returns {string|Promise} Promise resolves to a string\n */\n\n\n _createClass(Typeson, [{\n key: \"stringify\",\n value: function stringify(obj, replacer, space, opts) {\n opts = _objectSpread2(_objectSpread2(_objectSpread2({}, this.options), opts), {}, {\n stringification: true\n });\n var encapsulated = this.encapsulate(obj, null, opts);\n\n if (isArray(encapsulated)) {\n return JSON.stringify(encapsulated[0], replacer, space);\n }\n\n return encapsulated.then(function (res) {\n return JSON.stringify(res, replacer, space);\n });\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {TypesonOptions} opts\n * @returns {string}\n */\n\n }, {\n key: \"stringifySync\",\n value: function stringifySync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n *\n * @param {any} obj\n * @param {JSONReplacer|string[]} replacer\n * @param {number|string} space\n * @param {TypesonOptions} opts\n * @returns {Promise}\n */\n\n }, {\n key: \"stringifyAsync\",\n value: function stringifyAsync(obj, replacer, space, opts) {\n return this.stringify(obj, replacer, space, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * @callback JSONReviver\n * @param {string} key\n * @param {JSON} value\n * @returns {JSON}\n */\n\n /**\n * Parse Typeson back into an obejct.\n * Initial arguments works identical to those of `JSON.parse()`.\n * @param {string} text\n * @param {JSONReviver} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {TypesonOptions} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parse\",\n value: function parse(text, reviver, opts) {\n opts = _objectSpread2(_objectSpread2(_objectSpread2({}, this.options), opts), {}, {\n parse: true\n });\n return this.revive(JSON.parse(text, reviver), opts);\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {string} text\n * @param {JSONReviver} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {TypesonOptions} opts\n * @returns {external:JSON}\n */\n\n }, {\n key: \"parseSync\",\n value: function parseSync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n * @param {string} text\n * @param {JSONReviver} reviver This JSON reviver has nothing to do with\n * our revivers.\n * @param {TypesonOptions} opts\n * @returns {Promise} Resolves to `external:JSON`\n */\n\n }, {\n key: \"parseAsync\",\n value: function parseAsync(text, reviver, opts) {\n return this.parse(text, reviver, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * @typedef {} StateObject\n */\n\n /**\n *\n * @param {any} obj\n * @param {StateObject} stateObj\n * @param {TypesonOptions} [opts={}]\n * @returns {string[]|false}\n */\n\n }, {\n key: \"specialTypeNames\",\n value: function specialTypeNames(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.returnTypeNames = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n *\n * @param {any} obj\n * @param {PlainObject} stateObj\n * @param {PlainObject} [opts={}]\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"rootTypeName\",\n value: function rootTypeName(obj, stateObj) {\n var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n opts.iterateNone = true;\n return this.encapsulate(obj, stateObj, opts);\n }\n /**\n * Encapsulate a complex object into a plain Object by replacing\n * registered types with plain objects representing the types data.\n *\n * This method is used internally by `Typeson.stringify()`.\n * @param {any} obj - Object to encapsulate.\n * @param {PlainObject} stateObj\n * @param {PlainObject} opts\n * @returns {Promise|GenericArray|PlainObject|string|false}\n */\n\n }, {\n key: \"encapsulate\",\n value: function encapsulate(obj, stateObj, opts) {\n /**\n *\n * @param {any} ret\n * @param {GenericArray} promisesData\n * @returns {Promise}\n */\n var checkPromises = _async(function (ret, promisesData) {\n return _await(Promise.all(promisesData.map(function (pd) {\n return pd[1].p;\n })), function (promResults) {\n return _await(Promise.all(promResults.map(_async(function (promResult) {\n var _exit = false;\n var newPromisesData = [];\n\n var _promisesData$splice = promisesData.splice(0, 1),\n _promisesData$splice2 = _slicedToArray(_promisesData$splice, 1),\n prData = _promisesData$splice2[0];\n\n var _prData = _slicedToArray(prData, 7),\n keyPath = _prData[0],\n cyclic = _prData[2],\n stateObj = _prData[3],\n parentObj = _prData[4],\n key = _prData[5],\n detectedType = _prData[6];\n\n var encaps = _encapsulate(keyPath, promResult, cyclic, stateObj, newPromisesData, true, detectedType);\n\n var isTypesonPromise = hasConstructorOf(encaps, TypesonPromise); // Handle case where an embedded custom type itself\n // returns a `Typeson.Promise`\n\n return _invoke(function () {\n if (keyPath && isTypesonPromise) {\n return _await(encaps.p, function (encaps2) {\n parentObj[key] = encaps2;\n _exit = true;\n return checkPromises(ret, newPromisesData);\n });\n }\n }, function (_result) {\n if (_exit) return _result;\n\n if (keyPath) {\n parentObj[key] = encaps;\n } else if (isTypesonPromise) {\n ret = encaps.p;\n } else {\n // If this is itself a `Typeson.Promise` (because the\n // original value supplied was a `Promise` or\n // because the supplied custom type value resolved\n // to one), returning it below will be fine since\n // a `Promise` is expected anyways given current\n // config (and if not a `Promise`, it will be ready\n // as the resolve value)\n ret = encaps;\n }\n\n return checkPromises(ret, newPromisesData);\n });\n }))), function () {\n return ret;\n });\n });\n });\n /**\n * @typedef {PlainObject} OwnKeysObject\n * @property {boolean} ownKeys\n */\n\n /**\n * @callback BuiltinStateObjectPropertiesCallback\n * @returns {void}\n */\n\n /**\n *\n * @param {StateObject} stateObj\n * @param {OwnKeysObject} ownKeysObj\n * @param {BuiltinStateObjectPropertiesCallback} cb\n * @returns {undefined}\n */\n\n\n opts = _objectSpread2(_objectSpread2({\n sync: true\n }, this.options), opts);\n var _opts = opts,\n sync = _opts.sync;\n var that = this,\n types = {},\n refObjs = [],\n // For checking cyclic references\n refKeys = [],\n // For checking cyclic references\n promisesDataRoot = []; // Clone the object deeply while at the same time replacing any\n // special types or cyclic reference:\n\n var cyclic = 'cyclic' in opts ? opts.cyclic : true;\n var _opts2 = opts,\n encapsulateObserver = _opts2.encapsulateObserver;\n\n var ret = _encapsulate('', obj, cyclic, stateObj || {}, promisesDataRoot);\n /**\n *\n * @param {any} ret\n * @returns {GenericArray|PlainObject|string|false}\n */\n\n\n function finish(ret) {\n // Add `$types` to result only if we ever bumped into a\n // special type (or special case where object has own `$types`)\n var typeNames = Object.values(types);\n\n if (opts.iterateNone) {\n if (typeNames.length) {\n return typeNames[0];\n }\n\n return Typeson.getJSONType(ret);\n }\n\n if (typeNames.length) {\n if (opts.returnTypeNames) {\n return _toConsumableArray(new Set(typeNames));\n } // Special if array (or a primitive) was serialized\n // because JSON would ignore custom `$types` prop on it\n\n\n if (!ret || !isPlainObject(ret) || // Also need to handle if this is an object with its\n // own `$types` property (to avoid ambiguity)\n hasOwn.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: {\n $: types\n }\n };\n } else {\n ret.$types = types;\n } // No special types\n\n } else if (isObject(ret) && hasOwn.call(ret, '$types')) {\n ret = {\n $: ret,\n $types: true\n };\n }\n\n if (opts.returnTypeNames) {\n return false;\n }\n\n return ret;\n }\n\n function _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, cb) {\n Object.assign(stateObj, ownKeysObj);\n var vals = internalStateObjPropsToIgnore.map(function (prop) {\n var tmp = stateObj[prop];\n delete stateObj[prop];\n return tmp;\n }); // eslint-disable-next-line node/callback-return\n\n cb();\n internalStateObjPropsToIgnore.forEach(function (prop, i) {\n stateObj[prop] = vals[i];\n });\n }\n /**\n *\n * @param {string} keypath\n * @param {any} value\n * @param {boolean} cyclic\n * @param {PlainObject} stateObj\n * @param {boolean} promisesData\n * @param {boolean} resolvingTypesonPromise\n * @param {string} detectedType\n * @returns {any}\n */\n\n\n function _encapsulate(keypath, value, cyclic, stateObj, promisesData, resolvingTypesonPromise, detectedType) {\n var ret;\n var observerData = {};\n\n var $typeof = _typeof(value);\n\n var runObserver = encapsulateObserver ? function (obj) {\n var type = detectedType || stateObj.type || Typeson.getJSONType(value);\n encapsulateObserver(Object.assign(obj || observerData, {\n keypath: keypath,\n value: value,\n cyclic: cyclic,\n stateObj: stateObj,\n promisesData: promisesData,\n resolvingTypesonPromise: resolvingTypesonPromise,\n awaitingTypesonPromise: hasConstructorOf(value, TypesonPromise)\n }, {\n type: type\n }));\n } : null;\n\n if (['string', 'boolean', 'number', 'undefined'].includes($typeof)) {\n if (value === undefined || Number.isNaN(value) || value === Number.NEGATIVE_INFINITY || value === Number.POSITIVE_INFINITY) {\n ret = stateObj.replaced ? value : replace(keypath, value, stateObj, promisesData, false, resolvingTypesonPromise, runObserver);\n\n if (ret !== value) {\n observerData = {\n replaced: ret\n };\n }\n } else {\n ret = value;\n }\n\n if (runObserver) {\n runObserver();\n }\n\n return ret;\n }\n\n if (value === null) {\n if (runObserver) {\n runObserver();\n }\n\n return value;\n }\n\n if (cyclic && !stateObj.iterateIn && !stateObj.iterateUnsetNumeric && value && _typeof(value) === 'object') {\n // Options set to detect cyclic references and be able\n // to rewrite them.\n var refIndex = refObjs.indexOf(value);\n\n if (refIndex < 0) {\n if (cyclic === true) {\n refObjs.push(value);\n refKeys.push(keypath);\n }\n } else {\n types[keypath] = '#';\n\n if (runObserver) {\n runObserver({\n cyclicKeypath: refKeys[refIndex]\n });\n }\n\n return '#' + refKeys[refIndex];\n }\n }\n\n var isPlainObj = isPlainObject(value);\n var isArr = isArray(value);\n var replaced = // Running replace will cause infinite loop as will test\n // positive again\n (isPlainObj || isArr) && (!that.plainObjectReplacers.length || stateObj.replaced) || stateObj.iterateIn ? // Optimization: if plain object and no plain-object\n // replacers, don't try finding a replacer\n value : replace(keypath, value, stateObj, promisesData, isPlainObj || isArr, null, runObserver);\n var clone;\n\n if (replaced !== value) {\n ret = replaced;\n observerData = {\n replaced: replaced\n };\n } else {\n // eslint-disable-next-line no-lonely-if\n if (keypath === '' && hasConstructorOf(value, TypesonPromise)) {\n promisesData.push([keypath, value, cyclic, stateObj, undefined, undefined, stateObj.type]);\n ret = value;\n } else if (isArr && stateObj.iterateIn !== 'object' || stateObj.iterateIn === 'array') {\n // eslint-disable-next-line unicorn/no-new-array -- Sparse\n clone = new Array(value.length);\n observerData = {\n clone: clone\n };\n } else if (!['function', 'symbol'].includes(_typeof(value)) && !('toJSON' in value) && !hasConstructorOf(value, TypesonPromise) && !hasConstructorOf(value, Promise) && !hasConstructorOf(value, ArrayBuffer) || isPlainObj || stateObj.iterateIn === 'object') {\n clone = {};\n\n if (stateObj.addLength) {\n clone.length = value.length;\n }\n\n observerData = {\n clone: clone\n };\n } else {\n ret = value; // Only clone vanilla objects and arrays\n }\n }\n\n if (runObserver) {\n runObserver();\n }\n\n if (opts.iterateNone) {\n return clone || ret;\n }\n\n if (!clone) {\n return ret;\n } // Iterate object or array\n\n\n if (stateObj.iterateIn) {\n var _loop = function _loop(key) {\n var ownKeysObj = {\n ownKeys: hasOwn.call(value, key)\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n };\n\n // eslint-disable-next-line guard-for-in\n for (var key in value) {\n _loop(key);\n }\n\n if (runObserver) {\n runObserver({\n endIterateIn: true,\n end: true\n });\n }\n } else {\n // Note: Non-indexes on arrays won't survive stringify so\n // somewhat wasteful for arrays, but so too is iterating\n // all numeric indexes on sparse arrays when not wanted\n // or filtering own keys for positive integers\n keys(value).forEach(function (key) {\n var kp = keypath + (keypath ? '.' : '') + escapeKeyPathComponent(key);\n var ownKeysObj = {\n ownKeys: true\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, value[key], Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, key, stateObj.type]);\n } else if (val !== undefined) {\n clone[key] = val;\n }\n });\n });\n\n if (runObserver) {\n runObserver({\n endIterateOwn: true,\n end: true\n });\n }\n } // Iterate array for non-own numeric properties (we can't\n // replace the prior loop though as it iterates non-integer\n // keys)\n\n\n if (stateObj.iterateUnsetNumeric) {\n var vl = value.length;\n\n var _loop2 = function _loop2(i) {\n if (!(i in value)) {\n // No need to escape numeric\n var kp = keypath + (keypath ? '.' : '') + i;\n var ownKeysObj = {\n ownKeys: false\n };\n\n _adaptBuiltinStateObjectProperties(stateObj, ownKeysObj, function () {\n var val = _encapsulate(kp, undefined, Boolean(cyclic), stateObj, promisesData, resolvingTypesonPromise);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n promisesData.push([kp, val, Boolean(cyclic), stateObj, clone, i, stateObj.type]);\n } else if (val !== undefined) {\n clone[i] = val;\n }\n });\n }\n };\n\n for (var i = 0; i < vl; i++) {\n _loop2(i);\n }\n\n if (runObserver) {\n runObserver({\n endIterateUnsetNumeric: true,\n end: true\n });\n }\n }\n\n return clone;\n }\n /**\n * @typedef {PlainObject} KeyPathEvent\n * @property {string} cyclicKeypath\n */\n\n /**\n * @typedef {PlainObject} EndIterateInEvent\n * @property {boolean} endIterateIn\n * @property {boolean} end\n */\n\n /**\n * @typedef {PlainObject} EndIterateUnsetNumericEvent\n * @property {boolean} endIterateUnsetNumeric\n * @property {boolean} end\n */\n\n /**\n * @typedef {PlainObject} TypeDetectedEvent\n * @property {boolean} typeDetected\n */\n\n /**\n * @typedef {PlainObject} ReplacingEvent\n * @property {boolean} replacing\n */\n\n /**\n * @callback Observer\n * @param {KeyPathEvent|EndIterateInEvent|EndIterateUnsetNumericEvent|\n * TypeDetectedEvent|ReplacingEvent} [event]\n * @returns {void}\n */\n\n /**\n *\n * @param {string} keypath\n * @param {any} value\n * @param {PlainObject} stateObj\n * @param {GenericArray} promisesData\n * @param {boolean} plainObject\n * @param {boolean} resolvingTypesonPromise\n * @param {Observer} [runObserver]\n * @returns {any}\n */\n\n\n function replace(keypath, value, stateObj, promisesData, plainObject, resolvingTypesonPromise, runObserver) {\n // Encapsulate registered types\n var replacers = plainObject ? that.plainObjectReplacers : that.nonplainObjectReplacers;\n var i = replacers.length;\n\n while (i--) {\n var replacer = replacers[i];\n\n if (replacer.test(value, stateObj)) {\n var type = replacer.type;\n\n if (that.revivers[type]) {\n // Record the type only if a corresponding reviver\n // exists. This is to support specs where only\n // replacement is done.\n // For example, ensuring deep cloning of the object,\n // or replacing a type to its equivalent without\n // the need to revive it.\n var existing = types[keypath]; // type can comprise an array of types (see test\n // \"should support intermediate types\")\n\n types[keypath] = existing ? [type].concat(existing) : type;\n }\n\n Object.assign(stateObj, {\n type: type,\n replaced: true\n });\n\n if ((sync || !replacer.replaceAsync) && !replacer.replace) {\n if (runObserver) {\n runObserver({\n typeDetected: true\n });\n }\n\n return _encapsulate(keypath, value, cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n\n if (runObserver) {\n runObserver({\n replacing: true\n });\n } // Now, also traverse the result in case it contains its\n // own types to replace\n\n\n var replaceMethod = sync || !replacer.replaceAsync ? 'replace' : 'replaceAsync';\n return _encapsulate(keypath, replacer[replaceMethod](value, stateObj), cyclic && 'readonly', stateObj, promisesData, resolvingTypesonPromise, type);\n }\n }\n\n return value;\n }\n\n return promisesDataRoot.length ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : Promise.resolve(checkPromises(ret, promisesDataRoot)).then(finish) : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() // If this is a synchronous request for stringification, yet\n // a promise is the result, we don't want to resolve leading\n // to an async result, so we return an array to avoid\n // ambiguity\n : opts.stringification && sync ? [finish(ret)] : sync ? finish(ret) : Promise.resolve(finish(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {any} obj\n * @param {StateObject} stateObj\n * @param {TypesonOptions} opts\n * @returns {any}\n */\n\n }, {\n key: \"encapsulateSync\",\n value: function encapsulateSync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n * @param {any} obj\n * @param {StateObject} stateObj\n * @param {TypesonOptions} opts\n * @returns {any}\n */\n\n }, {\n key: \"encapsulateAsync\",\n value: function encapsulateAsync(obj, stateObj, opts) {\n return this.encapsulate(obj, stateObj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * Revive an encapsulated object.\n * This method is used internally by `Typeson.parse()`.\n * @param {PlainObject} obj - Object to revive. If it has `$types` member,\n * the properties that are listed there will be replaced with its true\n * type instead of just plain objects.\n * @param {TypesonOptions} opts\n * @throws TypeError If mismatch between sync/async type and result\n * @returns {Promise|any} If async, returns a Promise that resolves\n * to `any`.\n */\n\n }, {\n key: \"revive\",\n value: function revive(obj, opts) {\n var types = obj && obj.$types; // No type info added. Revival not needed.\n\n if (!types) {\n return obj;\n } // Object happened to have own `$types` property but with\n // no actual types, so we unescape and return that object\n\n\n if (types === true) {\n return obj.$;\n }\n\n opts = _objectSpread2(_objectSpread2({\n sync: true\n }, this.options), opts);\n var _opts3 = opts,\n sync = _opts3.sync;\n var keyPathResolutions = [];\n var stateObj = {};\n var ignore$Types = true; // Special when root object is not a trivial Object, it will\n // be encapsulated in `$`. It will also be encapsulated in\n // `$` if it has its own `$` property to avoid ambiguity\n\n if (types.$ && isPlainObject(types.$)) {\n obj = obj.$;\n types = types.$;\n ignore$Types = false;\n }\n\n var that = this;\n /**\n * @callback RevivalReducer\n * @param {any} value\n * @param {string} type\n * @returns {any}\n */\n\n /**\n *\n * @param {string} type\n * @param {any} val\n * @throws {Error}\n * @returns {any}\n */\n\n function executeReviver(type, val) {\n var _ref = that.revivers[type] || [],\n _ref2 = _slicedToArray(_ref, 1),\n reviver = _ref2[0];\n\n if (!reviver) {\n throw new Error('Unregistered type: ' + type);\n } // Only `sync` expected here, as problematic async would\n // be missing both `reviver` and `reviverAsync`, and\n // encapsulation shouldn't have added types, so\n // should have made an early exit\n\n\n if (sync && !('revive' in reviver)) {\n // Just return value as is\n return val;\n }\n\n return reviver[sync && reviver.revive ? 'revive' : !sync && reviver.reviveAsync ? 'reviveAsync' : 'revive'](val, stateObj);\n }\n /**\n *\n * @returns {void|TypesonPromise}\n */\n\n\n function revivePlainObjects() {\n // const references = [];\n // const reviveTypes = [];\n var plainObjectTypes = [];\n Object.entries(types).forEach(function (_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n keypath = _ref4[0],\n type = _ref4[1];\n\n if (type === '#') {\n /*\n references.push({\n keypath,\n reference: getByKeyPath(obj, keypath)\n });\n */\n return;\n }\n\n [].concat(type).forEach(function (type) {\n var _ref5 = that.revivers[type] || [null, {}],\n _ref6 = _slicedToArray(_ref5, 2),\n plain = _ref6[1].plain;\n\n if (!plain) {\n // reviveTypes.push({keypath, type});\n return;\n }\n\n plainObjectTypes.push({\n keypath: keypath,\n type: type\n });\n delete types[keypath]; // Avoid repeating\n });\n });\n\n if (!plainObjectTypes.length) {\n return undefined;\n } // console.log(plainObjectTypes.sort(nestedPathsFirst));\n\n /**\n * @typedef {PlainObject} PlainObjectType\n * @property {string} keypath\n * @property {string} type\n */\n\n\n return plainObjectTypes.sort(nestedPathsFirst).reduce(function reducer(possibleTypesonPromise, _ref7) {\n var keypath = _ref7.keypath,\n type = _ref7.type;\n\n if (isThenable(possibleTypesonPromise)) {\n return possibleTypesonPromise.then(function (val) {\n return reducer(val, {\n keypath: keypath,\n type: type\n });\n });\n } // console.log('obj', JSON.stringify(keypath), obj);\n\n\n var val = getByKeyPath(obj, keypath);\n val = executeReviver(type, val);\n\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n var newVal = setAtKeyPath(obj, keypath, v);\n\n if (newVal === v) {\n obj = newVal;\n }\n\n return undefined;\n });\n }\n\n var newVal = setAtKeyPath(obj, keypath, val);\n\n if (newVal === val) {\n obj = newVal;\n }\n\n return undefined;\n }, undefined // This argument must be explicit\n ); // references.forEach(({keypath, reference}) => {});\n // reviveTypes.sort(nestedPathsFirst).forEach(() => {});\n }\n\n var revivalPromises = [];\n /**\n *\n * @param {string} keypath\n * @param {any} value\n * @param {?(GenericArray|PlainObject)} target\n * @param {GenericArray|PlainObject} [clone]\n * @param {string} [key]\n * @returns {any}\n */\n\n function _revive(keypath, value, target, clone, key) {\n if (ignore$Types && keypath === '$types') {\n return undefined;\n }\n\n var type = types[keypath];\n var isArr = isArray(value);\n\n if (isArr || isPlainObject(value)) {\n // eslint-disable-next-line unicorn/no-new-array -- Sparse\n var _clone = isArr ? new Array(value.length) : {}; // Iterate object or array\n\n\n keys(value).forEach(function (k) {\n var val = _revive(keypath + (keypath ? '.' : '') + escapeKeyPathComponent(k), value[k], target || _clone, _clone, k);\n\n var set = function set(v) {\n if (hasConstructorOf(v, Undefined)) {\n _clone[k] = undefined;\n } else if (v !== undefined) {\n _clone[k] = v;\n }\n\n return v;\n };\n\n if (hasConstructorOf(val, TypesonPromise)) {\n revivalPromises.push(val.then(function (ret) {\n return set(ret);\n }));\n } else {\n set(val);\n }\n });\n value = _clone; // Try to resolve cyclic reference as soon as available\n\n while (keyPathResolutions.length) {\n var _keyPathResolutions$ = _slicedToArray(keyPathResolutions[0], 4),\n _target = _keyPathResolutions$[0],\n keyPath = _keyPathResolutions$[1],\n _clone2 = _keyPathResolutions$[2],\n k = _keyPathResolutions$[3];\n\n var val = getByKeyPath(_target, keyPath); // Typeson.Undefined not expected here as not cyclic or\n // `undefined`\n\n if (val !== undefined) {\n _clone2[k] = val;\n } else {\n break;\n }\n\n keyPathResolutions.splice(0, 1);\n }\n }\n\n if (!type) {\n return value;\n }\n\n if (type === '#') {\n var _ret = getByKeyPath(target, value.slice(1));\n\n if (_ret === undefined) {\n // Cyclic reference not yet available\n keyPathResolutions.push([target, value.slice(1), clone, key]);\n }\n\n return _ret;\n } // `type` can be an array here\n\n\n return [].concat(type).reduce(function reducer(val, typ) {\n if (hasConstructorOf(val, TypesonPromise)) {\n return val.then(function (v) {\n // TypesonPromise here too\n return reducer(v, typ);\n });\n }\n\n return executeReviver(typ, val);\n }, value);\n }\n /**\n *\n * @param {any} retrn\n * @returns {undefined|any}\n */\n\n\n function checkUndefined(retrn) {\n return hasConstructorOf(retrn, Undefined) ? undefined : retrn;\n }\n\n var possibleTypesonPromise = revivePlainObjects();\n var ret;\n\n if (hasConstructorOf(possibleTypesonPromise, TypesonPromise)) {\n ret = possibleTypesonPromise.then(function () {\n return obj;\n });\n } else {\n ret = _revive('', obj, null);\n\n if (revivalPromises.length) {\n // Ensure children resolved\n ret = TypesonPromise.resolve(ret).then(function (r) {\n return TypesonPromise.all([// May be a TypesonPromise or not\n r].concat(revivalPromises));\n }).then(function (_ref8) {\n var _ref9 = _slicedToArray(_ref8, 1),\n r = _ref9[0];\n\n return r;\n });\n }\n }\n\n return isThenable(ret) ? sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Sync method requested but async result obtained');\n }() : hasConstructorOf(ret, TypesonPromise) ? ret.p.then(checkUndefined) : ret : !sync && opts.throwOnBadSyncType ? function () {\n throw new TypeError('Async method requested but sync result obtained');\n }() : sync ? checkUndefined(ret) : Promise.resolve(checkUndefined(ret));\n }\n /**\n * Also sync but throws on non-sync result.\n * @param {any} obj\n * @param {TypesonOptions} opts\n * @returns {any}\n */\n\n }, {\n key: \"reviveSync\",\n value: function reviveSync(obj, opts) {\n return this.revive(obj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: true\n }));\n }\n /**\n * @param {any} obj\n * @param {TypesonOptions} opts\n * @returns {Promise}\n */\n\n }, {\n key: \"reviveAsync\",\n value: function reviveAsync(obj, opts) {\n return this.revive(obj, _objectSpread2(_objectSpread2({\n throwOnBadSyncType: true\n }, opts), {}, {\n sync: false\n }));\n }\n /**\n * @typedef {Tester|Replacer|Reviver} Spec\n */\n\n /**\n * Register types.\n * For examples on how to use this method, see\n * {@link https://github.com/dfahlander/typeson-registry/tree/master/types}.\n * @param {object[]} typeSpecSets -\n * Types and their functions [test, encapsulate, revive];\n * @param {TypesonOptions} opts\n * @returns {Typeson}\n */\n\n }, {\n key: \"register\",\n value: function register(typeSpecSets, opts) {\n opts = opts || {};\n [].concat(typeSpecSets).forEach(function R(typeSpec) {\n var _this = this;\n\n // Allow arrays of arrays of arrays...\n if (isArray(typeSpec)) {\n return typeSpec.map(function (typSpec) {\n return R.call(_this, typSpec);\n });\n }\n\n typeSpec && keys(typeSpec).forEach(function (typeId) {\n if (typeId === '#') {\n throw new TypeError('# cannot be used as a type name as it is reserved ' + 'for cyclic objects');\n } else if (Typeson.JSON_TYPES.includes(typeId)) {\n throw new TypeError('Plain JSON object types are reserved as type names');\n }\n\n var spec = typeSpec[typeId];\n var replacers = spec && spec.testPlainObjects ? this.plainObjectReplacers : this.nonplainObjectReplacers;\n var existingReplacer = replacers.filter(function (r) {\n return r.type === typeId;\n });\n\n if (existingReplacer.length) {\n // Remove existing spec and replace with this one.\n replacers.splice(replacers.indexOf(existingReplacer[0]), 1);\n delete this.revivers[typeId];\n delete this.types[typeId];\n }\n\n if (typeof spec === 'function') {\n // Support registering just a class without replacer/reviver\n var Class = spec;\n spec = {\n test: function test(x) {\n return x && x.constructor === Class;\n },\n replace: function replace(x) {\n return _objectSpread2({}, x);\n },\n revive: function revive(x) {\n return Object.assign(Object.create(Class.prototype), x);\n }\n };\n } else if (isArray(spec)) {\n var _spec = spec,\n _spec2 = _slicedToArray(_spec, 3),\n test = _spec2[0],\n replace = _spec2[1],\n revive = _spec2[2];\n\n spec = {\n test: test,\n replace: replace,\n revive: revive\n };\n }\n\n if (!spec || !spec.test) {\n return;\n }\n\n var replacerObj = {\n type: typeId,\n test: spec.test.bind(spec)\n };\n\n if (spec.replace) {\n replacerObj.replace = spec.replace.bind(spec);\n }\n\n if (spec.replaceAsync) {\n replacerObj.replaceAsync = spec.replaceAsync.bind(spec);\n }\n\n var start = typeof opts.fallback === 'number' ? opts.fallback : opts.fallback ? 0 : Number.POSITIVE_INFINITY;\n\n if (spec.testPlainObjects) {\n this.plainObjectReplacers.splice(start, 0, replacerObj);\n } else {\n this.nonplainObjectReplacers.splice(start, 0, replacerObj);\n } // Todo: We might consider a testAsync type\n\n\n if (spec.revive || spec.reviveAsync) {\n var reviverObj = {};\n\n if (spec.revive) {\n reviverObj.revive = spec.revive.bind(spec);\n }\n\n if (spec.reviveAsync) {\n reviverObj.reviveAsync = spec.reviveAsync.bind(spec);\n }\n\n this.revivers[typeId] = [reviverObj, {\n plain: spec.testPlainObjects\n }];\n } // Record to be retrieved via public types property.\n\n\n this.types[typeId] = spec;\n }, this);\n }, this);\n return this;\n }\n }]);\n\n return Typeson;\n}();\n/**\n * We keep this function minimized so if using two instances of this\n * library, where one is minimized and one is not, it will still work\n * with `hasConstructorOf`.\n * @class\n */\n\n\nvar Undefined = function Undefined() {\n _classCallCheck(this, Undefined);\n}; // eslint-disable-line space-before-blocks\n\n\nUndefined.__typeson__type__ = 'TypesonUndefined'; // The following provide classes meant to avoid clashes with other values\n// To insist `undefined` should be added\n\nTypeson.Undefined = Undefined; // To support async encapsulation/stringification\n\nTypeson.Promise = TypesonPromise; // Some fundamental type-checking utilities\n\nTypeson.isThenable = isThenable;\nTypeson.toStringTag = toStringTag;\nTypeson.hasConstructorOf = hasConstructorOf;\nTypeson.isObject = isObject;\nTypeson.isPlainObject = isPlainObject;\nTypeson.isUserObject = isUserObject;\nTypeson.escapeKeyPathComponent = escapeKeyPathComponent;\nTypeson.unescapeKeyPathComponent = unescapeKeyPathComponent;\nTypeson.getByKeyPath = getByKeyPath;\nTypeson.getJSONType = getJSONType;\nTypeson.JSON_TYPES = ['null', 'boolean', 'number', 'string', 'array', 'object'];\n\nexport default Typeson;\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.\n\nvar lookup = new Uint8Array(256);\n\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n/**\n * @param {ArrayBuffer} arraybuffer\n * @param {Integer} byteOffset\n * @param {Integer} lngth\n * @returns {string}\n */\n\n\nvar encode = function encode(arraybuffer, byteOffset, lngth) {\n if (lngth === null || lngth === undefined) {\n lngth = arraybuffer.byteLength; // Needed for Safari\n }\n\n var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari\n lngth);\n var len = bytes.length;\n var base64 = '';\n\n for (var _i = 0; _i < len; _i += 3) {\n base64 += chars[bytes[_i] >> 2];\n base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];\n base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];\n base64 += chars[bytes[_i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.slice(0, -1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.slice(0, -2) + '==';\n }\n\n return base64;\n};\n/**\n * @param {string} base64\n * @returns {ArrayBuffer}\n */\n\nvar decode = function decode(base64) {\n var len = base64.length;\n var bufferLength = base64.length * 0.75;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (var _i2 = 0; _i2 < len; _i2 += 4) {\n encoded1 = lookup[base64.charCodeAt(_i2)];\n encoded2 = lookup[base64.charCodeAt(_i2 + 1)];\n encoded3 = lookup[base64.charCodeAt(_i2 + 2)];\n encoded4 = lookup[base64.charCodeAt(_i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n\n return arraybuffer;\n};\n\nexport { decode, encode };\n","import Typeson from 'typeson';\n\nconst userObject = {\n userObject: {\n test (x, stateObj) { return Typeson.isUserObject(x); },\n replace (n) { return {...n}; },\n revive (s) { return s; }\n }\n};\n\nexport default userObject;\n","const arrayNonindexKeys = [\n {\n arrayNonindexKeys: {\n testPlainObjects: true,\n test (x, stateObj) {\n if (Array.isArray(x)) {\n if (\n // By avoiding serializing arrays into objects which\n // have only positive-integer keys, we reduce\n // size and improve revival performance; arrays with\n // non-index keys will be larger however\n Object.keys(x).some((k) => {\n // No need to check for `isNaN` or\n // `isNaN(Number.parseInt())` as `NaN` will be\n // treated as a string.\n // No need to do check as\n // `Number.parseInt(Number())` since scientific\n // notation will be pre-resolved if a number\n // was given, and it will otherwise be a string\n return String(Number.parseInt(k)) !== k;\n })\n ) {\n stateObj.iterateIn = 'object';\n stateObj.addLength = true;\n }\n return true;\n }\n return false;\n },\n replace (a, stateObj) {\n // Catch sparse undefined\n stateObj.iterateUnsetNumeric = true;\n return a;\n },\n revive (o) {\n if (Array.isArray(o)) {\n return o;\n }\n const arr = [];\n // No map here as may be a sparse array (including\n // with `length` set)\n // Todo: Reenable when Node `engines` >= 7\n // Object.entries(o).forEach(([key, val]) => {\n Object.keys(o).forEach((key) => {\n const val = o[key];\n arr[key] = val;\n });\n return arr;\n }\n }\n },\n {\n sparseUndefined: {\n test (x, stateObj) {\n return typeof x === 'undefined' && stateObj.ownKeys === false;\n },\n replace (n) { return 0; },\n revive (s) { return undefined; } // Will avoid adding anything\n }\n }\n];\n\nexport default arrayNonindexKeys;\n","// This does not preserve `undefined` in sparse arrays; see the `undefined`\n// or `sparse-undefined` preset\nimport Typeson from 'typeson';\n\nconst undef = {\n undef: {\n test (x, stateObj) {\n return typeof x === 'undefined' &&\n (stateObj.ownKeys || !('ownKeys' in stateObj));\n },\n replace (n) { return 0; },\n revive (s) {\n // Will add `undefined` (returning `undefined` would instead\n // avoid explicitly setting)\n return new Typeson.Undefined();\n }\n }\n};\n\nexport default undef;\n","// This module is for objectified primitives (such as `new Number(3)` or\n// `new String(\"foo\")`)\n/* eslint-disable no-new-wrappers, unicorn/new-for-builtins */\nimport Typeson from 'typeson';\n\nconst primitiveObjects = {\n // String Object (not primitive string which need no type spec)\n StringObject: {\n test (x) {\n return Typeson.toStringTag(x) === 'String' && typeof x === 'object';\n },\n replace (s) { return String(s); }, // convert to primitive string\n revive (s) { return new String(s); } // Revive to an objectified string\n },\n // Boolean Object (not primitive boolean which need no type spec)\n BooleanObject: {\n test (x) {\n return Typeson.toStringTag(x) === 'Boolean' &&\n typeof x === 'object';\n },\n replace (b) { return Boolean(b); }, // convert to primitive boolean\n revive (b) {\n // Revive to an objectified Boolean\n return new Boolean(b);\n }\n },\n // Number Object (not primitive number which need no type spec)\n NumberObject: {\n test (x) {\n return Typeson.toStringTag(x) === 'Number' && typeof x === 'object';\n },\n replace (n) { return Number(n); }, // convert to primitive number\n revive (n) { return new Number(n); } // Revive to an objectified number\n }\n};\n/* eslint-enable no-new-wrappers, unicorn/new-for-builtins */\n\nexport default primitiveObjects;\n","import nan from '../types/nan.js';\nimport infinity from '../types/infinity.js';\nimport NegativeInfinity from '../types/negative-infinity.js';\n\nconst specialNumbers = [\n nan,\n infinity,\n NegativeInfinity\n];\n\nexport default specialNumbers;\n","const nan = {\n nan: {\n test (x) { return Number.isNaN(x); },\n replace (n) { return 'NaN'; },\n revive (s) { return Number.NaN; }\n }\n};\n\nexport default nan;\n","const infinity = {\n infinity: {\n test (x) { return x === Number.POSITIVE_INFINITY; },\n replace (n) { return 'Infinity'; },\n revive (s) { return Number.POSITIVE_INFINITY; }\n }\n};\n\nexport default infinity;\n","const negativeInfinity = {\n negativeInfinity: {\n test (x) { return x === Number.NEGATIVE_INFINITY; },\n replace (n) { return '-Infinity'; },\n revive (s) { return Number.NEGATIVE_INFINITY; }\n }\n};\n\nexport default negativeInfinity;\n","import Typeson from 'typeson';\n\nconst date = {\n date: {\n test (x) { return Typeson.toStringTag(x) === 'Date'; },\n replace (dt) {\n const time = dt.getTime();\n if (Number.isNaN(time)) {\n return 'NaN';\n }\n return time;\n },\n revive (time) {\n if (time === 'NaN') {\n return new Date(Number.NaN);\n }\n return new Date(time);\n }\n }\n};\n\nexport default date;\n","import Typeson from 'typeson';\n\nconst regexp = {\n regexp: {\n test (x) { return Typeson.toStringTag(x) === 'RegExp'; },\n replace (rexp) {\n return {\n source: rexp.source,\n flags: (rexp.global ? 'g' : '') +\n (rexp.ignoreCase ? 'i' : '') +\n (rexp.multiline ? 'm' : '') +\n (rexp.sticky ? 'y' : '') +\n (rexp.unicode ? 'u' : '')\n };\n },\n revive ({source, flags}) { return new RegExp(source, flags); }\n }\n};\n\nexport default regexp;\n","import Typeson from 'typeson';\n\nconst map = {\n map: {\n test (x) { return Typeson.toStringTag(x) === 'Map'; },\n replace (mp) { return [...mp.entries()]; },\n revive (entries) { return new Map(entries); }\n }\n};\n\nexport default map;\n","import Typeson from 'typeson';\n\nconst set = {\n set: {\n test (x) { return Typeson.toStringTag(x) === 'Set'; },\n replace (st) {\n return [...st.values()];\n },\n revive (values) { return new Set(values); }\n }\n};\n\nexport default set;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst arraybuffer = {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(b);\n if (index > -1) {\n return {index};\n }\n stateObj.buffers.push(b);\n return encode(b);\n },\n revive (b64, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n if (typeof b64 === 'object') {\n return stateObj.buffers[b64.index];\n }\n const buffer = decode(b64);\n stateObj.buffers.push(buffer);\n return buffer;\n }\n }\n};\n\nexport default arraybuffer;\n\n// See also typed-arrays!\n","/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\n/* istanbul ignore next */\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst typedArrays = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n /* istanbul ignore if */\n if (!TypedArray) {\n return;\n }\n typedArrays[typeName.toLowerCase()] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length: l}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, length: l};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n length: l\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, length: len, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new TypedArray(buffer, byteOffset, len);\n }\n };\n});\n\nexport default typedArrays;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst dataview = {\n dataview: {\n test (x) { return Typeson.toStringTag(x) === 'DataView'; },\n replace ({buffer, byteOffset, byteLength}, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const index = stateObj.buffers.indexOf(buffer);\n if (index > -1) {\n return {index, byteOffset, byteLength};\n }\n stateObj.buffers.push(buffer);\n return {\n encoded: encode(buffer),\n byteOffset,\n byteLength\n };\n },\n revive (b64Obj, stateObj) {\n if (!stateObj.buffers) {\n stateObj.buffers = [];\n }\n const {byteOffset, byteLength, encoded, index} = b64Obj;\n let buffer;\n if ('index' in b64Obj) {\n buffer = stateObj.buffers[index];\n } else {\n buffer = decode(encoded);\n stateObj.buffers.push(buffer);\n }\n return new DataView(buffer, byteOffset, byteLength);\n }\n }\n};\n\nexport default dataview;\n","import Typeson from 'typeson';\n\nconst IntlCollator = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.Collator); },\n replace (c) { return c.resolvedOptions(); },\n revive (options) { return new Intl.Collator(options.locale, options); }\n};\n\nconst IntlDateTimeFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.DateTimeFormat); },\n replace (dtf) { return dtf.resolvedOptions(); },\n revive (options) {\n return new Intl.DateTimeFormat(options.locale, options);\n }\n};\n\nconst IntlNumberFormat = {\n test (x) { return Typeson.hasConstructorOf(x, Intl.NumberFormat); },\n replace (nf) { return nf.resolvedOptions(); },\n revive (options) { return new Intl.NumberFormat(options.locale, options); }\n};\n\nconst intlTypes = {\n IntlCollator,\n IntlDateTimeFormat,\n IntlNumberFormat\n};\n\nexport default intlTypes;\n","/**\n * Not currently in use internally, but provided for parity.\n * @param {ArrayBuffer} buf\n * @returns {Uint8Array}\n */\nfunction arraybuffer2string (buf) {\n return new Uint8Array(buf).reduce(\n (s, byte) => s + String.fromCharCode(byte), ''\n );\n}\n\n/**\n *\n * @param {string} str\n * @returns {ArrayBuffer}\n */\nfunction string2arraybuffer (str) {\n /*\n // UTF-8 approaches\n const utf8 = unescape(encodeURIComponent(str));\n const arr = new Uint8Array(utf8.length);\n for (let i = 0; i < utf8.length; i++) {\n arr[i] = utf8.charCodeAt(i);\n }\n return arr.buffer;\n\n const utf8 = [];\n for (let i = 0; i < str.length; i++) {\n let charcode = str.charCodeAt(i);\n if (charcode < 0x80) utf8.push(charcode);\n else if (charcode < 0x800) {\n utf8.push(0xc0 | (charcode >> 6),\n 0x80 | (charcode & 0x3f));\n } else if (charcode < 0xd800 || charcode >= 0xe000) {\n utf8.push(0xe0 | (charcode >> 12),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n // surrogate pair\n } else {\n i++;\n // UTF-16 encodes 0x10000-0x10FFFF by\n // subtracting 0x10000 and splitting the\n // 20 bits of 0x0-0xFFFFF into two halves\n charcode = 0x10000 + (((charcode & 0x3ff) << 10) |\n (str.charCodeAt(i) & 0x3ff));\n utf8.push(0xf0 | (charcode >> 18),\n 0x80 | ((charcode >> 12) & 0x3f),\n 0x80 | ((charcode >> 6) & 0x3f),\n 0x80 | (charcode & 0x3f));\n }\n }\n return utf8;\n */\n /*\n // Working UTF-16 options (equivalents)\n const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char\n const bufView = new Uint16Array(buf);\n for (let i = 0, strLen = str.length; i < strLen; i++) {\n bufView[i] = str.charCodeAt(i);\n }\n return buf;\n */\n\n const array = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n array[i] = str.charCodeAt(i); // & 0xff;\n }\n return array.buffer;\n}\nexport {arraybuffer2string, string2arraybuffer};\n","/* globals XMLHttpRequest, File, FileReader */\nimport Typeson from 'typeson';\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nconst file = {\n file: {\n test (x) { return Typeson.toStringTag(x) === 'File'; },\n replace (f) { // Sync\n const req = new XMLHttpRequest();\n req.overrideMimeType('text/plain; charset=x-user-defined');\n req.open('GET', URL.createObjectURL(f), false); // Sync\n req.send();\n\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad File access: ' + req.status);\n }\n return {\n type: f.type,\n stringContents: req.responseText,\n name: f.name,\n lastModified: f.lastModified\n };\n },\n revive ({name, type, stringContents, lastModified}) {\n return new File([string2arraybuffer(stringContents)], name, {\n type,\n lastModified\n });\n },\n replaceAsync (f) {\n return new Typeson.Promise(function (resolve, reject) {\n /*\n if (f.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The File is closed'));\n return;\n }\n */\n const reader = new FileReader();\n reader.addEventListener('load', function () {\n resolve({\n type: f.type,\n stringContents: reader.result,\n name: f.name,\n lastModified: f.lastModified\n });\n });\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n reader.addEventListener('error', function () {\n reject(reader.error);\n });\n reader.readAsBinaryString(f);\n });\n }\n }\n};\n\nexport default file;\n","/* globals BigInt */\n\nconst bigint = {\n bigint: {\n test (x) {\n return typeof x === 'bigint';\n },\n replace (n) { return String(n); },\n revive (s) { return BigInt(s); }\n }\n};\n\nexport default bigint;\n","/* globals BigInt */\nimport Typeson from 'typeson';\n\nconst bigintObject = {\n bigintObject: {\n test (x) {\n return typeof x === 'object' && Typeson.hasConstructorOf(x, BigInt);\n },\n replace (n) { return String(n); },\n revive (s) {\n // Filed this to avoid error: https://github.com/eslint/eslint/issues/11810\n // eslint-disable-next-line no-new-object\n return new Object(BigInt(s));\n }\n }\n};\n\nexport default bigintObject;\n","/* globals crypto */\nimport Typeson from 'typeson';\n\nconst cryptokey = {\n cryptokey: {\n test (x) {\n return Typeson.toStringTag(x) === 'CryptoKey' && x.extractable;\n },\n replaceAsync (key) {\n return new Typeson.Promise((resolve, reject) => {\n // eslint-disable-next-line promise/catch-or-return\n crypto.subtle.exportKey('jwk', key).catch(\n /* eslint-disable promise/prefer-await-to-callbacks */\n // istanbul ignore next\n (err) => {\n /* eslint-enable promise/prefer-await-to-callbacks */\n // eslint-disable-next-line max-len\n // istanbul ignore next -- Our format should be valid and our key extractable\n reject(err);\n }\n // eslint-disable-next-line max-len\n // eslint-disable-next-line promise/always-return, promise/prefer-await-to-then\n ).then((jwk) => {\n resolve({\n jwk,\n algorithm: key.algorithm,\n usages: key.usages\n });\n });\n });\n },\n revive ({jwk, algorithm, usages}) {\n return crypto.subtle.importKey('jwk', jwk, algorithm, true, usages);\n }\n }\n};\n\nexport default cryptokey;\n","/* This preset includes types for the Structured Cloning Algorithm. */\n\nimport userObject from '../types/user-object.js';\nimport arrayNonindexKeys from './array-nonindex-keys.js';\nimport undef from '../types/undef.js';\nimport primitiveObjects from '../types/primitive-objects.js';\nimport specialNumbers from './special-numbers.js';\nimport date from '../types/date.js';\nimport regexp from '../types/regexp.js';\nimport map from '../types/map.js';\nimport set from '../types/set.js';\nimport arraybuffer from '../types/arraybuffer.js';\nimport typedArrays from '../types/typed-arrays.js';\nimport dataview from '../types/dataview.js';\nimport intlTypes from '../types/intl-types.js';\n\nimport imagedata from '../types/imagedata.js';\nimport imagebitmap from '../types/imagebitmap.js'; // Async return\nimport file from '../types/file.js';\nimport filelist from '../types/filelist.js';\nimport blob from '../types/blob.js';\nimport bigint from '../types/bigint.js';\nimport bigintObject from '../types/bigint-object.js';\n\nimport cryptokey from '../types/cryptokey.js';\n\nconst expObj = [\n // Todo: Might also register synchronous `ImageBitmap` and\n // `Blob`/`File`/`FileList`?\n // ES5\n userObject, // Processed last (non-builtin)\n\n undef,\n arrayNonindexKeys, primitiveObjects, specialNumbers,\n date, regexp,\n\n // Non-built-ins\n imagedata,\n imagebitmap, // Async return\n file,\n filelist,\n blob\n].concat(\n // ES2015 (ES6)\n /* istanbul ignore next */\n typeof Map === 'function' ? map : [],\n /* istanbul ignore next */\n typeof Set === 'function' ? set : [],\n /* istanbul ignore next */\n typeof ArrayBuffer === 'function' ? arraybuffer : [],\n /* istanbul ignore next */\n typeof Uint8Array === 'function' ? typedArrays : [],\n /* istanbul ignore next */\n typeof DataView === 'function' ? dataview : [],\n /* istanbul ignore next */\n typeof Intl !== 'undefined' ? intlTypes : [],\n /* istanbul ignore next */\n typeof crypto !== 'undefined' ? cryptokey : [],\n /* istanbul ignore next */\n typeof BigInt !== 'undefined' ? [bigint, bigintObject] : []\n);\nexport default expObj;\n","/* globals ImageData */\n// `ImageData` is browser / DOM specific (though `node-canvas` has it\n// available on `Canvas`).\n\nimport Typeson from 'typeson';\n\nconst imagedata = {\n imagedata: {\n test (x) { return Typeson.toStringTag(x) === 'ImageData'; },\n replace (d) {\n return {\n // Ensure `length` gets preserved for revival\n array: [...d.data],\n width: d.width,\n height: d.height\n };\n },\n revive (o) {\n return new ImageData(\n new Uint8ClampedArray(o.array), o.width, o.height\n );\n }\n }\n};\n\nexport default imagedata;\n","/* globals createImageBitmap */\n// `ImageBitmap` is browser / DOM specific. It also can only work\n// same-domain (or CORS)\n\nimport Typeson from 'typeson';\n\nconst imagebitmap = {\n imagebitmap: {\n test (x) {\n return Typeson.toStringTag(x) === 'ImageBitmap' ||\n // In Node, our polyfill sets the dataset on a canvas\n // element as JSDom no longer allows overriding toStringTag\n (x && x.dataset && x.dataset.toStringTag === 'ImageBitmap');\n },\n replace (bm) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n ctx.drawImage(bm, 0, 0);\n // Although `width` and `height` are part of `ImageBitMap`,\n // these will be auto-created for us when reviving with the\n // data URL (and they are not settable even if they weren't)\n // return {\n // width: bm.width, height: bm.height, dataURL: canvas.toDataURL()\n // };\n return canvas.toDataURL();\n },\n revive (o) {\n /*\n var req = new XMLHttpRequest();\n req.open('GET', o, false); // Sync\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad ImageBitmap access: ' + req.status);\n }\n req.send();\n return req.responseText;\n */\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.addEventListener('load', function () {\n ctx.drawImage(img, 0, 0);\n });\n img.src = o;\n // Works in contexts allowing an `ImageBitmap` (We might use\n // `OffscreenCanvas.transferToBitmap` when supported)\n return canvas;\n },\n reviveAsync (o) {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d');\n const img = document.createElement('img');\n // The onload is needed by some browsers per http://stackoverflow.com/a/4776378/271577\n img.addEventListener('load', function () {\n ctx.drawImage(img, 0, 0);\n });\n img.src = o; // o.dataURL;\n return createImageBitmap(canvas); // Returns a promise\n }\n }\n};\n\nexport default imagebitmap;\n","import Typeson from 'typeson';\nimport file from './file.js';\n\nconst filelist = {\n file: file.file,\n filelist: {\n test (x) { return Typeson.toStringTag(x) === 'FileList'; },\n replace (fl) {\n const arr = [];\n for (let i = 0; i < fl.length; i++) {\n arr[i] = fl.item(i);\n }\n return arr;\n },\n revive (o) {\n /**\n * `FileList` polyfill.\n */\n class FileList {\n /**\n * Set private properties and length.\n */\n constructor () {\n // eslint-disable-next-line prefer-rest-params\n this._files = arguments[0];\n this.length = this._files.length;\n }\n /**\n * @param {Integer} index\n * @returns {File}\n */\n item (index) {\n return this._files[index];\n }\n /* eslint-disable class-methods-use-this */\n /**\n * @returns {\"FileList\"}\n */\n get [Symbol.toStringTag] () {\n /* eslint-enable class-methods-use-this */\n return 'FileList';\n }\n }\n return new FileList(o);\n }\n }\n};\n\nexport default filelist;\n","/* globals XMLHttpRequest, Blob, FileReader */\nimport Typeson from 'typeson';\nimport {string2arraybuffer} from '../utils/stringArrayBuffer.js';\n\nconst blob = {\n blob: {\n test (x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace (b) { // Sync\n const req = new XMLHttpRequest();\n req.overrideMimeType('text/plain; charset=x-user-defined');\n req.open('GET', URL.createObjectURL(b), false); // Sync\n req.send();\n\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n if (req.status !== 200 && req.status !== 0) {\n throw new Error('Bad Blob access: ' + req.status);\n }\n return {\n type: b.type,\n stringContents: req.responseText\n };\n },\n revive ({type, stringContents}) {\n return new Blob([string2arraybuffer(stringContents)], {type});\n },\n replaceAsync (b) {\n return new Typeson.Promise((resolve, reject) => {\n /*\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n reject(new Error('The Blob is closed'));\n return;\n }\n */\n const reader = new FileReader();\n reader.addEventListener('load', () => {\n resolve({\n type: b.type,\n stringContents: reader.result\n });\n });\n // Seems not feasible to accurately simulate\n /* istanbul ignore next */\n reader.addEventListener('error', () => {\n reject(reader.error);\n });\n reader.readAsBinaryString(b);\n });\n }\n }\n};\n\nexport default blob;\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2017 Brett Zamir, 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\nvar chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.\n\nvar lookup = new Uint8Array(256);\n\nfor (var i = 0; i < chars.length; i++) {\n lookup[chars.codePointAt(i)] = i;\n}\n/**\n * @param {ArrayBuffer} arraybuffer\n * @param {Integer} byteOffset\n * @param {Integer} lngth\n * @returns {string}\n */\n\n\nvar encode = function encode(arraybuffer, byteOffset, lngth) {\n if (lngth === null || lngth === undefined) {\n lngth = arraybuffer.byteLength; // Needed for Safari\n }\n\n var bytes = new Uint8Array(arraybuffer, byteOffset || 0, // Default needed for Safari\n lngth);\n var len = bytes.length;\n var base64 = '';\n\n for (var _i = 0; _i < len; _i += 3) {\n base64 += chars[bytes[_i] >> 2];\n base64 += chars[(bytes[_i] & 3) << 4 | bytes[_i + 1] >> 4];\n base64 += chars[(bytes[_i + 1] & 15) << 2 | bytes[_i + 2] >> 6];\n base64 += chars[bytes[_i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.slice(0, -1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.slice(0, -2) + '==';\n }\n\n return base64;\n};\n/**\n * @param {string} base64\n * @returns {ArrayBuffer}\n */\n\nvar decode = function decode(base64) {\n var len = base64.length;\n var bufferLength = base64.length * 0.75;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (var _i2 = 0; _i2 < len; _i2 += 4) {\n encoded1 = lookup[base64.codePointAt(_i2)];\n encoded2 = lookup[base64.codePointAt(_i2 + 1)];\n encoded3 = lookup[base64.codePointAt(_i2 + 2)];\n encoded4 = lookup[base64.codePointAt(_i2 + 3)];\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n\n return arraybuffer;\n};\n\nexport { decode, encode };\n","declare var global;\n\n/* eslint-env browser, node */\nimport Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nconst _global = typeof self === 'undefined' ? global : self;\n\nconst exportObj = {};\n[\n 'Int8Array',\n 'Uint8Array',\n 'Uint8ClampedArray',\n 'Int16Array',\n 'Uint16Array',\n 'Int32Array',\n 'Uint32Array',\n 'Float32Array',\n 'Float64Array'\n].forEach(function (typeName) {\n const arrType = typeName;\n const TypedArray = _global[arrType];\n if (TypedArray) {\n exportObj[typeName.toLowerCase()+\"2\"] = {\n test (x) { return Typeson.toStringTag(x) === arrType; },\n replace ({buffer, byteOffset, length}) {\n return {\n buffer,\n byteOffset,\n length\n };\n },\n revive (b64Obj) {\n const {buffer, byteOffset, length} = b64Obj;\n return new TypedArray(buffer, byteOffset, length);\n }\n };\n }\n});\n\nexport default exportObj;\n","import Typeson from 'typeson';\nimport {encode, decode} from 'base64-arraybuffer-es6';\n\nexport default {\n arraybuffer: {\n test (x) { return Typeson.toStringTag(x) === 'ArrayBuffer'; },\n replace (b) {\n return encode(b, 0, b.byteLength);\n },\n revive (b64) {\n const buffer = decode(b64);\n return buffer;\n }\n }\n};\n\n// See also typed-arrays!\n","import Typeson from 'typeson';\nimport StructuredCloning from 'typeson-registry/dist/presets/structured-cloning';\nimport { encode as encodeB64, decode as decodeB64 } from 'base64-arraybuffer-es6';\nimport Dexie from 'dexie';\nimport { readBlobSync, readBlobAsync } from './helpers';\nimport typedArray from './tson-typed-array';\nimport arrayBuffer from './tson-arraybuffer';\n\nexport const TSON = new Typeson().register(StructuredCloning);\n\nconst readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\nlet blobsToAwait: any[] = [];\nlet blobsToAwaitPos = 0;\n\n// Need to patch encapsulateAsync as it does not work as of typeson 5.8.2\n// Also, current version of typespn-registry-1.0.0-alpha.21 does not\n// encapsulate/revive Blobs correctly (fails one of the unit tests in\n// this library (test 'export-format'))\nTSON.register([\n arrayBuffer,\n typedArray, {\n blob2: {\n test(x) { return Typeson.toStringTag(x) === 'Blob'; },\n replace(b) {\n if (b.isClosed) { // On MDN, but not in https://w3c.github.io/FileAPI/#dfn-Blob\n throw new Error('The Blob is closed');\n }\n if (readBlobsSynchronously) {\n const data = readBlobSync(b, 'binary');\n const base64 = encodeB64(data, 0, data.byteLength);\n return {\n type: b.type,\n data: base64\n }\n } else {\n blobsToAwait.push(b); // This will also make TSON.mustFinalize() return true.\n const result = {\n type: b.type,\n data: {start: blobsToAwaitPos, end: blobsToAwaitPos + b.size}\n }\n blobsToAwaitPos += b.size;\n return result;\n }\n },\n finalize(b, ba: ArrayBuffer) {\n b.data = encodeB64(ba, 0, ba.byteLength);\n },\n revive ({type, data}) {\n return new Blob([decodeB64(data)], {type});\n }\n }\n }\n]);\n\nTSON.mustFinalize = ()=>blobsToAwait.length > 0;\n\nTSON.finalize = async (items?: any[]) => {\n const allChunks = await readBlobAsync(new Blob(blobsToAwait), 'binary');\n if (items) {\n for (const item of items) {\n // Manually go through all \"blob\" types in the result\n // and lookup the data slice they point at.\n if (item.$types) {\n let types = item.$types;\n const arrayType = types.$;\n if (arrayType) types = types.$;\n for (let keyPath in types) {\n const typeName = types[keyPath];\n const typeSpec = TSON.types[typeName];\n if (typeSpec && typeSpec.finalize) {\n const b = Dexie.getByKeyPath(item, arrayType ? \"$.\" + keyPath : keyPath);\n typeSpec.finalize(b, allChunks.slice(b.start, b.end));\n }\n }\n }\n }\n }\n // Free up memory\n blobsToAwait = [];\n}\n","\nimport Dexie from 'dexie';\nimport { getSchemaString, extractDbSchema } from './helpers';\nimport { DexieExportedTable, DexieExportJsonStructure } from './json-structure';\nimport { TSON } from './tson';\n\nexport interface ExportOptions {\n noTransaction?: boolean;\n numRowsPerChunk?: number;\n prettyJson?: boolean;\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ExportProgress) => boolean;\n}\n\nexport interface ExportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nconst DEFAULT_ROWS_PER_CHUNK = 2000;\n\nexport async function exportDB(db: Dexie, options?: ExportOptions): Promise {\n options = options || {};\n const slices: (string | Blob)[] = [];\n const tables = db.tables.map(table => ({\n name: table.name,\n schema: getSchemaString(table),\n rowCount: 0\n }));\n const {prettyJson} = options!;\n const emptyExport: DexieExportJsonStructure = {\n formatName: \"dexie\",\n formatVersion: 1,\n data: {\n databaseName: db.name,\n databaseVersion: db.verno,\n tables: tables,\n data: []\n }\n };\n \n const {progressCallback} = options!;\n const progress: ExportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: NaN,\n totalTables: db.tables.length\n };\n\n try {\n if (options!.noTransaction) {\n await exportAll();\n } else {\n await db.transaction('r', db.tables, exportAll);\n }\n } finally {\n TSON.finalize(); // Free up mem if error has occurred\n }\n\n return new Blob(slices,{type: \"text/json\"});\n\n async function exportAll() {\n // Count rows:\n const tablesRowCounts = await Promise.all(db.tables.map(table => table.count()));\n tablesRowCounts.forEach((rowCount, i) => tables[i].rowCount = rowCount);\n progress.totalRows = tablesRowCounts.reduce((p,c)=>p+c);\n\n // Write first JSON slice\n const emptyExportJson = JSON.stringify(emptyExport, undefined, prettyJson ? 2 : undefined);\n const posEndDataArray = emptyExportJson.lastIndexOf(']');\n const firstJsonSlice = emptyExportJson.substring(0, posEndDataArray);\n slices.push(firstJsonSlice);\n\n const filter = options!.filter;\n\n for (const {name: tableName} of tables) {\n const table = db.table(tableName);\n const {primKey} = table.schema;\n const inbound = !!primKey.keyPath;\n const LIMIT = options!.numRowsPerChunk || DEFAULT_ROWS_PER_CHUNK;\n const emptyTableExport: DexieExportedTable = inbound ? {\n tableName: table.name,\n inbound: true,\n rows: []\n } : {\n tableName: table.name,\n inbound: false,\n rows: []\n };\n let emptyTableExportJson = JSON.stringify(emptyTableExport, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) {\n // Increase indentation according to this:\n // {\n // ...\n // data: [\n // ...\n // data: [\n // 123456<---- here\n // ] \n // ]\n // }\n emptyTableExportJson = emptyTableExportJson.split('\\n').join('\\n ');\n }\n const posEndRowsArray = emptyTableExportJson.lastIndexOf(']');\n slices.push(emptyTableExportJson.substring(0, posEndRowsArray));\n let lastKey: any = null;\n let lastNumRows = 0;\n let mayHaveMoreRows = true;\n while (mayHaveMoreRows) {\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const chunkedCollection = lastKey == null ?\n table.limit(LIMIT) :\n table.where(':id').above(lastKey).limit(LIMIT);\n\n const values = await chunkedCollection.toArray();\n\n if (values.length === 0) break;\n\n if (lastKey != null && lastNumRows > 0) {\n // Not initial chunk. Must add a comma:\n slices.push(\",\");\n if (prettyJson) {\n slices.push(\"\\n \");\n }\n }\n\n mayHaveMoreRows = values.length === LIMIT;\n \n if (inbound) {\n const filteredValues = filter ?\n values.filter(value => filter(tableName, value)) :\n values;\n\n const tsonValues = filteredValues.map(value => TSON.encapsulate(value));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonValues));\n }\n\n let json = JSON.stringify(tsonValues, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = filteredValues.length;\n lastKey = values.length > 0 ?\n Dexie.getByKeyPath(values[values.length -1], primKey.keyPath as string) :\n null;\n } else {\n const keys = await chunkedCollection.primaryKeys();\n let keyvals = keys.map((key, i) => [key, values[i]]);\n if (filter) keyvals = keyvals.filter(([key, value]) => filter(tableName, value, key));\n\n const tsonTuples = keyvals.map(tuple => TSON.encapsulate(tuple));\n if (TSON.mustFinalize()) {\n await Dexie.waitFor(TSON.finalize(tsonTuples));\n }\n\n let json = JSON.stringify(tsonTuples, undefined, prettyJson ? 2 : undefined);\n if (prettyJson) json = json.split('\\n').join('\\n ');\n\n // By generating a blob here, we give web platform the opportunity to store the contents\n // on disk and release RAM.\n slices.push(new Blob([json.substring(1, json.length - 1)]));\n lastNumRows = keyvals.length;\n lastKey = keys.length > 0 ?\n keys[keys.length - 1] :\n null;\n }\n progress.completedRows += values.length;\n }\n slices.push(emptyTableExportJson.substr(posEndRowsArray)); // \"]}\"\n progress.completedTables += 1;\n if (progress.completedTables < progress.totalTables) {\n slices.push(\",\");\n }\n }\n slices.push(emptyExportJson.substr(posEndDataArray));\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n }\n}\n","export const VERSION = 1;\n\n/** Same as DexieExportJsonStructure but without the data.data array */\nexport interface DexieExportJsonMeta {\n formatName: 'dexie';\n formatVersion: typeof VERSION;\n data: {\n databaseName: string;\n databaseVersion: number;\n tables: Array<{\n name: string;\n schema: string;\n rowCount: number;\n }>;\n }\n}\n\nexport interface DexieExportJsonStructure extends DexieExportJsonMeta {\n formatName: 'dexie';\n formatVersion: typeof VERSION;\n data: {\n databaseName: string;\n databaseVersion: number;\n tables: Array<{\n name: string;\n schema: string;\n rowCount: number;\n }>;\n data: Array<{\n tableName: string;\n inbound: boolean;\n rows: any[];\n }>;\n }\n}\n\nexport type DexieExportedDatabase = DexieExportJsonStructure[\"data\"];\nexport type DexieExportedTable = DexieExportedDatabase[\"data\"][number];\n","module.exports = {Stream: function(){}};\n\n",";(function (clarinet) {\n \"use strict\";\n\n // non node-js needs to set clarinet debug on root\n var env =(typeof process === 'object' && process.env)\n ? process.env\n : self;\n\n clarinet.parser = function (opt) { return new CParser(opt);};\n clarinet.CParser = CParser;\n clarinet.CStream = CStream;\n clarinet.createStream = createStream;\n clarinet.MAX_BUFFER_LENGTH = 10 * 1024 * 1024;\n clarinet.DEBUG = (env.CDEBUG==='debug');\n clarinet.INFO = (env.CDEBUG==='debug' || env.CDEBUG==='info');\n clarinet.EVENTS =\n [ \"value\"\n , \"string\"\n , \"key\"\n , \"openobject\"\n , \"closeobject\"\n , \"openarray\"\n , \"closearray\"\n , \"error\"\n , \"end\"\n , \"ready\"\n ];\n\n var buffers = {\n textNode: undefined,\n numberNode: \"\"\n }\n , streamWraps = clarinet.EVENTS.filter(function (ev) {\n return ev !== \"error\" && ev !== \"end\";\n })\n , S = 0\n , Stream\n ;\n\n clarinet.STATE =\n { BEGIN : S++\n , VALUE : S++ // general stuff\n , OPEN_OBJECT : S++ // {\n , CLOSE_OBJECT : S++ // }\n , OPEN_ARRAY : S++ // [\n , CLOSE_ARRAY : S++ // ]\n , TEXT_ESCAPE : S++ // \\ stuff\n , STRING : S++ // \"\"\n , BACKSLASH : S++\n , END : S++ // No more stack\n , OPEN_KEY : S++ // , \"a\"\n , CLOSE_KEY : S++ // :\n , TRUE : S++ // r\n , TRUE2 : S++ // u\n , TRUE3 : S++ // e\n , FALSE : S++ // a\n , FALSE2 : S++ // l\n , FALSE3 : S++ // s\n , FALSE4 : S++ // e\n , NULL : S++ // u\n , NULL2 : S++ // l\n , NULL3 : S++ // l\n , NUMBER_DECIMAL_POINT : S++ // .\n , NUMBER_DIGIT : S++ // [0-9]\n };\n\n for (var s_ in clarinet.STATE) clarinet.STATE[clarinet.STATE[s_]] = s_;\n\n // switcharoo\n S = clarinet.STATE;\n\n const Char = {\n tab : 0x09, // \\t\n lineFeed : 0x0A, // \\n\n carriageReturn : 0x0D, // \\r\n space : 0x20, // \" \"\n\n doubleQuote : 0x22, // \"\n plus : 0x2B, // +\n comma : 0x2C, // ,\n minus : 0x2D, // -\n period : 0x2E, // .\n\n _0 : 0x30, // 0\n _9 : 0x39, // 9\n\n colon : 0x3A, // :\n\n E : 0x45, // E\n\n openBracket : 0x5B, // [\n backslash : 0x5C, // \\\n closeBracket : 0x5D, // ]\n\n a : 0x61, // a\n b : 0x62, // b\n e : 0x65, // e \n f : 0x66, // f\n l : 0x6C, // l\n n : 0x6E, // n\n r : 0x72, // r\n s : 0x73, // s\n t : 0x74, // t\n u : 0x75, // u\n\n openBrace : 0x7B, // {\n closeBrace : 0x7D, // }\n }\n\n if (!Object.create) {\n Object.create = function (o) {\n function f () { this[\"__proto__\"] = o; }\n f.prototype = o;\n return new f;\n };\n }\n\n if (!Object.getPrototypeOf) {\n Object.getPrototypeOf = function (o) {\n return o[\"__proto__\"];\n };\n }\n\n if (!Object.keys) {\n Object.keys = function (o) {\n var a = [];\n for (var i in o) if (o.hasOwnProperty(i)) a.push(i);\n return a;\n };\n }\n\n function checkBufferLength (parser) {\n var maxAllowed = Math.max(clarinet.MAX_BUFFER_LENGTH, 10)\n , maxActual = 0\n ;\n for (var buffer in buffers) {\n var len = parser[buffer] === undefined ? 0 : parser[buffer].length;\n if (len > maxAllowed) {\n switch (buffer) {\n case \"text\":\n closeText(parser);\n break;\n\n default:\n error(parser, \"Max buffer length exceeded: \"+ buffer);\n }\n }\n maxActual = Math.max(maxActual, len);\n }\n parser.bufferCheckPosition = (clarinet.MAX_BUFFER_LENGTH - maxActual)\n + parser.position;\n }\n\n function clearBuffers (parser) {\n for (var buffer in buffers) {\n parser[buffer] = buffers[buffer];\n }\n }\n\n var stringTokenPattern = /[\\\\\"\\n]/g;\n\n function CParser (opt) {\n if (!(this instanceof CParser)) return new CParser (opt);\n\n var parser = this;\n clearBuffers(parser);\n parser.bufferCheckPosition = clarinet.MAX_BUFFER_LENGTH;\n parser.q = parser.c = parser.p = \"\";\n parser.opt = opt || {};\n parser.closed = parser.closedRoot = parser.sawRoot = false;\n parser.tag = parser.error = null;\n parser.state = S.BEGIN;\n parser.stack = new Array();\n // mostly just for error reporting\n parser.position = parser.column = 0;\n parser.line = 1;\n parser.slashed = false;\n parser.unicodeI = 0;\n parser.unicodeS = null;\n parser.depth = 0;\n emit(parser, \"onready\");\n }\n\n CParser.prototype =\n { end : function () { end(this); }\n , write : write\n , resume : function () { this.error = null; return this; }\n , close : function () { return this.write(null); }\n };\n\n try { Stream = require(\"stream\").Stream; }\n catch (ex) { Stream = function () {}; }\n\n function createStream (opt) { return new CStream(opt); }\n\n function CStream (opt) {\n if (!(this instanceof CStream)) return new CStream(opt);\n\n this._parser = new CParser(opt);\n this.writable = true;\n this.readable = true;\n\n //var Buffer = this.Buffer || function Buffer () {}; // if we don't have Buffers, fake it so we can do `var instanceof Buffer` and not throw an error\n this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary\n this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read\n this.temp_buffs = { \"2\": new Buffer(2), \"3\": new Buffer(3), \"4\": new Buffer(4) }; // for rebuilding chars split before boundary is reached\n this.string = '';\n\n var me = this;\n Stream.apply(me);\n\n this._parser.onend = function () { me.emit(\"end\"); };\n this._parser.onerror = function (er) {\n me.emit(\"error\", er);\n me._parser.error = null;\n };\n\n streamWraps.forEach(function (ev) {\n Object.defineProperty(me, \"on\" + ev,\n { get : function () { return me._parser[\"on\" + ev]; }\n , set : function (h) {\n if (!h) {\n me.removeAllListeners(ev);\n me._parser[\"on\"+ev] = h;\n return h;\n }\n me.on(ev, h);\n }\n , enumerable : true\n , configurable : false\n });\n });\n }\n\n CStream.prototype = Object.create(Stream.prototype,\n { constructor: { value: CStream } });\n\n CStream.prototype.write = function (data) {\n data = new Buffer(data);\n for (var i = 0; i < data.length; i++) {\n var n = data[i];\n\n // check for carry over of a multi byte char split between data chunks\n // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration\n if (this.bytes_remaining > 0) {\n for (var j = 0; j < this.bytes_remaining; j++) {\n this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = data[j];\n }\n this.string = this.temp_buffs[this.bytes_in_sequence].toString();\n this.bytes_in_sequence = this.bytes_remaining = 0;\n\n // move iterator forward by number of byte read during sequencing\n i = i + j - 1;\n\n // pass data to parser and move forward to parse rest of data\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n\n // if no remainder bytes carried over, parse multi byte (>=128) chars one at a time\n if (this.bytes_remaining === 0 && n >= 128) {\n if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;\n if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;\n if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;\n if ((this.bytes_in_sequence + i) > data.length) { // if bytes needed to complete char fall outside data length, we have a boundary split\n\n for (var k = 0; k <= (data.length - 1 - i); k++) {\n this.temp_buffs[this.bytes_in_sequence][k] = data[i + k]; // fill temp data of correct size with bytes available in this chunk\n }\n this.bytes_remaining = (i + this.bytes_in_sequence) - data.length;\n\n // immediately return as we need another chunk to sequence the character\n return true;\n } else {\n this.string = data.slice(i, (i + this.bytes_in_sequence)).toString();\n i = i + this.bytes_in_sequence - 1;\n\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n continue;\n }\n }\n\n // is there a range of characters that are immediately parsable?\n for (var p = i; p < data.length; p++) {\n if (data[p] >= 128) break;\n }\n this.string = data.slice(i, p).toString();\n this._parser.write(this.string);\n this.emit(\"data\", this.string);\n i = p - 1;\n\n // handle any remaining characters using multibyte logic\n continue;\n }\n };\n\n CStream.prototype.end = function (chunk) {\n if (chunk && chunk.length) this._parser.write(chunk.toString());\n this._parser.end();\n return true;\n };\n\n CStream.prototype.on = function (ev, handler) {\n var me = this;\n if (!me._parser[\"on\"+ev] && streamWraps.indexOf(ev) !== -1) {\n me._parser[\"on\"+ev] = function () {\n var args = arguments.length === 1 ? [arguments[0]]\n : Array.apply(null, arguments);\n args.splice(0, 0, ev);\n me.emit.apply(me, args);\n };\n }\n return Stream.prototype.on.call(me, ev, handler);\n };\n\n CStream.prototype.destroy = function () {\n clearBuffers(this._parser);\n this.emit(\"close\");\n };\n\n function emit(parser, event, data) {\n if(clarinet.INFO) console.log('-- emit', event, data);\n if (parser[event]) parser[event](data);\n }\n\n function emitNode(parser, event, data) {\n closeValue(parser);\n emit(parser, event, data);\n }\n\n function closeValue(parser, event) {\n parser.textNode = textopts(parser.opt, parser.textNode);\n if (parser.textNode !== undefined) {\n emit(parser, (event ? event : \"onvalue\"), parser.textNode);\n }\n parser.textNode = undefined;\n }\n\n function closeNumber(parser) {\n if (parser.numberNode)\n emit(parser, \"onvalue\", parseFloat(parser.numberNode));\n parser.numberNode = \"\";\n }\n\n function textopts (opt, text) {\n if (text === undefined) {\n return text;\n }\n if (opt.trim) text = text.trim();\n if (opt.normalize) text = text.replace(/\\s+/g, \" \");\n return text;\n }\n\n function error (parser, er) {\n closeValue(parser);\n er += \"\\nLine: \"+parser.line+\n \"\\nColumn: \"+parser.column+\n \"\\nChar: \"+parser.c;\n er = new Error(er);\n parser.error = er;\n emit(parser, \"onerror\", er);\n return parser;\n }\n\n function end(parser) {\n if (parser.state !== S.VALUE || parser.depth !== 0)\n error(parser, \"Unexpected end\");\n\n closeValue(parser);\n parser.c = \"\";\n parser.closed = true;\n emit(parser, \"onend\");\n CParser.call(parser, parser.opt);\n return parser;\n }\n\n function isWhitespace(c) {\n return c === Char.carriageReturn || c === Char.lineFeed || c === Char.space || c === Char.tab;\n }\n\n function write (chunk) {\n var parser = this;\n if (this.error) throw this.error;\n if (parser.closed) return error(parser,\n \"Cannot write after close. Assign an onready handler.\");\n if (chunk === null) return end(parser);\n var i = 0, c = chunk.charCodeAt(0), p = parser.p;\n if (clarinet.DEBUG) console.log('write -> [' + chunk + ']');\n while (c) {\n p = c;\n parser.c = c = chunk.charCodeAt(i++);\n // if chunk doesnt have next, like streaming char by char\n // this way we need to check if previous is really previous\n // if not we need to reset to what the parser says is the previous\n // from buffer\n if(p !== c ) parser.p = p;\n else p = parser.p;\n\n if(!c) break;\n\n if (clarinet.DEBUG) console.log(i,c,clarinet.STATE[parser.state]);\n parser.position ++;\n if (c === Char.lineFeed) {\n parser.line ++;\n parser.column = 0;\n } else parser.column ++;\n switch (parser.state) {\n\n case S.BEGIN:\n if (c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if (c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if (!isWhitespace(c))\n error(parser, \"Non-whitespace before {[.\");\n continue;\n\n case S.OPEN_KEY:\n case S.OPEN_OBJECT:\n if (isWhitespace(c)) continue;\n if(parser.state === S.OPEN_KEY) parser.stack.push(S.CLOSE_KEY);\n else {\n if(c === Char.closeBrace) {\n emit(parser, 'onopenobject');\n this.depth++;\n emit(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else parser.stack.push(S.CLOSE_OBJECT);\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else error(parser, \"Malformed object key should start with \\\"\");\n continue;\n\n case S.CLOSE_KEY:\n case S.CLOSE_OBJECT:\n if (isWhitespace(c)) continue;\n var event = (parser.state === S.CLOSE_KEY) ? 'key' : 'object';\n if(c === Char.colon) {\n if(parser.state === S.CLOSE_OBJECT) {\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser, 'onopenobject');\n this.depth++;\n } else closeValue(parser, 'onkey');\n parser.state = S.VALUE;\n } else if (c === Char.closeBrace) {\n emitNode(parser, 'oncloseobject');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if(c === Char.comma) {\n if(parser.state === S.CLOSE_OBJECT)\n parser.stack.push(S.CLOSE_OBJECT);\n closeValue(parser);\n parser.state = S.OPEN_KEY;\n } else error(parser, 'Bad object');\n continue;\n\n case S.OPEN_ARRAY: // after an array there always a value\n case S.VALUE:\n if (isWhitespace(c)) continue;\n if(parser.state===S.OPEN_ARRAY) {\n emit(parser, 'onopenarray');\n this.depth++;\n parser.state = S.VALUE;\n if(c === Char.closeBracket) {\n emit(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n continue;\n } else {\n parser.stack.push(S.CLOSE_ARRAY);\n }\n }\n if(c === Char.doubleQuote) parser.state = S.STRING;\n else if(c === Char.openBrace) parser.state = S.OPEN_OBJECT;\n else if(c === Char.openBracket) parser.state = S.OPEN_ARRAY;\n else if(c === Char.t) parser.state = S.TRUE;\n else if(c === Char.f) parser.state = S.FALSE;\n else if(c === Char.n) parser.state = S.NULL;\n else if(c === Char.minus) { // keep and continue\n parser.numberNode += \"-\";\n } else if(Char._0 <= c && c <= Char._9) {\n parser.numberNode += String.fromCharCode(c);\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, \"Bad value\");\n continue;\n\n case S.CLOSE_ARRAY:\n if(c === Char.comma) {\n parser.stack.push(S.CLOSE_ARRAY);\n closeValue(parser, 'onvalue');\n parser.state = S.VALUE;\n } else if (c === Char.closeBracket) {\n emitNode(parser, 'onclosearray');\n this.depth--;\n parser.state = parser.stack.pop() || S.VALUE;\n } else if (isWhitespace(c))\n continue;\n else error(parser, 'Bad array');\n continue;\n\n case S.STRING:\n if (parser.textNode === undefined) {\n parser.textNode = \"\";\n }\n\n // thanks thejh, this is an about 50% performance improvement.\n var starti = i-1\n , slashed = parser.slashed\n , unicodeI = parser.unicodeI\n ;\n STRING_BIGLOOP: while (true) {\n if (clarinet.DEBUG)\n console.log(i,c,clarinet.STATE[parser.state]\n ,slashed);\n // zero means \"no unicode active\". 1-4 mean \"parse some more\". end after 4.\n while (unicodeI > 0) {\n parser.unicodeS += String.fromCharCode(c);\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (unicodeI === 4) {\n // TODO this might be slow? well, probably not used too often anyway\n parser.textNode += String.fromCharCode(parseInt(parser.unicodeS, 16));\n unicodeI = 0;\n starti = i-1;\n } else {\n unicodeI++;\n }\n // we can just break here: no stuff we skipped that still has to be sliced out or so\n if (!c) break STRING_BIGLOOP;\n }\n if (c === Char.doubleQuote && !slashed) {\n parser.state = parser.stack.pop() || S.VALUE;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n if (c === Char.backslash && !slashed) {\n slashed = true;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n c = chunk.charCodeAt(i++);\n parser.position++;\n if (!c) break;\n }\n if (slashed) {\n slashed = false;\n if (c === Char.n) { parser.textNode += '\\n'; }\n else if (c === Char.r) { parser.textNode += '\\r'; }\n else if (c === Char.t) { parser.textNode += '\\t'; }\n else if (c === Char.f) { parser.textNode += '\\f'; }\n else if (c === Char.b) { parser.textNode += '\\b'; }\n else if (c === Char.u) {\n // \\uxxxx. meh!\n unicodeI = 1;\n parser.unicodeS = '';\n } else {\n parser.textNode += String.fromCharCode(c);\n }\n c = chunk.charCodeAt(i++);\n parser.position++;\n starti = i-1;\n if (!c) break;\n else continue;\n }\n\n stringTokenPattern.lastIndex = i;\n var reResult = stringTokenPattern.exec(chunk);\n if (reResult === null) {\n i = chunk.length+1;\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n i = reResult.index+1;\n c = chunk.charCodeAt(reResult.index);\n if (!c) {\n parser.textNode += chunk.substring(starti, i-1);\n parser.position += i - 1 - starti;\n break;\n }\n }\n parser.slashed = slashed;\n parser.unicodeI = unicodeI;\n continue;\n\n case S.TRUE:\n if (c === Char.r) parser.state = S.TRUE2;\n else error(parser, 'Invalid true started with t'+ c);\n continue;\n\n case S.TRUE2:\n if (c === Char.u) parser.state = S.TRUE3;\n else error(parser, 'Invalid true started with tr'+ c);\n continue;\n\n case S.TRUE3:\n if(c === Char.e) {\n emit(parser, \"onvalue\", true);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid true started with tru'+ c);\n continue;\n\n case S.FALSE:\n if (c === Char.a) parser.state = S.FALSE2;\n else error(parser, 'Invalid false started with f'+ c);\n continue;\n\n case S.FALSE2:\n if (c === Char.l) parser.state = S.FALSE3;\n else error(parser, 'Invalid false started with fa'+ c);\n continue;\n\n case S.FALSE3:\n if (c === Char.s) parser.state = S.FALSE4;\n else error(parser, 'Invalid false started with fal'+ c);\n continue;\n\n case S.FALSE4:\n if (c === Char.e) {\n emit(parser, \"onvalue\", false);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid false started with fals'+ c);\n continue;\n\n case S.NULL:\n if (c === Char.u) parser.state = S.NULL2;\n else error(parser, 'Invalid null started with n'+ c);\n continue;\n\n case S.NULL2:\n if (c === Char.l) parser.state = S.NULL3;\n else error(parser, 'Invalid null started with nu'+ c);\n continue;\n\n case S.NULL3:\n if(c === Char.l) {\n emit(parser, \"onvalue\", null);\n parser.state = parser.stack.pop() || S.VALUE;\n } else error(parser, 'Invalid null started with nul'+ c);\n continue;\n\n case S.NUMBER_DECIMAL_POINT:\n if(c === Char.period) {\n parser.numberNode += \".\";\n parser.state = S.NUMBER_DIGIT;\n } else error(parser, 'Leading zero not followed by .');\n continue;\n\n case S.NUMBER_DIGIT:\n if(Char._0 <= c && c <= Char._9) parser.numberNode += String.fromCharCode(c);\n else if (c === Char.period) {\n if(parser.numberNode.indexOf('.')!==-1)\n error(parser, 'Invalid number has two dots');\n parser.numberNode += \".\";\n } else if (c === Char.e || c === Char.E) {\n if(parser.numberNode.indexOf('e')!==-1 ||\n parser.numberNode.indexOf('E')!==-1 )\n error(parser, 'Invalid number has two exponential');\n parser.numberNode += \"e\";\n } else if (c === Char.plus || c === Char.minus) {\n if(!(p === Char.e || p === Char.E))\n error(parser, 'Invalid symbol in number');\n parser.numberNode += String.fromCharCode(c);\n } else {\n closeNumber(parser);\n i--; // go back one\n parser.state = parser.stack.pop() || S.VALUE;\n }\n continue;\n\n default:\n error(parser, \"Unknown state: \" + parser.state);\n }\n }\n if (parser.position >= parser.bufferCheckPosition)\n checkBufferLength(parser);\n return parser;\n }\n\n})(typeof exports === \"undefined\" ? clarinet = {} : exports);\n","import clarinet from 'clarinet';\nimport { readBlobAsync, readBlobSync } from './helpers';\n\nexport interface JsonStream {\n pullAsync(numBytes: number): Promise>;\n pullSync(numBytes: number): Partial;\n done(): boolean;\n eof(): boolean;\n result: Partial;\n}\n\nexport function JsonStream(blob: Blob): JsonStream {\n let pos = 0;\n const parser = JsonParser(true);\n\n const rv = {\n async pullAsync(numBytes: number): Promise> {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = await readBlobAsync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n pullSync(numBytes: number): Partial {\n const slize = blob.slice(pos, pos + numBytes);\n pos += numBytes;\n const jsonPart = readBlobSync(slize, 'text');\n const result = parser.write(jsonPart);\n rv.result = result || {};\n return result;\n },\n done() {\n return parser.done();\n },\n eof() {\n return pos >= blob.size;\n },\n result: {}\n }\n\n return rv;\n}\n\n\nexport function JsonParser (allowPartial: boolean) {\n const parser = (clarinet as any).parser();\n let level = 0;\n let result: any;\n const stack: any[][] = [];\n let obj: any;\n let key: string | null;\n let done = false;\n let array = false;\n\n parser.onopenobject = newKey => {\n const newObj = {};\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n key = newKey;\n array = false;\n ++level;\n }\n parser.onkey = newKey => key = newKey;\n parser.onvalue = value => array ? obj.push(value) : obj[key!] = value;\n parser.oncloseobject = ()=>{\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n parser.onopenarray = () => {\n const newObj = [];\n (newObj as any).incomplete = true;\n if (!result) result = newObj;\n if (obj) {\n stack.push([key,obj,array])\n if (allowPartial) {\n if (array) {\n obj.push(newObj);\n } else {\n obj[key!] = newObj;\n }\n }\n }\n obj = newObj;\n array = true;\n key = null;\n ++level;\n }\n parser.onclosearray = () => {\n delete obj.incomplete;\n key = null;\n if (--level === 0) {\n done = true;\n } else {\n const completedObj = obj;\n [key, obj, array] = stack.pop()!;\n if (!allowPartial) {\n if (array) {\n obj.push(completedObj);\n } else {\n obj[key!] = completedObj;\n }\n }\n }\n }\n\n return {\n write(jsonPart: string) {\n parser.write(jsonPart);\n return result;\n },\n done() {\n return done;\n }\n }\n}\n","import Dexie from 'dexie';\nimport { extractDbSchema } from './helpers';\nimport { DexieExportJsonMeta, DexieExportJsonStructure, VERSION } from './json-structure';\nimport { TSON } from './tson';\nimport { JsonStream } from './json-stream';\n\nexport interface StaticImportOptions {\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nexport interface ImportOptions extends StaticImportOptions {\n acceptMissingTables?: boolean;\n acceptVersionDiff?: boolean;\n acceptNameDiff?: boolean;\n acceptChangedPrimaryKey?: boolean;\n overwriteValues?: boolean;\n clearTablesBeforeImport?: boolean;\n noTransaction?: boolean;\n chunkSizeBytes?: number; // Default: DEFAULT_KILOBYTES_PER_CHUNK ( 1MB )\n filter?: (table: string, value: any, key?: any) => boolean;\n progressCallback?: (progress: ImportProgress) => boolean;\n}\n\nconst DEFAULT_KILOBYTES_PER_CHUNK = 1024;\n\nexport interface ImportProgress {\n totalTables: number;\n completedTables: number;\n totalRows: number | undefined;\n completedRows: number;\n done: boolean;\n}\n\nexport async function importDB(exportedData: Blob | JsonStream, options?: StaticImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const stream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n const dbExport = stream.result.data!;\n const db = new Dexie(dbExport.databaseName);\n db.version(dbExport.databaseVersion).stores(extractDbSchema(dbExport));\n await importInto(db, stream, options);\n return db;\n}\n\nexport async function peakImportFile(exportedData: Blob): Promise {\n const stream = JsonStream(exportedData);\n while (!stream.eof()) {\n await stream.pullAsync(5 * 1024); // 5 k is normally enough for the headers. If not, it will just do another go.\n if (stream.result.data && stream.result.data!.data) {\n // @ts-ignore - TS won't allow us to delete a required property - but we are going to cast it.\n delete stream.result.data.data; // Don't return half-baked data array.\n break;\n }\n }\n return stream.result as DexieExportJsonMeta;\n}\n\nexport async function importInto(db: Dexie, exportedData: Blob | JsonStream, options?: ImportOptions): Promise {\n options = options || {}; // All booleans defaults to false.\n const CHUNK_SIZE = options!.chunkSizeBytes || (DEFAULT_KILOBYTES_PER_CHUNK * 1024);\n const jsonStream = await loadUntilWeGotEnoughData(exportedData, CHUNK_SIZE);\n let dbExportFile = jsonStream.result;\n const readBlobsSynchronously = 'FileReaderSync' in self; // true in workers only.\n\n const dbExport = dbExportFile.data!;\n\n if (!options!.acceptNameDiff && db.name !== dbExport.databaseName)\n throw new Error(`Name differs. Current database name is ${db.name} but export is ${dbExport.databaseName}`);\n if (!options!.acceptVersionDiff && db.verno !== dbExport.databaseVersion) {\n // Possible feature: Call upgraders in some isolated way if this happens... ?\n throw new Error(`Database version differs. Current database is in version ${db.verno} but export is ${dbExport.databaseVersion}`);\n }\n \n const { progressCallback } = options;\n const progress: ImportProgress = {\n done: false,\n completedRows: 0,\n completedTables: 0,\n totalRows: dbExport.tables.reduce((p, c) => p + c.rowCount, 0),\n totalTables: dbExport.tables.length\n };\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n\n if (options!.clearTablesBeforeImport) {\n for (const table of db.tables) {\n await table.clear();\n }\n }\n\n if (options.noTransaction) {\n await importAll();\n } else {\n await db.transaction('rw', db.tables, importAll);\n } \n\n async function importAll () {\n do {\n for (const tableExport of dbExport.data) {\n if (!tableExport.rows) break; // Need to pull more!\n if (!(tableExport.rows as any).incomplete && tableExport.rows.length === 0)\n continue;\n\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n const tableName = tableExport.tableName;\n const table = db.table(tableName);\n const tableSchemaStr = dbExport.tables.filter(t => t.name === tableName)[0].schema;\n if (!table) {\n if (!options!.acceptMissingTables)\n throw new Error(`Exported table ${tableExport.tableName} is missing in installed database`);\n else\n continue;\n }\n if (!options!.acceptChangedPrimaryKey &&\n tableSchemaStr.split(',')[0] != table.schema.primKey.src) {\n throw new Error(`Primary key differs for table ${tableExport.tableName}. `);\n }\n\n const sourceRows = tableExport.rows\n \n // Our rows may be partial, so we need to ensure each one is completed before using it\n const rows: any[] = [];\n for(let i = 0; i < sourceRows.length; i++) {\n const obj = sourceRows[i];\n if (!obj.incomplete) {\n rows.push(TSON.revive(obj));\n } else {\n break;\n }\n }\n\n const filter = options!.filter;\n const filteredRows = filter ?\n tableExport.inbound ?\n rows.filter(value => filter(tableName, value)) :\n rows.filter(([key, value]) => filter(tableName, value, key)) :\n rows;\n const [keys, values] = tableExport.inbound ?\n [undefined, filteredRows] :\n [filteredRows.map(row=>row[0]), rows.map(row=>row[1])];\n\n if (options!.overwriteValues)\n await table.bulkPut(values, keys);\n else\n await table.bulkAdd(values, keys);\n \n progress.completedRows += rows.length;\n if (!(rows as any).incomplete) {\n progress.completedTables += 1;\n }\n sourceRows.splice(0, rows.length); // Free up RAM, keep existing array instance.\n }\n\n // Avoid unnescessary loops in \"for (const tableExport of dbExport.data)\" \n while (dbExport.data.length > 0 && dbExport.data[0].rows && !(dbExport.data[0].rows as any).incomplete) {\n // We've already imported all rows from the first table. Delete its occurrence\n dbExport.data.splice(0, 1); \n }\n if (!jsonStream.done() && !jsonStream.eof()) {\n // Pull some more (keeping transaction alive)\n if (readBlobsSynchronously) {\n // If we can pull from blob synchronically, we don't have to\n // keep transaction alive using Dexie.waitFor().\n // This will only be possible in workers.\n jsonStream.pullSync(CHUNK_SIZE);\n } else {\n await Dexie.waitFor(jsonStream.pullAsync(CHUNK_SIZE));\n }\n } else break;\n } while (true)\n }\n progress.done = true;\n if (progressCallback) {\n // Keep ongoing transaction private\n Dexie.ignoreTransaction(()=>progressCallback(progress));\n }\n}\n\nasync function loadUntilWeGotEnoughData(exportedData: Blob | JsonStream, CHUNK_SIZE: number): Promise> {\n const stream = ('slice' in exportedData ?\n JsonStream(exportedData) :\n exportedData);\n\n while (!stream.eof()) {\n await stream.pullAsync(CHUNK_SIZE);\n\n if (stream.result.data && stream.result.data!.data)\n break;\n }\n const dbExportFile = stream.result;\n if (!dbExportFile || dbExportFile.formatName != \"dexie\")\n throw new Error(`Given file is not a dexie export`);\n if (dbExportFile.formatVersion! > VERSION) {\n throw new Error(`Format version ${dbExportFile.formatVersion} not supported`);\n }\n if (!dbExportFile.data!) {\n throw new Error(`No data in export file`);\n }\n if (!dbExportFile.data!.databaseName) {\n throw new Error(`Missing databaseName in export file`);\n }\n if (!dbExportFile.data!.databaseVersion) {\n throw new Error(`Missing databaseVersion in export file`);\n }\n if (!dbExportFile.data!.tables) {\n throw new Error(`Missing tables in export file`);\n }\n return stream; \n}\n","import Dexie from 'dexie';\nimport { ExportOptions, exportDB } from './export';\nimport { importDB, peakImportFile, ImportOptions, importInto, StaticImportOptions } from './import';\nimport { DexieExportJsonMeta } from './json-structure';\n\nexport { exportDB, ExportOptions};\nexport { importDB, importInto, peakImportFile, ImportOptions, DexieExportJsonMeta};\n\n//\n// Extend Dexie interface (typescript-wise)\n//\ndeclare module 'dexie' {\n // Extend methods on db\n interface Dexie {\n export(options?: ExportOptions): Promise;\n import(blob: Blob, options?: ImportOptions): Promise;\n }\n interface DexieConstructor {\n import(blob: Blob, options?: StaticImportOptions): Promise;\n }\n}\n\n//\n// Extend Dexie interface (runtime wise)\n//\n\nDexie.prototype.export = function (this: Dexie, options?: ExportOptions) {\n return exportDB(this, options);\n};\nDexie.prototype.import = function (this: Dexie, blob: Blob, options?: ImportOptions) {\n return importInto(this, blob, options);\n};\nDexie.import = (blob: Blob, options?: StaticImportOptions) => importDB(blob, options);\n\nexport default ()=>{\n throw new Error(\"This addon extends Dexie.prototype globally and does not have be included in Dexie constructor's addons options.\")\n};\n"],"names":["this","_typeof","obj","Symbol","iterator","constructor","prototype","_classCallCheck","instance","Constructor","TypeError","_defineProperties","target","props","i","length","descriptor","enumerable","configurable","writable","Object","defineProperty","key","_defineProperty","value","ownKeys","object","enumerableOnly","keys","getOwnPropertySymbols","symbols","filter","sym","getOwnPropertyDescriptor","push","apply","_objectSpread2","arguments","source","forEach","getOwnPropertyDescriptors","defineProperties","_slicedToArray","arr","_arrayWithHoles","Array","isArray","_iterableToArrayLimit","_arr","_n","_d","_e","undefined","_s","_i","next","done","err","_unsupportedIterableToArray","_nonIterableRest","_toConsumableArray","_arrayWithoutHoles","_arrayLikeToArray","_iterableToArray","iter","from","_nonIterableSpread","o","minLen","n","toString","call","slice","name","test","len","arr2","TypesonPromise","f","p","Promise","__typeson__type__","toStringTag","then","onFulfilled","onRejected","_this","typesonResolve","typesonReject","res","reject","resolve","v","meth","promArr","map","prom","toStr","hasOwn$1","hasOwnProperty","getProto","getPrototypeOf","fnToString","isThenable","catchCheck","isObject","val","hasConstructorOf","a","b","proto","Ctor","isPlainObject","escapeKeyPathComponent","keyPathComponent","replace","unescapeKeyPathComponent","getByKeyPath","keyPath","period","indexOf","innerObj","setAtKeyPath","_await","direct","hasOwn","internalStateObjPropsToIgnore","_async","args","e","nestedPathsFirst","keypath","as","match","bs","Typeson","options","plainObjectReplacers","nonplainObjectReplacers","revivers","types","_createClass","protoProps","staticProps","stringify","replacer","space","opts","stringification","encapsulated","encapsulate","JSON","stringifySync","throwOnBadSyncType","sync","stringifyAsync","parse","text","reviver","revive","parseSync","parseAsync","specialTypeNames","stateObj","returnTypeNames","rootTypeName","iterateNone","checkPromises","ret","promisesData","all","pd","promResults","promResult","_exit","newPromisesData","_promisesData$splice2","splice","_prData","cyclic","parentObj","detectedType","encaps","_encapsulate","isTypesonPromise","_invoke","body","result","encaps2","_result","that","refObjs","refKeys","promisesDataRoot","encapsulateObserver","finish","typeNames","values","getJSONType","Set","$types","$","_adaptBuiltinStateObjectProperties","ownKeysObj","cb","assign","vals","prop","tmp","resolvingTypesonPromise","observerData","$typeof","runObserver","type","awaitingTypesonPromise","includes","Number","isNaN","NEGATIVE_INFINITY","POSITIVE_INFINITY","replaced","iterateIn","iterateUnsetNumeric","refIndex","cyclicKeypath","clone","isPlainObj","isArr","ArrayBuffer","addLength","_loop","kp","Boolean","endIterateIn","end","endIterateOwn","vl","_loop2","endIterateUnsetNumeric","plainObject","replacers","existing","concat","replaceAsync","replacing","typeDetected","encapsulateSync","encapsulateAsync","keyPathResolutions","ignore$Types","executeReviver","Error","reviveAsync","revivalPromises","checkUndefined","retrn","Undefined","possibleTypesonPromise","revivePlainObjects","plainObjectTypes","entries","_ref3","_ref4","plain","sort","reduce","reducer","_ref7","newVal","_revive","_clone","k","set","_keyPathResolutions$","_target","_clone2","_ret","typ","r","_ref8","reviveSync","register","typeSpecSets","R","typeSpec","typSpec","typeId","JSON_TYPES","spec","testPlainObjects","existingReplacer","Class","x","create","_spec2","replacerObj","bind","start","fallback","reviverObj","isUserObject","userObject","s","arrayNonindexKeys","some","String","parseInt","sparseUndefined","undef","primitiveObjects","StringObject","BooleanObject","NumberObject","specialNumbers","nan","NaN","infinity","negativeInfinity","date","dt","time","getTime","Date","regexp","rexp","flags","global","ignoreCase","multiline","sticky","unicode","RegExp","mp","Map","st","chars","lookup","Uint8Array","charCodeAt","encode","arraybuffer","byteOffset","lngth","byteLength","bytes","base64","decode","encoded1","encoded2","encoded3","encoded4","bufferLength","_i2","buffers","index","b64","buffer","_global","self","typedArrays","typeName","arrType","TypedArray","toLowerCase","l","encoded","b64Obj","dataview","DataView","intlTypes","IntlCollator","Intl","Collator","c","resolvedOptions","locale","IntlDateTimeFormat","DateTimeFormat","dtf","IntlNumberFormat","NumberFormat","nf","string2arraybuffer","str","array","file","req","XMLHttpRequest","overrideMimeType","open","URL","createObjectURL","send","status","stringContents","responseText","lastModified","File","reader","FileReader","addEventListener","error","readAsBinaryString","bigint","BigInt","bigintObject","cryptokey","extractable","crypto","subtle","exportKey","jwk","algorithm","usages","importKey","imagedata","d","data","width","height","ImageData","Uint8ClampedArray","imagebitmap","dataset","bm","canvas","document","createElement","getContext","drawImage","toDataURL","ctx","img","src","createImageBitm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AC,CAAC;AACxD,qBAAA;AACD,oBAAA,IAAI,CAAC,YAAY,CAAC,IAAK,CAAC,eAAe,EAAE;AACvC,wBAAA,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC3D,qBAAA;AACD,oBAAA,IAAI,CAAC,YAAY,CAAC,IAAK,CAAC,MAAM,EAAE;AAC9B,wBAAA,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AAClD,qBAAA;AACD,oBAAA,OAAA,CAAA,CAAA,aAAO,MAAM,CAAC,CAAA;;;;AACf;;AClMD;AACA;AACA;AAEA,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,OAAuB,EAAA;AACrE,IAAA,OAAO,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AACjC,CAAC,CAAC;AACF,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,UAAuB,IAAU,EAAE,OAAuB,EAAA;IACjF,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;AACzC,CAAC,CAAC;AACF,KAAK,CAAC,MAAM,GAAG,UAAC,IAAU,EAAE,OAA6B,EAAA,EAAK,OAAA,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA,EAAA,CAAC;AAEtF,wBAAe,CAAA,YAAA;AACb,IAAA,MAAM,IAAI,KAAK,CAAC,kHAAkH,CAAC,CAAA;AACrI,CAAC;;;;"} \ No newline at end of file diff --git a/dist/README.md b/dist/README.md deleted file mode 100644 index e9e21f03f..000000000 --- a/dist/README.md +++ /dev/null @@ -1,46 +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 -``` - -## 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..07086499d --- /dev/null +++ b/dist/dexie.d.ts @@ -0,0 +1,1145 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 4.0.1-beta.1, Wed Oct 18 2023 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + // Generated by dts-bundle-generator v5.9.0 + +export interface IndexSpec { + name: string; + keyPath: string | Array | undefined; + unique: boolean | undefined; + multi: boolean | undefined; + auto: boolean | undefined; + compound: boolean | undefined; + src: string; +} +export interface TableSchema { + name: string; + primKey: IndexSpec; + indexes: IndexSpec[]; + mappedClass: Function; + idxByName: { + [name: string]: IndexSpec; + }; + readHook?: (x: any) => any; +} +export type IndexableTypePart = string | number | Date | ArrayBuffer | ArrayBufferView | DataView | Array>; +export type IndexableTypeArray = Array; +export type IndexableTypeArrayReadonly = ReadonlyArray; +export type IndexableType = IndexableTypePart | IndexableTypeArrayReadonly; +export interface DexieEvent { + subscribers: Function[]; + fire(...args: any[]): any; + subscribe(fn: (...args: any[]) => any): void; + unsubscribe(fn: (...args: any[]) => any): void; +} +export interface DexieEventSet { + (eventName: string): DexieEvent; // To be able to unsubscribe. + addEventType(eventName: string, chainFunction?: (f1: Function, f2: Function) => Function, defaultFunction?: Function): DexieEvent; + addEventType(events: { + [eventName: string]: ("asap" | [ + (f1: Function, f2: Function) => Function, + Function + ]); + }): DexieEvent; +} +export 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; +} +export interface Transaction { + db: Dexie; + active: boolean; + mode: IDBTransactionMode; + //tables: { [type: string]: Table }; Deprecated since 2.0. Obsolete from v3.0. + storeNames: Array; + explicit?: boolean; + parent?: Transaction; + on: TransactionEvents; + abort(): void; + table(tableName: string): Table; + table(tableName: string): Table; + table(tableName: string): Table; +} +export interface CreatingHookContext { + onsuccess?: (primKey: Key) => void; + onerror?: (err: any) => void; +} +export interface UpdatingHookContext { + onsuccess?: (updatedObj: T) => void; + onerror?: (err: any) => void; +} +export interface DeletingHookContext { + onsuccess?: () => void; + onerror?: (err: any) => void; +} +export interface TableHooks extends DexieEventSet { + (eventName: "creating", subscriber: (this: CreatingHookContext, primKey: TKey, obj: T, transaction: Transaction) => void | undefined | TKey): void; + (eventName: "reading", subscriber: (obj: T) => T | any): void; + (eventName: "updating", subscriber: (this: UpdatingHookContext, modifications: Object, primKey: TKey, obj: T, transaction: Transaction) => any): void; + (eventName: "deleting", subscriber: (this: DeletingHookContext, primKey: TKey, obj: T, transaction: Transaction) => any): void; + creating: DexieEvent; + reading: DexieEvent; + updating: DexieEvent; + deleting: DexieEvent; +} +export type ThenShortcut = (value: T) => TResult | PromiseLike; +export interface WhereClause { + above(key: any): Collection; + aboveOrEqual(key: any): Collection; + anyOf(keys: ReadonlyArray): Collection; + anyOf(...keys: Array): Collection; + anyOfIgnoreCase(keys: string[]): Collection; + anyOfIgnoreCase(...keys: string[]): Collection; + below(key: any): Collection; + belowOrEqual(key: any): Collection; + between(lower: any, upper: any, includeLower?: boolean, includeUpper?: boolean): Collection; + equals(key: IndexableType): Collection; + equalsIgnoreCase(key: string): Collection; + inAnyRange(ranges: ReadonlyArray<{ + 0: any; + 1: any; + }>, options?: { + includeLowers?: boolean; + includeUppers?: boolean; + }): 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: ReadonlyArray): Collection; + notEqual(key: IndexableType): Collection; +} +export interface PromiseExtendedConstructor extends PromiseConstructor { + readonly prototype: PromiseExtended; + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): PromiseExtended; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike, + T7 | PromiseLike, + T8 | PromiseLike, + T9 | PromiseLike, + T10 | PromiseLike + ]): PromiseExtended<[ + 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 + ]): PromiseExtended<[ + 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 + ]): PromiseExtended<[ + T1, + T2, + T3, + T4, + T5, + T6, + T7, + T8 + ]>; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike, + T7 | PromiseLike + ]): PromiseExtended<[ + T1, + T2, + T3, + T4, + T5, + T6, + T7 + ]>; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike + ]): PromiseExtended<[ + T1, + T2, + T3, + T4, + T5, + T6 + ]>; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike + ]): PromiseExtended<[ + T1, + T2, + T3, + T4, + T5 + ]>; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike + ]): PromiseExtended<[ + T1, + T2, + T3, + T4 + ]>; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike + ]): PromiseExtended<[ + T1, + T2, + T3 + ]>; + all(values: [ + T1 | PromiseLike, + T2 | PromiseLike + ]): PromiseExtended<[ + T1, + T2 + ]>; + all(values: (T | PromiseLike)[]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike, + T7 | PromiseLike, + T8 | PromiseLike, + T9 | PromiseLike, + T10 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike, + T7 | PromiseLike, + T8 | PromiseLike, + T9 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike, + T7 | PromiseLike, + T8 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike, + T7 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike, + T6 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike, + T5 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike, + T4 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike, + T3 | PromiseLike + ]): PromiseExtended; + race(values: [ + T1 | PromiseLike, + T2 | PromiseLike + ]): PromiseExtended; + race(values: (T | PromiseLike)[]): PromiseExtended; + reject(reason: any): PromiseExtended; + reject(reason: any): PromiseExtended; + resolve(value: T | PromiseLike): PromiseExtended; + resolve(): PromiseExtended; +} +/** The interface of Dexie.Promise, which basically extends standard Promise with methods: + * + * finally() - also subject for standardization + * timeout() - set a completion timeout + * catch(ErrorClass, handler) - java style error catching + * catch(errorName, handler) - cross-domain safe type error catching (checking error.name instead of instanceof) + * + */ +export interface PromiseExtended extends Promise { + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseExtended; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseExtended; + catch(ErrorConstructor: Function, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseExtended; + catch(errorName: string, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): PromiseExtended; + finally(onFinally?: () => U | PromiseLike): PromiseExtended; + timeout(ms: number, msg?: string): PromiseExtended; +} +export type KeyPaths = { + [P in keyof T]: P extends string ? T[P] extends Array ? K extends object // only drill into the array element if it's an object + ? P | `${P}.${number}` | `${P}.${number}.${KeyPaths}` : P | `${P}.${number}` : T[P] extends (...args: any[]) => any // Method + ? never : T[P] extends object ? P | `${P}.${KeyPaths}` : P : never; +}[keyof T]; +export type KeyPathValue = PATH extends `${infer R}.${infer S}` ? R extends keyof T ? KeyPathValue : T extends any[] ? PATH extends `${number}.${infer S}` ? KeyPathValue : void : void : PATH extends `${number}` ? T extends any[] ? T[number] : void : PATH extends keyof T ? T[PATH] : void; +export type UpdateSpec = { + [KP in KeyPaths]?: KeyPathValue; +}; +export interface Collection { + db: Dexie; + and(filter: (x: T) => boolean): Collection; + clone(props?: Object): Collection; + count(): PromiseExtended; + count(thenShortcut: ThenShortcut): PromiseExtended; + distinct(): Collection; + each(callback: (obj: T, cursor: { + key: IndexableType; + primaryKey: TKey; + }) => any): PromiseExtended; + eachKey(callback: (key: IndexableType, cursor: { + key: IndexableType; + primaryKey: TKey; + }) => any): PromiseExtended; + eachPrimaryKey(callback: (key: TKey, cursor: { + key: IndexableType; + primaryKey: TKey; + }) => any): PromiseExtended; + eachUniqueKey(callback: (key: IndexableType, cursor: { + key: IndexableType; + primaryKey: TKey; + }) => any): PromiseExtended; + filter(filter: (x: T) => x is S): Collection; + filter(filter: (x: T) => boolean): Collection; + first(): PromiseExtended; + first(thenShortcut: ThenShortcut): PromiseExtended; + keys(): PromiseExtended; + keys(thenShortcut: ThenShortcut): PromiseExtended; + primaryKeys(): PromiseExtended; + primaryKeys(thenShortcut: ThenShortcut): PromiseExtended; + last(): PromiseExtended; + last(thenShortcut: ThenShortcut): PromiseExtended; + limit(n: number): Collection; + offset(n: number): Collection; + or(indexOrPrimayKey: string): WhereClause; + raw(): Collection; + reverse(): Collection; + sortBy(keyPath: string): PromiseExtended; + sortBy(keyPath: string, thenShortcut: ThenShortcut): PromiseExtended; + toArray(): PromiseExtended>; + toArray(thenShortcut: ThenShortcut): PromiseExtended; + uniqueKeys(): PromiseExtended; + uniqueKeys(thenShortcut: ThenShortcut): PromiseExtended; + until(filter: (value: T) => boolean, includeStopEntry?: boolean): Collection; + // Mutating methods + delete(): PromiseExtended; + modify(changeCallback: (obj: T, ctx: { + value: T; + }) => void | boolean): PromiseExtended; + modify(changes: UpdateSpec): PromiseExtended; +} +export type IntervalTree = IntervalTreeNode | EmptyRange; +export interface IntervalTreeNode { + from: IndexableType; // lower bound + to: IndexableType; // upper bound + l: IntervalTreeNode | null; // left + r: IntervalTreeNode | null; // right + d: number; // depth +} +export interface EmptyRange { + d: 0; +} +export interface DexieOnReadyEvent { + subscribe(fn: (vipDb: Dexie) => any, bSticky: boolean): void; + unsubscribe(fn: (vipDb: Dexie) => any): void; + fire(vipDb: Dexie): any; +} +export interface DexieVersionChangeEvent { + subscribe(fn: (event: IDBVersionChangeEvent) => any): void; + unsubscribe(fn: (event: IDBVersionChangeEvent) => any): void; + fire(event: IDBVersionChangeEvent): any; +} +export interface DexiePopulateEvent { + subscribe(fn: (trans: Transaction) => any): void; + unsubscribe(fn: (trans: Transaction) => any): void; + fire(trans: Transaction): any; +} +export interface DexieCloseEvent { + subscribe(fn: (event: Event) => any): void; + unsubscribe(fn: (event: Event) => any): void; + fire(event: Event): any; +} +export interface DbEvents extends DexieEventSet { + (eventName: "ready", subscriber: (vipDb: Dexie) => any, bSticky?: boolean): void; + (eventName: "populate", subscriber: (trans: Transaction) => any): void; + (eventName: "blocked", subscriber: (event: IDBVersionChangeEvent) => any): void; + (eventName: "versionchange", subscriber: (event: IDBVersionChangeEvent) => any): void; + (eventName: "close", subscriber: (event: Event) => any): void; + ready: DexieOnReadyEvent; + populate: DexiePopulateEvent; + blocked: DexieEvent; + versionchange: DexieVersionChangeEvent; + close: DexieCloseEvent; +} +/** Set of mutated parts of the database + */ +export type ObservabilitySet = { + /** Database part having been mutated. + * + * This structure is produced in observability-middleware.ts + * and consumed in live-query.ts. + * + * Format of 'part': + * + * `idb://${dbName}/${tableName}/${indexName}` + * + * * dbName is the database name + * * tableName is the table name + * * indexName is any of: + * 1. An empty string - represents the primary keys of the affected objs + * 2. ":dels" - represents primary keys of deleted objects in the table + * 3. The keyPath of an index, such as "name", "age" or "address.city" - + * represents indexes that, if used in a query, might affect the + * result of that query. + * + * IntervalTree + * * See definition of IntervalTree type in rangeset.d.ts + * * See rangesOverlap() in rangeset.ts that can be used to compare two + * IntervalTrees and detect collissions. + * * See RangeSet class that can be used to create an IntervalTree and add + * ranges to it. + */ + [part: string]: IntervalTree; +}; +export interface DexieOnStorageMutatedEvent { + subscribe(fn: (parts: ObservabilitySet) => any): void; + unsubscribe(fn: (parts: ObservabilitySet) => any): void; + fire(parts: ObservabilitySet): any; +} +export interface GlobalDexieEvents extends DexieEventSet { + (eventName: "storagemutated", subscriber: (parts: ObservabilitySet) => any): void; + storagemutated: DexieOnStorageMutatedEvent; +} +export const enum DBCoreRangeType { + Equal = 1, + Range = 2, + Any = 3, + Never = 4 +} +export interface DBCoreKeyRange { + readonly type: DBCoreRangeType; + readonly lower: any; + readonly lowerOpen?: boolean; + readonly upper: any; + readonly upperOpen?: boolean; +} +export interface DBCoreTransaction { + abort(): void; +} +export interface DbCoreTransactionOptions { + durability: ChromeTransactionDurability; +} +export type DBCoreMutateRequest = DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest | DBCoreDeleteRangeRequest; +export interface DBCoreMutateResponse { + numFailures: number; + failures: { + [operationNumber: number]: Error; + }; + lastResult: any; + results?: any[]; // Present on AddRequest and PutRequest. +} +export interface DBCoreAddRequest { + type: "add"; + trans: DBCoreTransaction; + values: readonly any[]; + keys?: any[]; + mutatedParts?: ObservabilitySet; + /** @deprecated Will always get results since 3.1.0-alpha.5 */ + wantResults?: boolean; +} +export interface DBCorePutRequest { + type: "put"; + trans: DBCoreTransaction; + values: readonly any[]; + keys?: any[]; + mutatedParts?: ObservabilitySet; + criteria?: { + index: string | null; + range: DBCoreKeyRange; + }; + changeSpec?: { + [keyPath: string]: any; + }; // Common changeSpec for each key + updates?: { + keys: any[]; + changeSpecs: { + [keyPath: string]: any; + }[]; // changeSpec per key. + }; + /** @deprecated Will always get results since 3.1.0-alpha.5 */ + wantResults?: boolean; +} +export interface DBCoreDeleteRequest { + type: "delete"; + trans: DBCoreTransaction; + keys: any[]; + mutatedParts?: ObservabilitySet; + criteria?: { + index: string | null; + range: DBCoreKeyRange; + }; +} +export interface DBCoreDeleteRangeRequest { + type: "deleteRange"; + trans: DBCoreTransaction; + range: DBCoreKeyRange; + mutatedParts?: ObservabilitySet; +} +export interface DBCoreGetManyRequest { + trans: DBCoreTransaction; + keys: any[]; + cache?: "immutable" | "clone"; + obsSet?: ObservabilitySet; +} +export interface DBCoreGetRequest { + trans: DBCoreTransaction; + key: any; + obsSet?: ObservabilitySet; +} +export interface DBCoreQuery { + index: DBCoreIndex; //keyPath: null | string | string[]; // null represents primary key. string a property, string[] several properties. + range: DBCoreKeyRange; +} +export interface DBCoreQueryRequest { + trans: DBCoreTransaction; + values?: boolean; + limit?: number; + query: DBCoreQuery; + obsSet?: ObservabilitySet; +} +export interface DBCoreQueryResponse { + result: any[]; +} +export interface DBCoreOpenCursorRequest { + trans: DBCoreTransaction; + values?: boolean; + unique?: boolean; + reverse?: boolean; + query: DBCoreQuery; + obsSet?: ObservabilitySet; +} +export interface DBCoreCountRequest { + trans: DBCoreTransaction; + query: DBCoreQuery; + obsSet?: ObservabilitySet; +} +export interface DBCoreCursor { + readonly trans: DBCoreTransaction; + readonly key: any; + readonly primaryKey: any; + readonly value?: any; + readonly done?: boolean; + continue(key?: any): void; + continuePrimaryKey(key: any, primaryKey: any): void; + advance(count: number): void; + start(onNext: () => void): Promise; + stop(value?: any | Promise): void; + next(): Promise; + fail(error: Error): void; +} +export interface DBCoreSchema { + name: string; + tables: DBCoreTableSchema[]; +} +export interface DBCoreTableSchema { + readonly name: string; + readonly primaryKey: DBCoreIndex; + readonly indexes: DBCoreIndex[]; + readonly getIndexByKeyPath: (keyPath: null | string | string[]) => DBCoreIndex | undefined; +} +export interface DBCoreIndex { + /** Name of the index, or null for primary key */ + readonly name: string | null; + /** True if this index represents the primary key */ + readonly isPrimaryKey?: boolean; + /** True if this index represents the primary key and is not inbound (https://dexie.org/docs/inbound) */ + readonly outbound?: boolean; + /** True if and only if keyPath is an array (https://dexie.org/docs/Compound-Index) */ + readonly compound?: boolean; + /** keyPath, null for primary key, string for single-property indexes, Array for compound indexes */ + readonly keyPath: null | string | string[]; + /** Auto-generated primary key (does not apply to secondary indexes) */ + readonly autoIncrement?: boolean; + /** Whether index is unique. Also true if index is primary key. */ + readonly unique?: boolean; + /** Whether index is multiEntry. */ + readonly multiEntry?: boolean; + /** Extract (using keyPath) a key from given value (object). Null for outbound primary keys */ + readonly extractKey: ((value: any) => any) | null; + /** If this index is a virtual index, lowLevelIndex represents the actual IndexedDB index behind it */ + readonly lowLevelIndex?: DBCoreIndex; +} +export interface DBCore { + stack: "dbcore"; + // Transaction and Object Store + transaction(stores: string[], mode: "readonly" | "readwrite", options?: DbCoreTransactionOptions): DBCoreTransaction; + // Utility methods + readonly MIN_KEY: any; + readonly MAX_KEY: any; + readonly schema: DBCoreSchema; + table(name: string): DBCoreTable; +} +export interface DBCoreTable { + readonly name: string; + readonly schema: DBCoreTableSchema; + mutate(req: DBCoreMutateRequest): Promise; + get(req: DBCoreGetRequest): Promise; + getMany(req: DBCoreGetManyRequest): Promise; + query(req: DBCoreQueryRequest): Promise; + openCursor(req: DBCoreOpenCursorRequest): Promise; + count(req: DBCoreCountRequest): Promise; +} +export interface Table { + db: Dexie; + name: string; + schema: TableSchema; + hook: TableHooks; + core: DBCoreTable; + get(key: TKey): PromiseExtended; + get(key: TKey, thenShortcut: ThenShortcut): PromiseExtended; + get(equalityCriterias: { + [key: string]: any; + }): PromiseExtended; + get(equalityCriterias: { + [key: string]: any; + }, thenShortcut: ThenShortcut): PromiseExtended; + where(index: string | string[]): WhereClause; + where(equalityCriterias: { + [key: string]: any; + }): Collection; + filter(fn: (obj: T) => boolean): Collection; + count(): PromiseExtended; + count(thenShortcut: ThenShortcut): PromiseExtended; + offset(n: number): Collection; + limit(n: number): Collection; + each(callback: (obj: T, cursor: { + key: any; + primaryKey: TKey; + }) => any): PromiseExtended; + toArray(): PromiseExtended>; + toArray(thenShortcut: ThenShortcut): PromiseExtended; + toCollection(): Collection; + orderBy(index: string | string[]): Collection; + reverse(): Collection; + mapToClass(constructor: Function): Function; + add(item: TInsertType, key?: TKey): PromiseExtended; + update(key: TKey | T, changes: UpdateSpec | ((obj: T, ctx: { + value: any; + primKey: IndexableType; + }) => void | boolean)): PromiseExtended; + put(item: TInsertType, key?: TKey): PromiseExtended; + delete(key: TKey): PromiseExtended; + clear(): PromiseExtended; + bulkGet(keys: TKey[]): PromiseExtended<(T | undefined)[]>; + bulkAdd(items: readonly TInsertType[], keys: IndexableTypeArrayReadonly, options: { + allKeys: B; + }): PromiseExtended; + bulkAdd(items: readonly TInsertType[], options: { + allKeys: B; + }): PromiseExtended; + bulkAdd(items: readonly TInsertType[], keys?: IndexableTypeArrayReadonly, options?: { + allKeys: boolean; + }): PromiseExtended; + bulkPut(items: readonly TInsertType[], keys: IndexableTypeArrayReadonly, options: { + allKeys: B; + }): PromiseExtended; + bulkPut(items: readonly TInsertType[], options: { + allKeys: B; + }): PromiseExtended; + bulkPut(items: readonly TInsertType[], keys?: IndexableTypeArrayReadonly, options?: { + allKeys: boolean; + }): PromiseExtended; + bulkUpdate(keysAndChanges: ReadonlyArray<{ + key: TKey; + changes: UpdateSpec; + }>): PromiseExtended; + bulkDelete(keys: TKey[]): PromiseExtended; +} +export interface Version { + stores(schema: { + [tableName: string]: string | null; + }): Version; + upgrade(fn: (trans: Transaction) => PromiseLike | void): Version; +} +export type TransactionMode = "readonly" | "readwrite" | "r" | "r!" | "r?" | "rw" | "rw!" | "rw?"; +export type DbSchema = { + [tableName: string]: TableSchema; +}; +export interface Middleware { + stack: TStack["stack"]; + create: (down: TStack) => Partial; + level?: number; + name?: string; +} +export interface DexieStacks { + dbcore: DBCore; +} +export type TableProp = { + [K in keyof DX]: DX[K] extends { + schema: any; + get: any; + put: any; + add: any; + where: any; + } ? K : never; +}[keyof DX] & string; +export type TXWithTables = Dexie extends DX ? Transaction // If not subclassed, just expect a Transaction without table props + : Transaction & { + [P in TableProp]: DX[P]; +}; +export interface Dexie { + readonly name: string; + readonly tables: Table[]; + readonly verno: number; + readonly vip: Dexie; + readonly _allTables: { + [name: string]: Table; + }; + readonly core: DBCore; + _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: DbSchema, parentTransaction?: Transaction | null) => Transaction; + readonly _novip: Dexie; + _dbSchema: DbSchema; + version(versionNumber: number): Version; + on: DbEvents; + open(): PromiseExtended; + table(tableName: string): Table; + transaction(mode: TransactionMode, tables: readonly (string | Table)[], scope: (trans: TXWithTables) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string | Table, scope: (trans: TXWithTables) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string | Table, table2: string | Table, scope: (trans: TXWithTables) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string | Table, table2: string | Table, table3: string | Table, scope: (trans: TXWithTables) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string | Table, table2: string | Table, table3: string | Table, table4: string | Table, scope: (trans: TXWithTables) => PromiseLike | U): PromiseExtended; + transaction(mode: TransactionMode, table: string | Table, table2: string | Table, table3: string | Table, table5: string | Table, scope: (trans: TXWithTables) => PromiseLike | U): PromiseExtended; + close(closeOptions?: { + disableAutoOpen: boolean; + }): void; + delete(): PromiseExtended; + isOpen(): boolean; + hasBeenClosed(): boolean; + hasFailed(): boolean; + dynamicallyOpened(): boolean; + backendDB(): IDBDatabase; + use(middleware: Middleware): this; + // Add more supported stacks here... : use(middleware: Middleware): this; + unuse({ stack, create }: Middleware<{ + stack: keyof DexieStacks; + }>): this; + unuse({ stack, name }: { + stack: keyof DexieStacks; + name: string; + }): this; + // 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: { + prototype: Table; + }; + WhereClause: { + prototype: WhereClause; + }; + Version: { + prototype: Version; + }; + Transaction: { + prototype: Transaction; + }; + Collection: { + prototype: Collection; + }; +} +/** DexieError + * + * Common base class for all errors originating from Dexie.js except TypeError, + * SyntaxError and RangeError. + * + * https://dexie.org/docs/DexieErrors/DexieError + * + */ +export interface DexieError extends Error { + name: string; + message: string; + stack: string; + inner: any; + toString(): string; +} +/** + * List of the names of auto-generated error classes that extends DexieError + * and shares the interface of DexieError. + * + * Each error should be documented at https://dexie.org/docs/DexieErrors/Dexie. + * + * The generic type DexieExceptionClasses is a map of full error name to + * error constructor. The DexieExceptionClasses is mixed in into Dexie, + * so that it is always possible to throw or catch certain errors via + * Dexie.ErrorName. Example: + * + * try { + * throw new Dexie.InvalidTableError("Invalid table foo", innerError?); + * } catch (err) { + * if (err instanceof Dexie.InvalidTableError) { + * // Could also have check for err.name === "InvalidTableError", or + * // err.name === Dexie.errnames.InvalidTableError. + * console.log("Seems to be an invalid table here..."); + * } else { + * throw err; + * } + * } + */ +export type DexieErrors = { + // https://dexie.org/docs/DexieErrors/Dexie.OpenFailedError + OpenFailed: "OpenFailedError"; + // https://dexie.org/docs/DexieErrors/Dexie.VersionChangeError + VersionChange: "VersionChangeError"; + // https://dexie.org/docs/DexieErrors/Dexie.SchemaError + Schema: "SchemaError"; + // https://dexie.org/docs/DexieErrors/Dexie.UpgradeError + Upgrade: "UpgradeError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidTableError + InvalidTable: "InvalidTableError"; + // https://dexie.org/docs/DexieErrors/Dexie.MissingAPIError + MissingAPI: "MissingAPIError"; + // https://dexie.org/docs/DexieErrors/Dexie.NoSuchDatabaseError + NoSuchDatabase: "NoSuchDatabaseError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidArgumentError + InvalidArgument: "InvalidArgumentError"; + // https://dexie.org/docs/DexieErrors/Dexie.SubTransactionError + SubTransaction: "SubTransactionError"; + // https://dexie.org/docs/DexieErrors/Dexie.UnsupportedError + Unsupported: "UnsupportedError"; + // https://dexie.org/docs/DexieErrors/Dexie.InternalError + Internal: "InternalError"; + // https://dexie.org/docs/DexieErrors/Dexie.DatabaseClosedError + DatabaseClosed: "DatabaseClosedError"; + // https://dexie.org/docs/DexieErrors/Dexie.PrematureCommitError + PrematureCommit: "PrematureCommitError"; + // https://dexie.org/docs/DexieErrors/Dexie.ForeignAwaitError + ForeignAwait: "ForeignAwaitError"; + // https://dexie.org/docs/DexieErrors/Dexie.UnknownError + Unknown: "UnknownError"; + // https://dexie.org/docs/DexieErrors/Dexie.ConstraintError + Constraint: "ConstraintError"; + // https://dexie.org/docs/DexieErrors/Dexie.DataError + Data: "DataError"; + // https://dexie.org/docs/DexieErrors/Dexie.TransactionInactiveError + TransactionInactive: "TransactionInactiveError"; + // https://dexie.org/docs/DexieErrors/Dexie.ReadOnlyError + ReadOnly: "ReadOnlyError"; + // https://dexie.org/docs/DexieErrors/Dexie.VersionError + Version: "VersionError"; + // https://dexie.org/docs/DexieErrors/Dexie.NotFoundError + NotFound: "NotFoundError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidStateError + InvalidState: "InvalidStateError"; + // https://dexie.org/docs/DexieErrors/Dexie.InvalidAccessError + InvalidAccess: "InvalidAccessError"; + // https://dexie.org/docs/DexieErrors/Dexie.AbortError + Abort: "AbortError"; + // https://dexie.org/docs/DexieErrors/Dexie.TimeoutError + Timeout: "TimeoutError"; + // https://dexie.org/docs/DexieErrors/Dexie.QuotaExceededError + QuotaExceeded: "QuotaExceededError"; + // https://dexie.org/docs/DexieErrors/Dexie.DataCloneError + DataClone: "DataCloneError"; +}; +/** ModifyError + * + * https://dexie.org/docs/DexieErrors/Dexie.ModifyError + */ +export interface ModifyError extends DexieError { + failures: Array; + failedKeys: IndexableTypeArrayReadonly; + successCount: number; +} +/** BulkError + * + * https://dexie.org/docs/DexieErrors/Dexie.BulkError + */ +export interface BulkError extends DexieError { + failures: Error[]; + failuresByPos: { + [operationNumber: number]: Error; + }; +} +export interface DexieErrorConstructor { + new (msg?: string, inner?: Object): DexieError; + new (inner: Object): DexieError; + prototype: DexieError; +} +export interface ModifyErrorConstructor { + new (msg?: string, failures?: any[], successCount?: number, failedKeys?: IndexableTypeArrayReadonly): ModifyError; + prototype: ModifyError; +} +export interface BulkErrorConstructor { + new (msg?: string, failures?: { + [operationNumber: number]: Error; + }): BulkError; + prototype: BulkError; +} +export type ExceptionSet = { + [P in DexieErrors[keyof DexieErrors]]: DexieErrorConstructor; +}; +export type DexieExceptionClasses = ExceptionSet & { + DexieError: DexieErrorConstructor; + ModifyError: ModifyErrorConstructor; + BulkError: BulkErrorConstructor; +}; +export interface DexieDOMDependencies { + indexedDB: IDBFactory; + IDBKeyRange: typeof IDBKeyRange; +} +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} +export interface Subscribable { + subscribe(observer: Partial>): Unsubscribable; +} +export interface Unsubscribable { + unsubscribe(): void; +} +export interface Observable { + subscribe(observerOrNext?: Observer | ((value: T) => void)): Subscription; + subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription; + getValue?(): T; + hasValue?(): boolean; + [Symbol.observable]: () => Subscribable; +} +export interface Subscription { + unsubscribe(): void; + readonly closed: boolean; +} +export interface Observer { + start?: (subscription: Subscription) => void; + next?: (value: T) => void; + error?: (error: any) => void; + complete?: () => void; +} +export type GlobalQueryCache = { + // TODO: Change to parts: {[part: string]: TblQueryCache} + // och unsignaledParts: ObservabilitySet; + [part: string]: TblQueryCache; // part is `idb://${dbName}/${tableName}` +}; +export interface TblQueryCache { + queries: { + query: { + [indexName: string]: CacheEntry[]; + }; + count: { + [indexName: string]: CacheEntry[]; + }; + }; + objs: Map; + optimisticOps: DBCoreMutateRequest[]; + unsignaledParts: ObservabilitySet; + signalTimer?: number; +} +export interface CacheEntryCommon { + subscribers: Set<() => void>; + obsSet: ObservabilitySet; + //txObsSet: ObservabilitySet; + promise: Promise; + dirty: boolean; +} +export type CacheEntry = CacheEntryCommon & ({ + type: "query"; + req: DBCoreQueryRequest; + res?: readonly any[]; +} | { + type: "count"; + req: DBCoreCountRequest; + res?: number; +}); +export type ChromeTransactionDurability = "default" | "strict" | "relaxed"; +export interface DexieOptions { + addons?: Array<(db: Dexie) => void>; + autoOpen?: boolean; + indexedDB?: { + open: Function; + }; + IDBKeyRange?: { + bound: Function; + lowerBound: Function; + upperBound: Function; + }; + allowEmptyDB?: boolean; + modifyChunkSize?: number; + chromeTransactionDurability?: ChromeTransactionDurability; + cache?: "immutable" | "cloned" | "disabled"; +} +export interface DexieConstructor extends DexieExceptionClasses { + new (databaseName: string, options?: DexieOptions): Dexie; + prototype: Dexie; + addons: Array<(db: Dexie) => void>; + version: number; + semVer: string; + currentTransaction: Transaction; + waitFor(promise: PromiseLike | T, timeoutMilliseconds?: number): Promise; + getDatabaseNames(): Promise; + getDatabaseNames(thenShortcut: ThenShortcut): Promise; + vip(scopeFunction: () => U): U; + ignoreTransaction(fn: () => U): U; + liveQuery(fn: () => T | Promise): Observable; + extendObservabilitySet(target: ObservabilitySet, newSet: ObservabilitySet): ObservabilitySet; + override(origFunc: F, overridedFactory: (fn: any) => any): F; // ? + getByKeyPath(obj: Object, keyPath: string | string[]): any; + setByKeyPath(obj: Object, keyPath: string | string[], value: any): void; + delByKeyPath(obj: Object, keyPath: string | string[]): void; + shallowClone(obj: T): T; + deepClone(obj: T): T; + asap(fn: Function): void; //? + maxKey: Array> | string; + minKey: number; + exists(dbName: string): Promise; + delete(dbName: string): Promise; + dependencies: DexieDOMDependencies; + default: Dexie; // Work-around for different build tools handling default imports differently. + cache: GlobalQueryCache; + debug: false | true | "dexie"; + Promise: PromiseExtendedConstructor; + //TableSchema: {}; // Deprecate! + //IndexSpec: {new():IndexSpec}; //? Deprecate + Events: (ctx?: any) => DexieEventSet; + on: GlobalDexieEvents; + errnames: DexieErrors; +} +export class Entity { + protected constructor(); + protected readonly db: TDexieSubClass; + table(): TableProp; +} +export type IsStrictlyAny = (T extends never ? true : false) extends false ? false : true; +/** Extract the union of literal method names in T + */ +export type MethodProps = { + [P in keyof T]: IsStrictlyAny extends true ? never // Plain property of type any (not method) + : T[P] extends (...args: any[]) => any ? P // a function (method) + : never; +}[keyof T]; +/** Default insert type of T is a subset of T where: + * * given optional props (such as an auto-generated primary key) are made optional + * * methods are omitted + */ +export type InsertType = Omit> & { + [P in OptionalProps]?: T[P]; +}; +/** IDType extract the actual type of the primary key: + * * If TKey is a literal type that names a property of T, extract the type using T[TKey] + * * Else, use TKey as is. + */ +export type IDType = IsStrictlyAny extends true ? TKeyPropNameOrKeyType : TKeyPropNameOrKeyType extends string ? TKeyPropNameOrKeyType extends keyof T ? T[TKeyPropNameOrKeyType] : TKeyPropNameOrKeyType : TKeyPropNameOrKeyType; +export type EntityTable> = Table, TInsertType>; +export declare var Dexie: DexieConstructor; +export interface _Table extends Table { +} +export interface _Collection extends Collection { +} +export declare module Dexie { + // The "Dexie.Promise" type. + type Promise = PromiseExtended; // Because many samples have been Dexie.Promise. + // The "Dexie.Table" interface. Same as named exported interface Table. + interface Table extends _Table { + } // Because all samples have been Dexie.Table<...> + // The "Dexie.Collection" interface. Same as named exported interface Collection. + interface Collection extends _Collection { + } // Because app-code may declare it. +} +export function liveQuery(querier: () => T | Promise): Observable; +export function mergeRanges(target: IntervalTree, newSet: IntervalTree): void; +export function rangesOverlap(rangeSet1: IntervalTree, rangeSet2: IntervalTree): boolean; +export function cmp(a: any, b: any): number; +/** Exporting 'Dexie' as the default export. + **/ +export default Dexie; + +export {}; diff --git a/dist/dexie.js b/dist/dexie.js new file mode 100644 index 000000000..c6c5c925d --- /dev/null +++ b/dist/dexie.js @@ -0,0 +1,5778 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 4.0.1-beta.1, Wed Oct 18 2023 + * + * https://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 = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Dexie = factory()); +})(this, (function () { 'use strict'; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + + var _global = typeof globalThis !== 'undefined' ? globalThis : + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + + var keys = Object.keys; + var isArray = Array.isArray; + if (typeof Promise !== 'undefined' && !_global.Promise) { + _global.Promise = Promise; + } + 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)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(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); + var proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); + } + var _slice = [].slice; + function slice(args, start, end) { + return _slice.call(args, start, end); + } + function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); + } + function assert(b) { + if (!b) + throw new Error("Assertion Failed"); + } + function asap$1(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); + } + 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 tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } + } + function getByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) + return obj[keyPath]; + 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) { + if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) + obj.splice(currentKeyPath, 1); + else + delete obj[currentKeyPath]; + } + else + obj[currentKeyPath] = value; + else { + var innerObj = obj[currentKeyPath]; + if (!innerObj || !hasOwn(obj, currentKeyPath)) + innerObj = (obj[currentKeyPath] = {}); + setByKeyPath(innerObj, remainingKeyPath, value); + } + } + else { + if (value === undefined) { + if (isArray(obj) && !isNaN(parseInt(keyPath))) + obj.splice(keyPath, 1); + else + 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); + } + var intrinsicTypeNames = "Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" + .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]; }); + var intrinsicTypes = new Set(intrinsicTypeNames.map(function (t) { return _global[t]; })); + function cloneSimpleObjectTree(o) { + var rv = {}; + for (var k in o) + if (hasOwn(o, k)) { + var v = o[k]; + rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); + } + return rv; + } + function objectIsEmpty(o) { + for (var k in o) + if (hasOwn(o, k)) + return false; + return true; + } + var circularRefs = null; + function deepClone(any) { + circularRefs = new WeakMap(); + var rv = innerDeepClone(any); + circularRefs = null; + return rv; + } + function innerDeepClone(x) { + if (!x || typeof x !== 'object') + return x; + var rv = circularRefs.get(x); + if (rv) + return rv; + if (isArray(x)) { + rv = []; + circularRefs.set(x, rv); + for (var i = 0, l = x.length; i < l; ++i) { + rv.push(innerDeepClone(x[i])); + } + } + else if (intrinsicTypes.has(x.constructor)) { + rv = x; + } + else { + var proto = getProto(x); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs.set(x, rv); + for (var prop in x) { + if (hasOwn(x, prop)) { + rv[prop] = innerDeepClone(x[prop]); + } + } + } + return rv; + } + var toString = {}.toString; + function toStringTag(o) { + return toString.call(o).slice(8, -1); + } + var iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; + var getIteratorOf = typeof iteratorSymbol === "symbol" ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); + } : function () { return null; }; + function delArrayItem(a, x) { + var i = a.indexOf(x); + if (i >= 0) + a.splice(i, 1); + return i >= 0; + } + var NO_CHAR_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; + } + var isAsyncFunction = typeof Symbol !== 'undefined' + ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } + : function () { return false; }; + + var debug = typeof location !== 'undefined' && + /^(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() { + if (NEEDS_THROW_FOR_STACK) + try { + getErrorWithStack.arguments; + throw new Error(); + } + 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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" + }; + function DexieError(name, msg) { + 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: " + Object.keys(failures) + .map(function (key) { return failures[key].toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) + .join('\n'); + } + function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + this.message = getMultiErrorMessage(msg, failures); + } + derive(ModifyError).from(DexieError); + function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = Object.keys(failures).map(function (pos) { return failures[pos]; }); + this.failuresByPos = failures; + this.message = getMultiErrorMessage(msg, this.failures); + } + derive(BulkError).from(DexieError); + var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); + var BaseException = DexieError; + var exceptions = errorList.reduce(function (obj, name) { + 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 = "".concat(msgOrInner).concat(!inner ? '' : '\n ' + inner); + this.inner = inner || null; + } + else if (typeof msgOrInner === 'object') { + this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name] = DexieError; + return obj; + }, {}); + 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) { + 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) { + 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) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, + onerror = 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, + onerror = 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); + var onsuccess = this.onsuccess, + onerror = 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); + }; + } + + var INTERNAL = {}; + var LONG_STACKS_CLIP_LIMIT = 100, + MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; + var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; + var patchGlobalPromise = !!resolvedGlobalPromise; + var stack_being_generated = false; + function schedulePhysicalTick() { + queueMicrotask(physicalTick); + } + var asap = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } + }; + var isOutsideMicroTick = true, + needsNewPhysicalTick = true, + unhandledErrors = [], + rejectingErrors = [], + currentFulfiller = null, rejectionMapper = mirror; + var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: nop, + pgp: false, + env: {}, + finalize: nop + }; + var PSD = globalPSD; + var microtickQueue = []; + var numScheduledCalls = 0; + var tickFinalizers = []; + function DexiePromise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this._lib = false; + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); + return; + } + this._state = null; + this._value = null; + ++psd.ref; + executePromiseTask(this, fn); + } + var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; + return then; + }, + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : + { + get: function () { + return value; + }, + set: thenProp.set + }); + } + }; + props(DexiePromise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (err) { + 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; + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new DexiePromise(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(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); + 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; + } + props(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) + .map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); }); + }); + }, + PSD: { + get: function () { return PSD; }, + set: function (value) { return PSD = value; } + }, + totalEchoes: { get: function () { return totalEchoes; } }, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap; }, + set: function (value) { asap = value; } + }, + rejectionMapper: { + get: function () { return rejectionMapper; }, + set: function (value) { rejectionMapper = value; } + }, + follow: function (fn, zoneProps) { + return new DexiePromise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject; + psd.finalize = callBoth(function () { + var _this = this; + 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); + }); + } + }); + if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) + .then(function () { return --remaining || resolve(results); }); }); + }); + }); + if (NativePromise.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); }); + }); + }); + } + function executePromiseTask(promise, fn) { + try { + fn(function (value) { + if (promise._state !== null) + return; + 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 DexiePromise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); + } + 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; + } + }); + }); + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); + } + function propagateAllListeners(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 (numScheduledCalls === 0) { + ++numScheduledCalls; + asap(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } + } + function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap(callListener, [cb, promise, listener]); + } + function callListener(cb, promise, listener) { + try { + currentFulfiller = promise; + var ret, value = promise._value; + if (promise._state) { + ret = cb(value); + } + else { + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); + } + listener.resolve(ret); + } + catch (e) { + listener.reject(e); + } + finally { + 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; + 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) { + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } + } + function physicalTick() { + usePSD(globalPSD, function () { + beginMicroTickScope() && endMicroTickScope(); + }); + } + function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; + } + 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); + 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(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } + function addPossiblyUnhandledError(promise) { + if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) + unhandledErrors.push(promise); + } + function markErrorAsHandled(promise) { + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + unhandledErrors.splice(i, 1); + return; + } + } + function PromiseReject(reason) { + return new DexiePromise(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(); + } + }; + } + var task = { awaits: 0, echoes: 0, id: 0 }; + var taskCounter = 0; + var zoneStack = []; + var zoneEchoes = 0; + var totalEchoes = 0; + var zone_id_counter = 0; + function newScope(fn, props, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) + } : {}; + if (props) + extend(psd, props); + ++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 incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; + } + function decrementExpectedAwaits() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; + } + if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; + } + 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; + } + 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)) { + queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + var GlobalPromise_1 = globalPSD.env.Promise; + var targetEnv = targetZone.env; + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise_1.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + GlobalPromise_1.all = targetEnv.all; + GlobalPromise_1.race = targetEnv.race; + GlobalPromise_1.resolve = targetEnv.resolve; + GlobalPromise_1.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise_1.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise_1.any = targetEnv.any; + } + } + } + function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + 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 nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { + 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); + if (cleanup) + queueMicrotask(decrementExpectedAwaits); + } + }; + } + function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; + } + var rejection = DexiePromise.reject; + + function tempTransaction(db, mode, storeNames, fn) { + if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { + if (db._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); + } + if (!db._state.isBeingOpened) { + if (!db._options.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); + } + return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + else { + var trans = db._createTransaction(mode, storeNames, db._dbSchema); + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + return rejection(ex); + } + return trans._promise(mode, function (resolve, reject) { + return newScope(function () { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function (result) { + if (mode === 'readwrite') + try { + trans.idbtrans.commit(); + } + catch (_a) { } + return mode === 'readonly' ? result : trans._completion.then(function () { return result; }); + }); + } + } + + var DEXIE_VERSION = '4.0.1-beta.1'; + var maxString = String.fromCharCode(65535); + 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 DBNAMES_DB = '__dbnames'; + var READONLY = 'readonly'; + var READWRITE = 'readwrite'; + + function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; + } + + var AnyRange = { + type: 3 , + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false + }; + + function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) + ? function (obj) { + if (obj[keyPath] === undefined && (keyPath in obj)) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } + : function (obj) { return obj; }; + } + + function Entity() { + throw exceptions.Type(); + } + + function cmp(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; + } + function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function type(x) { + var t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + var tsTag = toStringTag(x); + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; + } + function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); + } + + var Table = (function () { + function Table() { + } + Table.prototype._trans = function (mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + var tableName = this.name; + function checkTableInTransaction(resolve, reject, trans) { + if (!trans.schema[tableName]) + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + return fn(trans.idbtrans, trans); + } + var wasRootExec = beginMicroTickScope(); + try { + return trans && trans.db._novip === this.db._novip ? + trans === PSD.trans ? + trans._promise(mode, checkTableInTransaction, writeLocked) : + newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + } + finally { + if (wasRootExec) + endMicroTickScope(); + } + }; + Table.prototype.get = function (keyOrCrit, cb) { + var _this = this; + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + return this._trans('readonly', function (trans) { + return _this.core.get({ trans: trans, key: keyOrCrit }) + .then(function (res) { return _this.hook.reading.fire(res); }); + }).then(cb); + }; + Table.prototype.where = function (indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, "[".concat(indexOrCrit.join('+'), "]")); + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { + if (ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) { + for (var i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this + .where(keyPathsInValidOrder) + .equals(keyPathsInValidOrder.map(function (kp) { return indexOrCrit[kp]; })); + } + if (!compoundIndex && debug) + console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit of a ") + + "compound index [".concat(keyPaths.join('+'), "]")); + var idxByName = this.schema.idxByName; + var idb = this.db._deps.indexedDB; + function equals(a, b) { + return idb.cmp(a, b) === 0; + } + var _a = keyPaths.reduce(function (_a, keyPath) { + var prevIndex = _a[0], prevFilterFn = _a[1]; + var index = idxByName[keyPath]; + var value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? + combine(prevFilterFn, index && index.multi ? + function (x) { + var prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(function (item) { return equals(value, item); }); + } : function (x) { return equals(value, getByKeyPath(x, keyPath)); }) + : prevFilterFn + ]; + }, [null, null]), idx = _a[0], filterFunction = _a[1]; + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(filterFunction) : + compoundIndex ? + this.filter(filterFunction) : + this.where(keyPaths).equals(''); + }; + Table.prototype.filter = function (filterFunction) { + return this.toCollection().and(filterFunction); + }; + Table.prototype.count = function (thenShortcut) { + return this.toCollection().count(thenShortcut); + }; + Table.prototype.offset = function (offset) { + return this.toCollection().offset(offset); + }; + Table.prototype.limit = function (numRows) { + return this.toCollection().limit(numRows); + }; + Table.prototype.each = function (callback) { + return this.toCollection().each(callback); + }; + Table.prototype.toArray = function (thenShortcut) { + return this.toCollection().toArray(thenShortcut); + }; + Table.prototype.toCollection = function () { + return new this.db.Collection(new this.db.WhereClause(this)); + }; + Table.prototype.orderBy = function (index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? + "[".concat(index.join('+'), "]") : + index)); + }; + Table.prototype.reverse = function () { + return this.toCollection().reverse(); + }; + Table.prototype.mapToClass = function (constructor) { + var _a = this, db = _a.db, tableName = _a.name; + this.schema.mappedClass = constructor; + if (constructor.prototype instanceof Entity) { + constructor = (function (_super) { + __extends(class_1, _super); + function class_1() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(class_1.prototype, "db", { + get: function () { return db; }, + enumerable: false, + configurable: true + }); + class_1.prototype.table = function () { return tableName; }; + return class_1; + }(constructor)); + } + var inheritedProps = new Set(); + for (var proto = constructor.prototype; proto; proto = getProto(proto)) { + Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); }); + } + var readHook = function (obj) { + if (!obj) + return obj; + var res = Object.create(constructor.prototype); + for (var m in obj) + if (!inheritedProps.has(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; + }; + Table.prototype.defineClass = function () { + function Class(content) { + extend(this, content); + } + return this.mapToClass(Class); + }; + Table.prototype.add = function (obj, key) { + var _this = this; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); + }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + }; + Table.prototype.update = function (keyOrObject, modifications) { + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + 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 { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + }; + Table.prototype.put = function (obj, key) { + var _this = this; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + }; + Table.prototype.delete = function (key) { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.clear = function () { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.bulkGet = function (keys) { + var _this = this; + return this._trans('readonly', function (trans) { + return _this.core.getMany({ + keys: keys, + trans: trans + }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); }); + }); + }; + Table.prototype.bulkAdd = function (objects, keysOrOptions, options) { + var _this = this; + var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToAdd = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); + }); + }); + }; + Table.prototype.bulkPut = function (objects, keysOrOptions, options) { + var _this = this; + var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToPut = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); + }); + }); + }; + Table.prototype.bulkUpdate = function (keysAndChanges) { + var _this = this; + var coreTable = this.core; + var keys = keysAndChanges.map(function (entry) { return entry.key; }); + var changeSpecs = keysAndChanges.map(function (entry) { return entry.changes; }); + var offsetMap = []; + return this._trans('readwrite', function (trans) { + return coreTable.getMany({ trans: trans, keys: keys, cache: 'clone' }).then(function (objs) { + var resultKeys = []; + var resultObjs = []; + keysAndChanges.forEach(function (_a, idx) { + var key = _a.key, changes = _a.changes; + var obj = objs[idx]; + if (obj) { + for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { + var keyPath = _b[_i]; + var value = changes[keyPath]; + if (keyPath === _this.schema.primKey.keyPath) { + if (cmp(value, key) !== 0) { + throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); + } + } + else { + setByKeyPath(obj, keyPath, value); + } + } + offsetMap.push(idx); + resultKeys.push(key); + resultObjs.push(obj); + } + }); + var numEntries = resultKeys.length; + return coreTable + .mutate({ + trans: trans, + type: 'put', + keys: resultKeys, + values: resultObjs, + updates: { + keys: keys, + changeSpecs: changeSpecs + } + }) + .then(function (_a) { + var numFailures = _a.numFailures, failures = _a.failures; + if (numFailures === 0) + return numEntries; + for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { + var offset = _b[_i]; + var mappedOffset = offsetMap[Number(offset)]; + if (mappedOffset != null) { + var failure = failures[offset]; + delete failures[offset]; + failures[mappedOffset] = failure; + } + } + throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); + }); + }); + }); + }; + Table.prototype.bulkDelete = function (keys) { + var _this = this; + var numKeys = keys.length; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'delete', keys: keys }); + }).then(function (_a) { + var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures; + if (numFailures === 0) + return lastResult; + throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); + }); + }; + return Table; + }()); + + function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + 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 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) { + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + var context = add(eventName, mirror, function fire() { + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + context.subscribers.forEach(function (fn) { + asap$1(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } + } + + function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype: prototype }); + return constructor; + } + + function createTableConstructor(db) { + return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) { + this.db = db; + this._tx = trans; + this.name = name; + this.schema = tableSchema; + this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + }); + } + + function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); + } + 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); + } + function getIndexOrStore(ctx, coreSchema) { + if (ctx.isPrimKey) + return coreSchema.primaryKey; + var index = coreSchema.getIndexByKeyPath(ctx.index); + if (!index) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); + return index; + } + function openCursor(ctx, coreTable, trans) { + var index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans: trans, + values: !ctx.keysOnly, + reverse: ctx.dir === 'prev', + unique: !!ctx.unique, + query: { + index: index, + range: ctx.range + } + }); + } + function iter(ctx, fn, coreTrans, coreTable) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); + } + else { + var set_1 = {}; + var union = function (item, cursor, advance) { + if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set_1, key)) { + set_1[key] = true; + fn(item, cursor, advance); + } + } + }; + return Promise.all([ + ctx.or._iterate(union, coreTrans), + iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) + ]); + } + } + function iterate(cursorPromise, filter, fn, valueMapper) { + var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(function (cursor) { + if (cursor) { + return cursor.start(function () { + var c = function () { return cursor.continue(); }; + if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; })) + wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; }); + c(); + }); + } + }); + } + + var Collection = (function () { + function Collection() { + } + Collection.prototype._read = function (fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readonly', fn).then(cb); + }; + Collection.prototype._write = function (fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readwrite', fn, "locked"); + }; + Collection.prototype._addAlgorithm = function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }; + Collection.prototype._iterate = function (fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + }; + Collection.prototype.clone = function (props) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props) + extend(ctx, props); + rv._ctx = ctx; + return rv; + }; + Collection.prototype.raw = function () { + this._ctx.valueMapper = null; + return this; + }; + Collection.prototype.each = function (fn) { + var ctx = this._ctx; + return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); }); + }; + Collection.prototype.count = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + var coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans: trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(function (count) { return Math.min(count, ctx.limit); }); + } + else { + var count = 0; + return iter(ctx, function () { ++count; return false; }, trans, coreTable) + .then(function () { return count; }); + } + }).then(cb); + }; + Collection.prototype.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); + }; + Collection.prototype.toArray = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + var valueMapper_1 = ctx.valueMapper; + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + limit: ctx.limit, + values: true, + query: { + index: index, + range: ctx.range + } + }).then(function (_a) { + var result = _a.result; + return valueMapper_1 ? result.map(valueMapper_1) : result; + }); + } + else { + var a_1 = []; + return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; }); + } + }, cb); + }; + Collection.prototype.offset = function (offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + 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; + }; + Collection.prototype.limit = function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + }; + Collection.prototype.until = function (filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + }; + Collection.prototype.first = function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.last = function (cb) { + return this.reverse().first(cb); + }; + Collection.prototype.filter = function (filterFunction) { + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + }; + Collection.prototype.and = function (filter) { + return this.filter(filter); + }; + Collection.prototype.or = function (indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + }; + Collection.prototype.reverse = function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }; + Collection.prototype.desc = function () { + return this.reverse(); + }; + Collection.prototype.eachKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }; + Collection.prototype.eachUniqueKey = function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }; + Collection.prototype.eachPrimaryKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }; + Collection.prototype.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); + }; + Collection.prototype.primaryKeys = function (cb) { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(function (trans) { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + values: false, + limit: ctx.limit, + query: { + index: index, + range: ctx.range + } + }); + }).then(function (_a) { + var result = _a.result; + return result; + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }; + Collection.prototype.uniqueKeys = function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }; + Collection.prototype.firstKey = function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.lastKey = function (cb) { + return this.reverse().firstKey(cb); + }; + Collection.prototype.distinct = function () { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }; + Collection.prototype.modify = function (changes) { + var _this = this; + var ctx = this._ctx; + return this._write(function (trans) { + var modifyer; + if (typeof changes === 'function') { + modifyer = changes; + } + else { + 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); + anythingModified = true; + } + } + return anythingModified; + }; + } + var coreTable = ctx.table.core; + var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey; + var limit = _this.db._options.modifyChunkSize || 200; + var totalFailures = []; + var successCount = 0; + var failedKeys = []; + var applyMutateResult = function (expectedCount, res) { + var failures = res.failures, numFailures = res.numFailures; + successCount += expectedCount - numFailures; + for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) { + var pos = _a[_i]; + totalFailures.push(failures[pos]); + } + }; + return _this.clone().primaryKeys().then(function (keys) { + var nextChunk = function (offset) { + var count = Math.min(limit, keys.length - offset); + return coreTable.getMany({ + trans: trans, + keys: keys.slice(offset, offset + count), + cache: "immutable" + }).then(function (values) { + var addValues = []; + var putValues = []; + var putKeys = outbound ? [] : null; + var deleteKeys = []; + for (var i = 0; i < count; ++i) { + var origValue = values[i]; + var ctx_1 = { + value: deepClone(origValue), + primKey: keys[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { + deleteKeys.push(keys[offset + i]); + addValues.push(ctx_1.value); + } + else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys[offset + i]); + } + } + } + var criteria = isPlainKeyRange(ctx) && + ctx.limit === Infinity && + (typeof changes !== 'function' || changes === deleteCallback) && { + index: ctx.index, + range: ctx.range + }; + return Promise.resolve(addValues.length > 0 && + coreTable.mutate({ trans: trans, type: 'add', values: addValues }) + .then(function (res) { + for (var pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(function () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) && + coreTable.mutate({ + trans: trans, + type: 'put', + keys: putKeys, + values: putValues, + criteria: criteria, + changeSpec: typeof changes !== 'function' + && changes + }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && + coreTable.mutate({ + trans: trans, + type: 'delete', + keys: deleteKeys, + criteria: criteria + }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { + return keys.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(function () { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys.length; + }); + }); + }); + }; + Collection.prototype.delete = function () { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 )) + { + return this._write(function (trans) { + var primaryKey = ctx.table.core.schema.primaryKey; + var coreRange = range; + return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) { + return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange }) + .then(function (_a) { + var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures; + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(deleteCallback); + }; + return Collection; + }()); + var deleteCallback = function (value, ctx) { return ctx.value = null; }; + + function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) { + this.db = db; + var keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx; + var table = whereCtx.table; + var readingHook = table.hook.reading.fire; + 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: readingHook !== mirror ? readingHook : null + }; + }); + } + + 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 fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new collectionOrWhereClause.Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; + } + function emptyCollection(whereClause) { + return new whereClause.Collection(whereClause, function () { return rangeEqual(""); }).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 whereClause.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); + c._ondirectionchange = function (direction) { + 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; + } + function createRange(lower, upper, lowerOpen, upperOpen) { + return { + type: 2 , + lower: lower, + upper: upper, + lowerOpen: lowerOpen, + upperOpen: upperOpen + }; + } + function rangeEqual(value) { + return { + type: 1 , + lower: value, + upper: value + }; + } + + var WhereClause = (function () { + function WhereClause() { + } + Object.defineProperty(WhereClause.prototype, "Collection", { + get: function () { + return this._ctx.table.db.Collection; + }, + enumerable: false, + configurable: true + }); + WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) { + includeLower = includeLower !== false; + includeUpper = includeUpper === true; + try { + if ((this._cmp(lower, upper) > 0) || + (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); + return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); }); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }; + WhereClause.prototype.equals = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return rangeEqual(value); }); + }; + WhereClause.prototype.above = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, true); }); + }; + WhereClause.prototype.aboveOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, false); }); + }; + WhereClause.prototype.below = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value, false, true); }); + }; + WhereClause.prototype.belowOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value); }); + }; + WhereClause.prototype.startsWith = function (str) { + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }; + WhereClause.prototype.startsWithIgnoreCase = function (str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }; + WhereClause.prototype.equalsIgnoreCase = function (str) { + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }; + WhereClause.prototype.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, ""); + }; + WhereClause.prototype.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); + }; + WhereClause.prototype.anyOf = function () { + var _this = this; + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = this._cmp; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); }); + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? + _this._ascending : + _this._descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + ++i; + if (i === set.length) { + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + return true; + } + else { + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }; + WhereClause.prototype.notEqual = function (value) { + return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.noneOf = function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new this.Collection(this); + try { + set.sort(this._ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + 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], this.db._maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.inAnyRange = function (ranges, options) { + var _this = this; + var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; + 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; + var includeUppers = options && options.includeUppers === true; + function addRange(ranges, newRange) { + var i = 0, l = ranges.length; + for (; 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]); } + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var rangePos = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function (key) { return ascending(key, set[rangePos][1]) > 0; } : + function (key) { return ascending(key, set[rangePos][1]) >= 0; }; + var keyIsBeforeCurrentEntry = includeLowers ? + function (key) { return descending(key, set[rangePos][0]) > 0; } : + function (key) { return descending(key, set[rangePos][0]) >= 0; }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new this.Collection(this, function () { return createRange(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)) { + ++rangePos; + if (rangePos === set.length) { + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + return true; + } + else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { + return false; + } + else { + advance(function () { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + }; + WhereClause.prototype.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]; })); + }; + return WhereClause; + }()); + + function createWhereClauseConstructor(db) { + return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) { + this.db = db; + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + this._cmp = this._ascending = cmp; + this._descending = function (a, b) { return cmp(b, a); }; + this._max = function (a, b) { return cmp(a, b) > 0 ? a : b; }; + this._min = function (a, b) { return cmp(a, b) < 0 ? a : b; }; + this._IDBKeyRange = db._deps.IDBKeyRange; + if (!this._IDBKeyRange) + throw new exceptions.MissingAPI(); + }); + } + + function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); + } + function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); + } + + var DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; + var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; + var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + + var Transaction = (function () { + function Transaction() { + } + Transaction.prototype._lock = function () { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }; + Transaction.prototype._unlock = function () { + assert(!PSD.global); + 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; + }; + Transaction.prototype._locked = function () { + return this._reculock && PSD.lockOwnerFor !== this; + }; + Transaction.prototype.create = function (idbtrans) { + var _this = this; + if (!this.mode) + return this; + var idbdb = this.db.idbdb; + var dbOpenError = this.db._state.dbOpenError; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) + throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + idbtrans = this.idbtrans = idbtrans || + (this.db.core + ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) + : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); + idbtrans.onerror = wrap(function (ev) { + preventDefault(ev); + _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(); + if ('mutatedParts' in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + return this; + }; + Transaction.prototype._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 DexiePromise(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 DexiePromise(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 DexiePromise(function (resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }; + Transaction.prototype._root = function () { + return this.parent ? this.parent._root() : this; + }; + Transaction.prototype.waitFor = function (promiseLike) { + var root = this._root(); + var promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(function () { return promise; }); + } + else { + root._waitingFor = promise; + root._waitingQueue = []; + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new DexiePromise(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) { + root._waitingFor = null; + } + }); + }); + }; + Transaction.prototype.abort = function () { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + }; + Transaction.prototype.table = function (tableName) { + var memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + var tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + }; + return Transaction; + }()); + + function createTransactionConstructor(db) { + return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + var _this = this; + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + 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; + this._completion = new DexiePromise(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); + }); + }); + } + + function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { + return { + name: name, + keyPath: keyPath, + unique: unique, + multi: multi, + auto: auto, + compound: compound, + src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) + }; + } + function nameFromKeyPath(keyPath) { + return typeof keyPath === 'string' ? + keyPath : + keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; + } + + function createTableSchema(name, primKey, indexes) { + return { + name: name, + primKey: primKey, + indexes: indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }) + }; + } + + function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; + } + var getMaxKey = function (IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + getMaxKey = function () { return [[]]; }; + return [[]]; + } + catch (e) { + getMaxKey = function () { return maxString; }; + return maxString; + } + }; + + function getKeyExtractor(keyPath) { + if (keyPath == null) { + return function () { return undefined; }; + } + else if (typeof keyPath === 'string') { + return getSinglePathKeyExtractor(keyPath); + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } + } + function getSinglePathKeyExtractor(keyPath) { + var split = keyPath.split('.'); + if (split.length === 1) { + return function (obj) { return obj[keyPath]; }; + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } + } + + function arrayify(arrayLike) { + return [].slice.call(arrayLike); + } + var _id_counter = 0; + function getKeyPathAlias(keyPath) { + return keyPath == null ? + ":id" : + typeof keyPath === 'string' ? + keyPath : + "[".concat(keyPath.join('+'), "]"); + } + function createDBCore(db, IdbKeyRange, tmpTrans) { + function extractSchema(db, trans) { + var tables = arrayify(db.objectStoreNames); + return { + schema: { + name: db.name, + tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) { + var keyPath = store.keyPath, autoIncrement = store.autoIncrement; + var compound = isArray(keyPath); + var outbound = keyPath == null; + var indexByKeyPath = {}; + var result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound: outbound, + compound: compound, + keyPath: keyPath, + autoIncrement: autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); }) + .map(function (index) { + var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath; + var compound = isArray(keyPath); + var result = { + name: name, + compound: compound, + keyPath: keyPath, + unique: unique, + multiEntry: multiEntry, + extractKey: getKeyExtractor(keyPath) + }; + indexByKeyPath[getKeyPathAlias(keyPath)] = result; + return result; + }), + getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; } + }; + indexByKeyPath[":id"] = result.primaryKey; + if (keyPath != null) { + indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; + } + return result; + }) + }, + hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && + !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) + }; + } + function makeIDBKeyRange(range) { + if (range.type === 3 ) + return null; + if (range.type === 4 ) + throw new Error("Cannot convert never type to IDBKeyRange"); + var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; + var idbRange = lower === undefined ? + upper === undefined ? + null : + IdbKeyRange.upperBound(upper, !!upperOpen) : + upper === undefined ? + IdbKeyRange.lowerBound(lower, !!lowerOpen) : + IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); + return idbRange; + } + function createDbCoreTable(tableSchema) { + var tableName = tableSchema.name; + function mutate(_a) { + var trans = _a.trans, type = _a.type, keys = _a.keys, values = _a.values, range = _a.range; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var outbound = store.keyPath == null; + var isAddOrPut = type === "put" || type === "add"; + if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') + throw new Error("Invalid operation type: " + type); + var length = (keys || values || { length: 1 }).length; + if (keys && values && keys.length !== values.length) { + throw new Error("Given keys array must have same length as given values array."); + } + if (length === 0) + return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); + var req; + var reqs = []; + var failures = []; + var numFailures = 0; + var errorHandler = function (event) { + ++numFailures; + preventDefault(event); + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined }); + if (range.type === 3 ) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } + else { + var _a = isAddOrPut ? + outbound ? + [values, keys] : + [values, null] : + [keys, null], args1 = _a[0], args2 = _a[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + reqs.push(req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i]))); + req.onerror = errorHandler; + } + } + else { + for (var i = 0; i < length; ++i) { + reqs.push(req = store[type](args1[i])); + req.onerror = errorHandler; + } + } + } + var done = function (event) { + var lastResult = event.target.result; + reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); }); + resolve({ + numFailures: numFailures, + failures: failures, + results: type === "delete" ? keys : reqs.map(function (req) { return req.result; }), + lastResult: lastResult + }); + }; + req.onerror = function (event) { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor(_a) { + var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? + store : + store.index(index.name); + var direction = reverse ? + unique ? + "prevunique" : + "prev" : + unique ? + "nextunique" : + "next"; + var req = values || !('openKeyCursor' in source) ? + source.openCursor(makeIDBKeyRange(range), direction) : + source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function (ev) { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + var _cursorContinue = cursor.continue.bind(cursor); + var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + var _cursorAdvance = cursor.advance.bind(cursor); + var doThrowCursorIsNotStarted = function () { throw new Error("Cursor not started"); }; + var doThrowCursorIsStopped = function () { throw new Error("Cursor not stopped"); }; + cursor.trans = trans; + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; + cursor.fail = wrap(reject); + cursor.next = function () { + var _this = this; + var gotOne = 1; + return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; }); + }; + cursor.start = function (callback) { + var iterationPromise = new Promise(function (resolveIteration, rejectIteration) { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = function (value) { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + var guardedCallback = function () { + if (req.result) { + try { + callback(); + } + catch (err) { + cursor.fail(err); + } + } + else { + cursor.done = true; + cursor.start = function () { throw new Error("Cursor behind last entry"); }; + cursor.stop(); + } + }; + req.onsuccess = wrap(function (ev) { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll) { + return function (request) { + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var trans = request.trans, values = request.values, limit = request.limit, query = request.query; + var nonInfinitLimit = limit === Infinity ? undefined : limit; + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasGetAll) { + var req = values ? + source.getAll(idbKeyRange, nonInfinitLimit) : + source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = function (event) { return resolve({ result: event.target.result }); }; + req.onerror = eventRejectHandler(reject); + } + else { + var count_1 = 0; + var req_1 = values || !('openKeyCursor' in source) ? + source.openCursor(idbKeyRange) : + source.openKeyCursor(idbKeyRange); + var result_1 = []; + req_1.onsuccess = function (event) { + var cursor = req_1.result; + if (!cursor) + return resolve({ result: result_1 }); + result_1.push(values ? cursor.value : cursor.primaryKey); + if (++count_1 === limit) + return resolve({ result: result_1 }); + cursor.continue(); + }; + req_1.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate: mutate, + getMany: function (_a) { + var trans = _a.trans, keys = _a.keys; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var req; + var successHandler = function (event) { + var req = event.target; + if ((result[req._pos] = req.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys[i]; + if (key != null) { + req = store.get(keys[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get: function (_a) { + var trans = _a.trans, key = _a.key; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var req = store.get(key); + req.onsuccess = function (event) { return resolve(event.target.result); }; + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll), + openCursor: openCursor, + count: function (_a) { + var query = _a.query, trans = _a.trans; + var index = query.index, range = query.range; + return new Promise(function (resolve, reject) { + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); }); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll; + var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); }); + var tableMap = {}; + tables.forEach(function (table) { return tableMap[table.name] = table; }); + return { + stack: "dbcore", + transaction: db.transaction.bind(db), + table: function (name) { + var result = tableMap[name]; + if (!result) + throw new Error("Table '".concat(name, "' not found")); + return tableMap[name]; + }, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema: schema + }; + } + + function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce(function (down, _a) { + var create = _a.create; + return (__assign(__assign({}, down), create(down))); + }, stackImpl); + } + function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) { + var IDBKeyRange = _a.IDBKeyRange; _a.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore: dbcore + }; + } + function generateMiddlewareStacks(db, tmpTrans) { + var idbdb = tmpTrans.db; + var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); + db.core = stacks.dbcore; + db.tables.forEach(function (table) { + var tableName = table.name; + if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) { + table.core = db.core.table(tableName); + if (db[tableName] instanceof db.Table) { + db[tableName].core = table.core; + } + } + }); + } + + function setApiOnPlace(db, objs, tableNames, dbschema) { + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + var propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { + if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { + setProp(obj, tableName, { + get: function () { return this.table(tableName); }, + set: function (value) { + defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true }); + } + }); + } + else { + obj[tableName] = new db.Table(tableName, schema); + } + } + }); + }); + } + function removeTablesApi(db, objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof db.Table) + delete obj[key]; + } + }); + } + function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; + } + function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { + var globalSchema = db._dbSchema; + var trans = db._createTransaction('readwrite', db._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + var transless = PSD.transless || PSD; + newScope(function () { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(function (tableName) { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db, idbUpgradeTrans); + DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); + } + else + updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction); + }); + } + function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { + var queue = []; + var versions = db._versions; + var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); + 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(db, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(function (tuple) { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + var store_1 = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(function (idx) { return addIndex(store_1, idx); }); + change.change.forEach(function (idx) { + store_1.deleteIndex(idx.name); + addIndex(store_1, idx); + }); + change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); }); + } + }); + var contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db, idbUpgradeTrans); + trans._memoizedTables = {}; + anyContentUpgraderHasRun = true; + var upgradeSchema_1 = shallowClone(newSchema); + diff.del.forEach(function (table) { + upgradeSchema_1[table] = oldSchema[table]; + }); + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); + trans.schema = upgradeSchema_1; + var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync_1) { + incrementExpectedAwaits(); + } + var returnValue_1; + var promiseFollowed = DexiePromise.follow(function () { + returnValue_1 = contentUpgrade(trans); + if (returnValue_1) { + if (contentUpgradeIsAsync_1) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue_1.then(decrementor, decrementor); + } + } + }); + return (returnValue_1 && typeof returnValue_1.then === 'function' ? + DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; })); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + var newSchema = version._cfg.dbschema; + deleteRemovedTables(newSchema, idbtrans); + } + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); + trans.schema = db._dbSchema; + }); + }); + function runQueue() { + return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + DexiePromise.resolve(); + } + return runQueue().then(function () { + createMissingTables(globalSchema, idbUpgradeTrans); + }); + } + function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] + }; + var table; + for (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.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || + (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) + { + change.recreate = true; + diff.change.push(change); + } + else { + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + var idxName = void 0; + for (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) { return 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) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) { + return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); + }); + } + function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); + } + function buildGlobalSchema(db, idbdb, tmpTrans) { + var globalSchema = {}; + var dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(function (storeName) { + var store = tmpTrans.objectStore(storeName); + var keyPath = store.keyPath; + var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); + indexes.push(index); + } + globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); + }); + return globalSchema; + } + function readGlobalSchema(db, idbdb, tmpTrans) { + db.verno = idbdb.version / 10; + var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); + db._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); + } + function verifyInstalledSchema(db, tmpTrans) { + var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); + var diff = getSchemaDiff(installedSchema, db._dbSchema); + return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; })); + } + function adjustToExistingIndexNames(db, schema, idbtrans) { + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + db._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; + delete schema[storeName].idxByName[dexieName]; + schema[storeName].idxByName[indexName] = indexSpec; + } + } + } + } + if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + db._hasGetAll = false; + } + } + function parseIndexSyntax(primKeyAndIndexes) { + return primKeyAndIndexes.split(',').map(function (index, indexNum) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); + }); + } + + var Version = (function () { + function Version() { + } + Version.prototype._parseStoresSpec = function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + 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"); + }); + outSchema[tableName] = createTableSchema(tableName, primKey, indexes); + } + }); + }; + Version.prototype.stores = function (stores) { + var db = this.db; + this._cfg.storesSource = this._cfg.storesSource ? + extend(this._cfg.storesSource, stores) : + stores; + var versions = db._versions; + var storesSpec = {}; + var dbschema = {}; + versions.forEach(function (version) { + extend(storesSpec, version._cfg.storesSource); + dbschema = (version._cfg.dbschema = {}); + version._parseStoresSpec(storesSpec, dbschema); + }); + db._dbSchema = dbschema; + removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); + setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + db._storeNames = keys(dbschema); + return this; + }; + Version.prototype.upgrade = function (upgradeFunction) { + this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + }; + return Version; + }()); + + function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); + } + + function getDbNamesTable(indexedDB, IDBKeyRange) { + var dbNamesDB = indexedDB["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB: indexedDB, + IDBKeyRange: IDBKeyRange, + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); + } + function hasDatabasesNative(indexedDB) { + return indexedDB && typeof indexedDB.databases === "function"; + } + function getDatabaseNames(_a) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + return hasDatabasesNative(indexedDB) + ? Promise.resolve(indexedDB.databases()).then(function (infos) { + return infos + .map(function (info) { return info.name; }) + .filter(function (name) { return name !== DBNAMES_DB; }); + }) + : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); + } + function _onDatabaseCreated(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop); + } + function _onDatabaseDeleted(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); + } + + function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); + } + + function idbReady() { + var isSafari = !navigator.userAgentData && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function (resolve) { + var tryIdb = function () { return indexedDB.databases().finally(resolve); }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function () { return clearInterval(intervalId); }); + } + + var _a; + function isEmptyRange(node) { + return !("from" in node); + } + var RangeSet = function (fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + var rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } + }; + props(RangeSet.prototype, (_a = { + add: function (rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey: function (key) { + addRange(this, key, key); + return this; + }, + addKeys: function (keys) { + var _this = this; + keys.forEach(function (key) { return addRange(_this, key, key); }); + return this; + } + }, + _a[iteratorSymbol] = function () { + return getRangeSetIterator(this); + }, + _a)); + function addRange(target, from, to) { + var diff = cmp(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from: from, to: to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges(target, left); + } + if (right && rightWasCutOff) { + mergeRanges(target, right); + } + } + function mergeRanges(target, newSet) { + function _addRangeSet(target, _a) { + var from = _a.from, to = _a.to, l = _a.l, r = _a.r; + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); + } + function rangesOverlap(rangeSet1, rangeSet2) { + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) + : (b = (nextResult2 = i2.next(a.from)).value); + } + return false; + } + function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function (key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; + } + function rebalance(target) { + var _a, _b; + var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + var l = r === "r" ? "l" : "r"; + var rootClone = __assign({}, target); + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); + } + function computeDepth(_a) { + var r = _a.r, l = _a.l; + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; + } + + function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(function (part) { + if (target[part]) + mergeRanges(target[part], newSet[part]); + else + target[part] = cloneSimpleObjectTree(newSet[part]); + }); + return target; + } + + function obsSetsOverlap(os1, os2) { + return Object.keys(os1).some(function (key) { return os2[key] && rangesOverlap(os2[key], os1[key]); }); + } + + var cache = {}; + + var unsignaledParts = {}; + var isTaskEnqueued = false; + function signalSubscribersLazily(part) { + extendObservabilitySet(unsignaledParts, part); + if (!isTaskEnqueued) { + isTaskEnqueued = true; + setTimeout(function () { + isTaskEnqueued = false; + var parts = unsignaledParts; + unsignaledParts = {}; + signalSubscribersNow(parts); + }, 0); + } + } + function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { + if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; } + var queriesToSignal = new Set(); + for (var key in updatedParts) { + var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); + if (parts) { + var dbName = parts[1], tableName = parts[2]; + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (tblCache) + signalTableSubscribersNow(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); + } + } + queriesToSignal.forEach(function (requery) { return requery(); }); + } + function signalTableSubscribersNow(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { + var updatedEntryLists = deleteAffectedCacheEntries && []; + for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) { + var _b = _a[_i], indexName = _b[0], entries = _b[1]; + var filteredEntries = deleteAffectedCacheEntries && []; + for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { + var entry = entries_1[_c]; + if (entry.obsSet && obsSetsOverlap(updatedParts, entry.obsSet)) { + entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); }); + } + else if (deleteAffectedCacheEntries) { + filteredEntries.push(entry); + } + } + if (deleteAffectedCacheEntries) + updatedEntryLists.push([indexName, filteredEntries]); + } + if (deleteAffectedCacheEntries) { + for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { + var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; + tblCache.queries.query[indexName] = filteredEntries; + } + } + } + + function dexieOpen(db) { + var state = db._state; + var indexedDB = db._deps.indexedDB; + if (state.isBeingOpened || db.idbdb) + return state.dbReadyPromise.then(function () { return state.dbOpenError ? + rejection(state.dbOpenError) : + db; }); + debug && (state.openCanceller._stackHolder = getErrorWithStack()); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + var openCanceller = state.openCanceller; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed('db.open() was cancelled'); + } + var resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null, wasCreated = false; + return DexiePromise.race([openCanceller, (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(function () { return new DexiePromise(function (resolve, reject) { + throwIfCancelled(); + if (!indexedDB) + throw new exceptions.MissingAPI(); + var dbName = db.name; + var req = state.autoSchema ? + indexedDB.open(dbName) : + indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI(); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db._fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + wasCreated = oldVer < 1; + db.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function () { + upgradeTransaction = null; + var idbdb = db.idbdb = req.result; + var objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); + if (state.autoSchema) + readGlobalSchema(db, idbdb, tmpTrans); + else { + adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); + if (!verifyInstalledSchema(db, tmpTrans)) { + console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail."); + } + } + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(function (ev) { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(function (ev) { + db.on("close").fire(ev); + }); + if (wasCreated) + _onDatabaseCreated(db._deps, dbName); + resolve(); + }, reject); + }); })]).then(function () { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders); + } + }); + }).finally(function () { + if (state.openCanceller === openCanceller) { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + } + }).catch(function (err) { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (_a) { } + if (openCanceller === state.openCanceller) { + db._close(); + } + return rejection(err); + }).finally(function () { + state.openComplete = true; + resolveDbReady(); + }).then(function () { + if (wasCreated) { + var everything_1 = {}; + db.tables.forEach(function (table) { + table.schema.indexes.forEach(function (idx) { + if (idx.name) + everything_1["idb://".concat(db.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet(-Infinity, [[[]]]); + }); + everything_1["idb://".concat(db.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db.name, "/").concat(table.name, "/:dels")] = new RangeSet(-Infinity, [[[]]]); + }); + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); + signalSubscribersNow(everything_1, true); + } + return db; + }); + } + + 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)(); + } + + function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + scopeFunc = args.pop(); + var tables = flatten(args); + return [mode, tables, scopeFunc]; + } + function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { + return DexiePromise.resolve().then(function () { + var transless = PSD.transless || PSD; + var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); + trans.explicit = true; + var zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } + else { + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); }); + } + return rejection(ex); + } + } + var scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = DexiePromise.follow(function () { + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (scopeFuncIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue).then(function (x) { return trans.active ? + x + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) + : promiseFollowed.then(function () { return returnValue; })).then(function (x) { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(function () { return x; }); + }).catch(function (e) { + trans._reject(e); + return rejection(e); + }); + }); + } + + function pad(a, value, count) { + var result = isArray(a) ? a.slice() : [a]; + for (var i = 0; i < count; ++i) + result.push(value); + return result; + } + function createVirtualIndexMiddleware(down) { + return __assign(__assign({}, down), { table: function (tableName) { + var table = down.table(tableName); + var schema = table.schema; + var indexLookup = {}; + var allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + var keyPathAlias = getKeyPathAlias(keyPath); + var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); + var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; + var isVirtual = keyTail > 0; + var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual + ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") + : lowLevelIndex.name, lowLevelIndex: lowLevelIndex, isVirtual: isVirtual, keyTail: keyTail, keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + var virtualKeyPath = keyLength === 2 ? + keyPath[0] : + keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort(function (a, b) { return a.keyTail - b.keyTail; }); + return virtualIndex; + } + var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) { + var index = _a[_i]; + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + var result = indexLookup[getKeyPathAlias(keyPath)]; + return result && result[0]; + } + function translateRange(range, keyTail) { + return { + type: range.type === 1 ? + 2 : + range.type, + lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), + lowerOpen: true, + upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), + upperOpen: true + }; + } + function translateRequest(req) { + var index = req.query.index; + return index.isVirtual ? __assign(__assign({}, req), { query: { + index: index.lowLevelIndex, + range: translateRange(req.query.range, index.keyTail) + } }) : req; + } + var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) { + return table.count(translateRequest(req)); + }, query: function (req) { + return table.query(translateRequest(req)); + }, openCursor: function (req) { + var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength; + if (!isVirtual) + return table.openCursor(req); + function createVirtualCursor(cursor) { + function _continue(key) { + key != null ? + cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : + req.unique ? + cursor.continue(cursor.key.slice(0, keyLength) + .concat(req.reverse + ? down.MIN_KEY + : down.MAX_KEY, keyTail)) : + cursor.continue(); + } + var virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value: function (key, primaryKey) { + cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); + } + }, + primaryKey: { + get: function () { + return cursor.primaryKey; + } + }, + key: { + get: function () { + var key = cursor.key; + return keyLength === 1 ? + key[0] : + key.slice(0, keyLength); + } + }, + value: { + get: function () { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)) + .then(function (cursor) { return cursor && createVirtualCursor(cursor); }); + } }); + return result; + } }); + } + var virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware + }; + + function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) { + rv[prfx + prop] = undefined; + } + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { + var apTypeName = toStringTag(ap); + var bpTypeName = toStringTag(bp); + if (apTypeName !== bpTypeName) { + rv[prfx + prop] = b[prop]; + } + else if (apTypeName === 'Object') { + getObjectDiff(ap, bp, rv, prfx + prop + '.'); + } + else if (ap !== bp) { + rv[prfx + prop] = b[prop]; + } + } + else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; + } + + function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); + } + + var hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) { + var downTable = downCore.table(tableName); + var primaryKey = downTable.schema.primaryKey; + var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) { + var dxTrans = PSD.trans; + var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating; + switch (req.type) { + case 'add': + if (creating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'put': + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'delete': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'deleteRange': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true); + } + return downTable.mutate(req); + function addPutOrDelete(req) { + var dxTrans = PSD.trans; + var keys = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req); + if (req.type !== 'delete') + req.values = __spreadArray([], req.values, true); + if (req.keys) + req.keys = __spreadArray([], req.keys, true); + return getExistingValues(downTable, req, keys).then(function (existingValues) { + var contexts = keys.map(function (key, i) { + var existingValue = existingValues[i]; + var ctx = { onerror: null, onsuccess: null }; + if (req.type === 'delete') { + deleting.fire.call(ctx, key, existingValue, dxTrans); + } + else if (req.type === 'add' || existingValue === undefined) { + var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); + if (key == null && generatedPrimaryKey != null) { + key = generatedPrimaryKey; + req.keys[i] = key; + if (!primaryKey.outbound) { + setByKeyPath(req.values[i], primaryKey.keyPath, key); + } + } + } + else { + var objectDiff = getObjectDiff(existingValue, req.values[i]); + var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); + if (additionalChanges_1) { + var requestedValue_1 = req.values[i]; + Object.keys(additionalChanges_1).forEach(function (keyPath) { + if (hasOwn(requestedValue_1, keyPath)) { + requestedValue_1[keyPath] = additionalChanges_1[keyPath]; + } + else { + setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); + } + }); + } + } + return ctx; + }); + return downTable.mutate(req).then(function (_a) { + var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult; + for (var i = 0; i < keys.length; ++i) { + var primKey = results ? results[i] : keys[i]; + var ctx = contexts[i]; + if (primKey == null) { + ctx.onerror && ctx.onerror(failures[i]); + } + else { + ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? + req.values[i] : + primKey + ); + } + } + return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult }; + }).catch(function (error) { + contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); }); + return Promise.reject(error); + }); + }); + } + function deleteRange(req) { + return deleteNextChunk(req.trans, req.range, 10000); + } + function deleteNextChunk(trans, range, limit) { + return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit }) + .then(function (_a) { + var result = _a.result; + return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) { + if (res.numFailures > 0) + return Promise.reject(res.failures[0]); + if (result.length < limit) { + return { failures: [], numFailures: 0, lastResult: undefined }; + } + else { + return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); + } + }); + }); + } + } }); + return tableMiddleware; + } })); } + }; + function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" + ? Promise.resolve([]) + : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); + } + + function getFromTransactionCache(keys, cache, clone) { + try { + if (!cache) + return null; + if (cache.keys.length < keys.length) + return null; + var result = []; + for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { + if (cmp(cache.keys[i], keys[j]) !== 0) + continue; + result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); + ++j; + } + return result.length === keys.length ? result : null; + } + catch (_a) { + return null; + } + } + var cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: function (core) { + return { + table: function (tableName) { + var table = core.table(tableName); + return __assign(__assign({}, table), { getMany: function (req) { + if (!req.cache) { + return table.getMany(req); + } + var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then(function (res) { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res, + }; + return res; + }); + }, mutate: function (req) { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + } }); + }, + }; + }, + }; + + function isCachableContext(ctx, table) { + return (ctx.trans.mode === 'readonly' && + !!ctx.subscr && + !ctx.trans.explicit && + ctx.trans.db._options.cache !== 'disabled' && + !table.schema.primaryKey.outbound); + } + + function isCachableRequest(type, req) { + switch (type) { + case 'query': + return req.values && !req.unique; + case 'get': + return false; + case 'getMany': + return false; + case 'count': + return false; + case 'openCursor': + return false; + } + } + + var observabilityMiddleware = { + stack: "dbcore", + level: 0, + name: "Observability", + create: function (core) { + var dbName = core.schema.name; + var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); + return __assign(__assign({}, core), { transaction: function (stores, mode, options) { + if (PSD.subscr && mode !== 'readonly') { + throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); + } + return core.transaction(stores, mode, options); + }, table: function (tableName) { + var table = core.table(tableName); + var schema = table.schema; + var primaryKey = schema.primaryKey; + var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound; + var tableClone = __assign(__assign({}, table), { mutate: function (req) { + var trans = req.trans; + var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); + var getRangeSet = function (indexName) { + var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); + return (mutatedParts[part] || + (mutatedParts[part] = new RangeSet())); + }; + var pkRangeSet = getRangeSet(""); + var delsRangeSet = getRangeSet(":dels"); + var type = req.type; + var _a = req.type === "deleteRange" + ? [req.range] + : req.type === "delete" + ? [req.keys] + : req.values.length < 50 + ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values] + : [], keys = _a[0], newObjs = _a[1]; + var oldCache = req.trans["_cache"]; + if (isArray(keys)) { + pkRangeSet.addKeys(keys); + var oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null; + if (!oldObjs && type !== "add") { + delsRangeSet.addKeys(keys); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } + else if (keys) { + var range = { from: keys.lower, to: keys.upper }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } + else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); }); + } + return table.mutate(req).then(function (res) { + if (keys && (req.type === 'add' || req.type === 'put')) { + pkRangeSet.addKeys(res.results); + } + trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); + return res; + }); + } }); + var getRange = function (_a) { + var _b, _c; + var _d = _a.query, index = _d.index, range = _d.range; + return [ + index, + new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY), + ]; + }; + var readSubscribers = { + get: function (req) { return [primaryKey, new RangeSet(req.key)]; }, + getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; }, + count: getRange, + query: getRange, + openCursor: getRange, + }; + keys(readSubscribers).forEach(function (method) { + tableClone[method] = function (req) { + var subscr = PSD.subscr; + var isLiveQuery = !!subscr; + var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); + var obsSet = cachable + ? req.obsSet = {} + : subscr; + if (isLiveQuery) { + var getRangeSet = function (indexName) { + var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); + return (obsSet[part] || + (obsSet[part] = new RangeSet())); + }; + var pkRangeSet_1 = getRangeSet(""); + var delsRangeSet_1 = getRangeSet(":dels"); + var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1]; + getRangeSet(queriedIndex.name || "").add(queriedRanges); + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet_1.add(FULL_RANGE); + } + else { + var keysPromise_1 = method === "query" && + outbound && + req.values && + table.query(__assign(__assign({}, req), { values: false })); + return table[method].apply(this, arguments).then(function (res) { + if (method === "query") { + if (outbound && req.values) { + return keysPromise_1.then(function (_a) { + var resultingKeys = _a.result; + pkRangeSet_1.addKeys(resultingKeys); + return res; + }); + } + var pKeys = req.values + ? res.result.map(extractKey) + : res.result; + if (req.values) { + pkRangeSet_1.addKeys(pKeys); + } + else { + delsRangeSet_1.addKeys(pKeys); + } + } + else if (method === "openCursor") { + var cursor_1 = res; + var wantValues_1 = req.values; + return (cursor_1 && + Object.create(cursor_1, { + key: { + get: function () { + delsRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.key; + }, + }, + primaryKey: { + get: function () { + var pkey = cursor_1.primaryKey; + delsRangeSet_1.addKey(pkey); + return pkey; + }, + }, + value: { + get: function () { + wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.value; + }, + }, + })); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + } }); + }, + }; + function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + var rangeSet = getRangeSet(ix.name || ""); + function extractKey(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key) + ? key.forEach(function (key) { return rangeSet.addKey(key); }) + : rangeSet.addKey(key); }; + (oldObjs || newObjs).forEach(function (_, i) { + var oldKey = oldObjs && extractKey(oldObjs[i]); + var newKey = newObjs && extractKey(newObjs[i]); + if (cmp(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); + } + + function isAboveLower(key, range) { + return range.lower === undefined + ? true + : range.lowerOpen + ? cmp(key, range.lower) > 0 + : cmp(key, range.lower) >= 0; + } + function isBelowUpper(key, range) { + return range.upper === undefined + ? true + : range.upperOpen + ? cmp(key, range.upper) < 0 + : cmp(key, range.upper) <= 0; + } + function isWithinRange(key, range) { + return isAboveLower(key, range) && isBelowUpper(key, range); + } + + function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { + if (!ops || ops.length === 0) + return result; + var index = req.query.index; + var primaryKey = table.schema.primaryKey; + var extractPrimKey = primaryKey.extractKey; + var extractIndex = index.extractKey; + var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; + var finalResult = ops.reduce(function (result, op) { + var modifedResult = result; + var includedValues = op.type === 'add' || op.type === 'put' + ? op.values.filter(function (v) { + return isWithinRange(extractIndex(v), req.query.range); + }).map(function (v) { + v = deepClone(v); + if (immutable) + Object.freeze(v); + return v; + }) + : []; + switch (op.type) { + case 'add': + modifedResult = result.concat(req.values + ? includedValues + : includedValues.map(function (v) { return extractPrimKey(v); })); + break; + case 'put': + var keySet_1 = new RangeSet().addKeys(op.values.map(function (v) { return extractPrimKey(v); })); + modifedResult = result + .filter(function (item) { + var key = req.values ? extractPrimKey(item) : item; + return !rangesOverlap(new RangeSet(key), keySet_1); + }) + .concat(req.values + ? includedValues + : includedValues.map(function (v) { return extractPrimKey(v); })); + break; + case 'delete': + var keysToDelete_1 = new RangeSet().addKeys(op.keys); + modifedResult = result.filter(function (item) { + var key = req.values ? extractPrimKey(item) : item; + return !rangesOverlap(new RangeSet(key), keysToDelete_1); + }); + break; + case 'deleteRange': + var range_1 = op.range; + modifedResult = result.filter(function (item) { return !isWithinRange(extractPrimKey(item), range_1); }); + break; + } + return modifedResult; + }, result); + if (finalResult === result) + return result; + finalResult.sort(function (a, b) { + return cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) || + cmp(extractPrimKey(a), extractPrimKey(b)); + }); + if (req.limit && req.limit < Infinity) { + if (finalResult.length > req.limit) { + finalResult.length = req.limit; + } + else if (result.length === req.limit && finalResult.length < req.limit) { + cacheEntry.dirty = true; + } + } + return immutable ? Object.freeze(finalResult) : finalResult; + } + + function areRangesEqual(r1, r2) { + return (cmp(r1.lower, r2.lower) === 0 && + cmp(r1.upper, r2.upper) === 0 && + !!r1.lowerOpen === !!r2.lowerOpen && + !!r1.upperOpen === !!r2.upperOpen); + } + + function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { + if (lower1 === undefined) + return lower2 !== undefined ? -1 : 0; + if (lower2 === undefined) + return 1; + var c = cmp(lower1, lower2); + if (c === 0) { + if (lowerOpen1 && lowerOpen2) + return 0; + if (lowerOpen1) + return 1; + if (lowerOpen2) + return -1; + } + return c; + } + function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { + if (upper1 === undefined) + return upper2 !== undefined ? 1 : 0; + if (upper2 === undefined) + return -1; + var c = cmp(upper1, upper2); + if (c === 0) { + if (upperOpen1 && upperOpen2) + return 0; + if (upperOpen1) + return -1; + if (upperOpen2) + return 1; + } + return c; + } + function isSuperRange(r1, r2) { + return (compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && + compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0); + } + + function findCompatibleQuery(dbName, tableName, type, req) { + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (!tblCache) + return []; + var queries = tblCache.queries[type]; + if (!queries) + return [null, false, tblCache, null]; + var indexName = req.query ? req.query.index.name : null; + var entries = queries[indexName || '']; + if (!entries) + return [null, false, tblCache, null]; + switch (type) { + case 'query': + var equalEntry = entries.find(function (entry) { + return entry.req.limit === req.limit && + entry.req.values === req.values && + areRangesEqual(entry.req.query.range, req.query.range); + }); + if (equalEntry) + return [ + equalEntry, + true, + tblCache, + entries, + ]; + var superEntry = entries.find(function (entry) { + var limit = 'limit' in entry.req ? entry.req.limit : Infinity; + return (limit >= req.limit && + (req.values ? entry.req.values : true) && + isSuperRange(entry.req.query.range, req.query.range)); + }); + return [superEntry, false, tblCache, entries]; + case 'count': + var countQuery = entries.find(function (entry) { + return areRangesEqual(entry.req.query.range, req.query.range); + }); + return [countQuery, !!countQuery, tblCache, entries]; + } + } + + function subscribeToCacheEntry(cacheEntry, container, requery, signal) { + cacheEntry.subscribers.add(requery); + signal.addEventListener("abort", function () { + cacheEntry.subscribers.delete(requery); + if (cacheEntry.subscribers.size === 0) { + enqueForDeletion(cacheEntry, container); + } + }); + } + function enqueForDeletion(cacheEntry, container) { + setTimeout(function () { + if (cacheEntry.subscribers.size === 0) { + delArrayItem(container, cacheEntry); + } + }, 3000); + } + + var cacheMiddleware = { + stack: 'dbcore', + level: 0, + name: 'Cache', + create: function (core) { + var dbName = core.schema.name; + var coreMW = __assign(__assign({}, core), { transaction: function (stores, mode, options) { + var idbtrans = core.transaction(stores, mode, options); + if (mode === 'readwrite') { + var ac_1 = new AbortController(); + var signal = ac_1.signal; + var endTransaction = function (wasCommitted) { return function () { + ac_1.abort(); + if (mode === 'readwrite') { + var affectedSubscribers_1 = new Set(); + for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { + var storeName = stores_1[_i]; + var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; + var table = core.table(storeName); + if (tblCache) { + var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; }); + if (ops.length > 0) { + tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; }); + for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) { + var entries = _b[_a]; + for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { + var entry = _d[_c]; + if (entry.res != null && + idbtrans.mutatedParts + ) { + if (wasCommitted && !entry.dirty) { + var freezeResults = Object.isFrozen(entry.res); + var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); + if (entry.dirty) { + delArrayItem(entries, entry); + entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); + } + else if (modRes !== entry.res) { + entry.res = modRes; + entry.promise = DexiePromise.resolve({ result: modRes }); + } + } + else { + if (entry.dirty) { + delArrayItem(entries, entry); + } + entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); + } + } + } + } + } + } + } + affectedSubscribers_1.forEach(function (requery) { return requery(); }); + } + }; }; + idbtrans.addEventListener('abort', endTransaction(false), { + signal: signal, + }); + idbtrans.addEventListener('error', endTransaction(false), { + signal: signal, + }); + idbtrans.addEventListener('complete', endTransaction(true), { + signal: signal, + }); + } + return idbtrans; + }, table: function (tableName) { + var downTable = core.table(tableName); + var primKey = downTable.schema.primaryKey; + var tableMW = __assign(__assign({}, downTable), { mutate: function (req) { + if (primKey.outbound || + PSD.trans.db._options.cache === 'disabled' + ) { + return downTable.mutate(req); + } + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (!tblCache) + return downTable.mutate(req); + var promise = downTable.mutate(req); + if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function (key) { return key == null; }))) { + promise.then(function (res) { + var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function (value, i) { + var valueWithKey = primKey.keyPath.includes('.') + ? deepClone(value) + : __assign({}, value); + setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); + return valueWithKey; + }) }); + tblCache.optimisticOps.push(reqWithResolvedKeys); + queueMicrotask(function () { return signalSubscribersLazily(req.mutatedParts); }); + }); + } + else { + tblCache.optimisticOps.push(req); + signalSubscribersLazily(req.mutatedParts); + promise.catch(function () { + delArrayItem(tblCache.optimisticOps, req); + signalSubscribersLazily(req.mutatedParts); + }); + } + return promise; + }, query: function (req) { + if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) + return downTable.query(req); + var freezeResults = PSD.trans.db._options.cache === 'immutable'; + var _a = PSD, requery = _a.requery, signal = _a.signal; + var _b = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _b[0], exactMatch = _b[1], tblCache = _b[2], container = _b[3]; + if (cacheEntry && exactMatch) { + cacheEntry.obsSet = req.obsSet; + } + else { + var promise = downTable.query(req).then(function (res) { + var result = res.result; + cacheEntry.res = result; + if (freezeResults) { + for (var i = 0, l = result.length; i < l; ++i) { + Object.freeze(result[i]); + } + Object.freeze(result); + } + else { + res.result = deepClone(result); + } + return res; + }).catch(function (error) { + if (container && cacheEntry) + delArrayItem(container, cacheEntry); + return Promise.reject(error); + }); + cacheEntry = { + obsSet: req.obsSet, + promise: promise, + subscribers: new Set(), + type: 'query', + req: req, + dirty: false, + }; + if (container) { + container.push(cacheEntry); + } + else { + container = [cacheEntry]; + if (!tblCache) { + tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { + queries: { + query: {}, + count: {}, + }, + objs: new Map(), + optimisticOps: [], + unsignaledParts: {} + }; + } + tblCache.queries.query[req.query.index.name || ''] = container; + } + } + subscribeToCacheEntry(cacheEntry, container, requery, signal); + return cacheEntry.promise.then(function (res) { + return { + result: applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults), + }; + }); + } }); + return tableMW; + } }); + return coreMW; + }, + }; + + function vipify(target, vipDb) { + return new Proxy(target, { + get: function (target, prop, receiver) { + if (prop === 'db') + return vipDb; + return Reflect.get(target, prop, receiver); + } + }); + } + + var Dexie$1 = (function () { + function Dexie(name, options) { + var _this = this; + this._middlewares = {}; + this.verno = 0; + var deps = Dexie.dependencies; + this._options = options = __assign({ + addons: Dexie.addons, autoOpen: true, + indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange, cache: 'cloned' }, options); + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + var addons = options.addons; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + this._novip = this; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3 + }; + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + var state = _this._state; + if (state.openComplete) { + if (!state.dbOpenError) + DexiePromise.resolve().then(subscriber); + if (bSticky) + subscribe(subscriber); + } + else if (state.onReadyBeingFired) { + state.onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + subscribe(subscriber); + var db_1 = _this; + if (!bSticky) + subscribe(function unsubscribe() { + db_1.on.ready.unsubscribe(subscriber); + db_1.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.Collection = createCollectionConstructor(this); + this.Table = createTableConstructor(this); + this.Transaction = createTransactionConstructor(this); + this.Version = createVersionConstructor(this); + this.WhereClause = createWhereClauseConstructor(this); + this.on("versionchange", function (ev) { + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); + else + console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); + _this.close({ disableAutoOpen: false }); + _this._state.openComplete = false; + }); + this.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); + else + console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); + }); + this._maxKey = getMaxKey(options.IDBKeyRange); + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); }; + this._fireOnBlocked = function (ev) { + _this.on("blocked").fire(ev); + connections + .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; }) + .map(function (c) { return c.on("versionchange").fire(ev); }); + }; + this.use(cacheExistingValuesMiddleware); + this.use(cacheMiddleware); + this.use(observabilityMiddleware); + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + var vipDB = new Proxy(this, { + get: function (_, prop, receiver) { + if (prop === '_vip') + return true; + if (prop === 'table') + return function (tableName) { return vipify(_this.table(tableName), vipDB); }; + var rv = Reflect.get(_, prop, receiver); + if (rv instanceof Table) + return vipify(rv, vipDB); + if (prop === 'tables') + return rv.map(function (t) { return vipify(t, vipDB); }); + if (prop === '_createTransaction') + return function () { + var tx = rv.apply(this, arguments); + return vipify(tx, vipDB); + }; + return rv; + } + }); + this.vip = vipDB; + addons.forEach(function (addon) { return addon(_this); }); + } + Dexie.prototype.version = function (versionNumber) { + if (isNaN(versionNumber) || versionNumber < 0.1) + throw new exceptions.Type("Given version is not a positive number"); + versionNumber = Math.round(versionNumber * 10) / 10; + if (this.idbdb || this._state.isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versions = this._versions; + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new this.Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + versionInstance.stores({}); + this._state.autoSchema = false; + return versionInstance; + }; + Dexie.prototype._whenReady = function (fn) { + var _this = this; + return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) { + if (_this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); + } + if (!_this._state.isBeingOpened) { + if (!_this._options.autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + _this.open().catch(nop); + } + _this._state.dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + Dexie.prototype.use = function (_a) { + var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name; + if (name) + this.unuse({ stack: stack, name: name }); + var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name }); + middlewares.sort(function (a, b) { return a.level - b.level; }); + return this; + }; + Dexie.prototype.unuse = function (_a) { + var stack = _a.stack, name = _a.name, create = _a.create; + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(function (mw) { + return create ? mw.create !== create : + name ? mw.name !== name : + false; + }); + } + return this; + }; + Dexie.prototype.open = function () { + var _this = this; + return usePSD(globalPSD, + function () { return dexieOpen(_this); }); + }; + Dexie.prototype._close = function () { + var state = this._state; + var idx = connections.indexOf(this); + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this.idbdb = null; + } + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + }; + Dexie.prototype.close = function (_a) { + var _b = _a === void 0 ? { disableAutoOpen: true } : _a, disableAutoOpen = _b.disableAutoOpen; + this._close(); + var state = this._state; + if (disableAutoOpen) + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + }; + Dexie.prototype.delete = function () { + var _this = this; + var hasArguments = arguments.length > 0; + var state = this._state; + return new DexiePromise(function (resolve, reject) { + var doDelete = function () { + _this.close({ disableAutoOpen: false }); + var req = _this._deps.indexedDB.deleteDatabase(_this.name); + req.onsuccess = wrap(function () { + _onDatabaseDeleted(_this._deps, _this.name); + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = _this._fireOnBlocked; + }; + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (state.isBeingOpened) { + state.dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + }); + }; + Dexie.prototype.backendDB = function () { + return this.idbdb; + }; + Dexie.prototype.isOpen = function () { + return this.idbdb !== null; + }; + Dexie.prototype.hasBeenClosed = function () { + var dbOpenError = this._state.dbOpenError; + return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); + }; + Dexie.prototype.hasFailed = function () { + return this._state.dbOpenError !== null; + }; + Dexie.prototype.dynamicallyOpened = function () { + return this._state.autoSchema; + }; + Object.defineProperty(Dexie.prototype, "tables", { + get: function () { + var _this = this; + return keys(this._allTables).map(function (name) { return _this._allTables[name]; }); + }, + enumerable: false, + configurable: true + }); + Dexie.prototype.transaction = function () { + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + Dexie.prototype._transaction = function (mode, tables, scopeFunc) { + var _this = this; + var parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); + var idbMode, storeNames; + try { + storeNames = tables.map(function (table) { + var storeName = table instanceof _this.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; + }); + if (mode == "r" || mode === READONLY) + idbMode = READONLY; + else if (mode == "rw" || mode == READWRITE) + idbMode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + if (parentTransaction.mode === READONLY && idbMode === READWRITE) { + if (onlyIfCompatible) { + 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) { + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, function (_, reject) { reject(e); }) : + rejection(e); + } + var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return (parentTransaction ? + parentTransaction._promise(idbMode, enterTransaction, "lock") : + PSD.trans ? + usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) : + this._whenReady(enterTransaction)); + }; + Dexie.prototype.table = function (tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); + } + return this._allTables[tableName]; + }; + return Dexie; + }()); + + var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol + ? Symbol.observable + : "@@observable"; + var Observable = (function () { + function Observable(subscribe) { + this._subscribe = subscribe; + } + Observable.prototype.subscribe = function (x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error: error, complete: complete } : x); + }; + Observable.prototype[symbolObservable] = function () { + return this; + }; + return Observable; + }()); + + var domDeps; + try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; + } + catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; + } + + function liveQuery(querier) { + var hasValue = false; + var currentValue; + var observable = new Observable(function (observer) { + var scopeFuncIsAsync = isAsyncFunction(querier); + function execute(ctx) { + var wasRootExec = beginMicroTickScope(); + try { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var rv = newScope(querier, ctx); + if (scopeFuncIsAsync) { + rv.finally(decrementExpectedAwaits); + } + return rv; + } + finally { + wasRootExec && endMicroTickScope(); + } + } + var closed = false; + var abortController; + var accumMuts = {}; + var currentObs = {}; + var subscription = { + get closed() { + return closed; + }, + unsubscribe: function () { + if (closed) + return; + closed = true; + if (abortController) + abortController.abort(); + if (startedListening) + globalEvents.storagemutated.unsubscribe(mutationListener); + }, + }; + observer.start && observer.start(subscription); + var startedListening = false; + function shouldNotify() { + return obsSetsOverlap(currentObs, accumMuts); + } + var mutationListener = function (parts) { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + var doQuery = function () { + if (closed || + !domDeps.indexedDB) + { + return; + } + accumMuts = {}; + var subscr = {}; + if (abortController) + abortController.abort(); + abortController = new AbortController(); + var ctx = { + subscr: subscr, + signal: abortController.signal, + requery: doQuery, + querier: querier, + trans: null + }; + var ret = execute(ctx); + Promise.resolve(ret).then(function (result) { + hasValue = true; + currentValue = result; + if (closed || ctx.signal.aborted) { + return; + } + accumMuts = {}; + currentObs = subscr; + if (!objectIsEmpty(currentObs) && !startedListening) { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); + startedListening = true; + } + observer.next && observer.next(result); + }, function (err) { + hasValue = false; + if (!['DatabaseClosedError', 'AbortError'].includes(err === null || err === void 0 ? void 0 : err.name)) { + if (closed) + return; + observer.error && observer.error(err); + } + }); + }; + doQuery(); + return subscription; + }); + observable.hasValue = function () { return hasValue; }; + observable.getValue = function () { return currentValue; }; + return observable; + } + + var Dexie = Dexie$1; + props(Dexie, __assign(__assign({}, fullNameExceptions), { + delete: function (databaseName) { + var db = new Dexie(databaseName, { addons: [] }); + return db.delete(); + }, + exists: function (name) { + return new Dexie(name, { addons: [] }).open().then(function (db) { + db.close(); + return true; + }).catch('NoSuchDatabaseError', function () { return false; }); + }, + getDatabaseNames: function (cb) { + try { + return getDatabaseNames(Dexie.dependencies).then(cb); + } + catch (_a) { + return rejection(new exceptions.MissingAPI()); + } + }, + defineClass: function () { + function Class(content) { + extend(this, content); + } + return Class; + }, ignoreTransaction: function (scopeFunc) { + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : + scopeFunc(); + }, vip: vip, async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return DexiePromise.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 DexiePromise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + currentTransaction: { + get: function () { return PSD.trans || null; } + }, waitFor: function (promiseOrFunction, optionalTimeout) { + var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? + Dexie.ignoreTransaction(promiseOrFunction) : + promiseOrFunction) + .timeout(optionalTimeout || 60000); + return PSD.trans ? + PSD.trans.waitFor(promise) : + promise; + }, + Promise: DexiePromise, + debug: { + get: function () { return debug; }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); + } + }, + derive: derive, extend: extend, props: props, override: override, + Events: Events, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet, + getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: domDeps, cache: cache, + 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)); }) })); + Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); + + if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) { + if (!propagatingLocally) { + var event_1; + if (isIEOrEdge) { + event_1 = document.createEvent('CustomEvent'); + event_1.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts); + } + else { + event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + } + propagatingLocally = true; + dispatchEvent(event_1); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) { + var detail = _a.detail; + if (!propagatingLocally) { + propagateLocally(detail); + } + }); + } + function propagateLocally(updateParts) { + var wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + signalSubscribersNow(updateParts, true); + } + finally { + propagatingLocally = wasMe; + } + } + var propagatingLocally = false; + + if (typeof BroadcastChannel !== 'undefined') { + var bc_1 = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + if (typeof bc_1.unref === 'function') { + bc_1.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + if (!propagatingLocally) { + bc_1.postMessage(changedParts); + } + }); + bc_1.onmessage = function (ev) { + if (ev.data) + propagateLocally(ev.data); + }; + } + else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + try { + if (!propagatingLocally) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({ + trig: Math.random(), + changedParts: changedParts, + })); + } + if (typeof self['clients'] === 'object') { + __spreadArray([], self['clients'].matchAll({ includeUncontrolled: true }), true).forEach(function (client) { + return client.postMessage({ + type: STORAGE_MUTATED_DOM_EVENT_NAME, + changedParts: changedParts, + }); + }); + } + } + } + catch (_a) { } + }); + if (typeof addEventListener !== 'undefined') { + addEventListener('storage', function (ev) { + if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) { + var data = JSON.parse(ev.newValue); + if (data) + propagateLocally(data.changedParts); + } + }); + } + var swContainer = self.document && navigator.serviceWorker; + if (swContainer) { + swContainer.addEventListener('message', propagateMessageLocally); + } + } + function propagateMessageLocally(_a) { + var data = _a.data; + if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) { + propagateLocally(data.changedParts); + } + } + + DexiePromise.rejectionMapper = mapError; + setDebug(debug, dexieStackFrameFilter); + + var namedExports = /*#__PURE__*/Object.freeze({ + __proto__: null, + Dexie: Dexie$1, + liveQuery: liveQuery, + Entity: Entity, + cmp: cmp, + 'default': Dexie$1, + RangeSet: RangeSet, + mergeRanges: mergeRanges, + rangesOverlap: rangesOverlap + }); + + __assign(Dexie$1, namedExports, { default: Dexie$1 }); + + return Dexie$1; + +})); +//# sourceMappingURL=dexie.js.map diff --git a/dist/dexie.js.map b/dist/dexie.js.map new file mode 100644 index 000000000..3e6c10700 --- /dev/null +++ b/dist/dexie.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.js","sources":["../node_modules/.pnpm/tslib@2.3.1/node_modules/tslib/tslib.es6.js","../src/globals/global.ts","../src/functions/utils.ts","../src/helpers/debug.ts","../src/errors/errors.js","../src/functions/chaining-functions.js","../src/helpers/promise.js","../src/functions/temp-transaction.ts","../src/globals/constants.ts","../src/functions/combine.ts","../src/dbcore/keyrange.ts","../src/functions/workaround-undefined-primkey.ts","../src/classes/entity/Entity.ts","../src/functions/cmp.ts","../src/classes/table/table.ts","../src/helpers/Events.js","../src/functions/make-class-constructor.ts","../src/classes/table/table-constructor.ts","../src/classes/collection/collection-helpers.ts","../src/classes/collection/collection.ts","../src/classes/collection/collection-constructor.ts","../src/functions/compare-functions.ts","../src/classes/where-clause/where-clause-helpers.ts","../src/classes/where-clause/where-clause.ts","../src/classes/where-clause/where-clause-constructor.ts","../src/functions/event-wrappers.ts","../src/globals/global-events.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/functions/quirks.ts","../src/dbcore/get-key-extractor.ts","../src/dbcore/dbcore-indexeddb.ts","../src/classes/dexie/generate-middleware-stacks.ts","../src/classes/version/schema-helpers.ts","../src/classes/version/version.ts","../src/classes/version/version-constructor.ts","../src/helpers/database-enumerator.ts","../src/classes/dexie/vip.ts","../node_modules/.pnpm/safari-14-idb-fix@3.0.0/node_modules/safari-14-idb-fix/dist/index.js","../src/helpers/rangeset.ts","../src/live-query/extend-observability-set.ts","../src/live-query/obs-sets-overlap.ts","../src/live-query/cache/cache.ts","../src/live-query/cache/signalSubscribers.ts","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/functions/get-object-diff.ts","../src/dbcore/get-effective-keys.ts","../src/hooks/hooks-middleware.ts","../src/dbcore/cache-existing-values-middleware.ts","../src/live-query/cache/is-cachable-context.ts","../src/live-query/cache/is-cachable-request.ts","../src/live-query/observability-middleware.ts","../src/live-query/cache/is-within-range.ts","../src/live-query/cache/apply-optimistic-ops.ts","../src/live-query/cache/are-ranges-equal.ts","../src/live-query/cache/is-super-range.ts","../src/live-query/cache/find-compatible-query.ts","../src/live-query/cache/subscribe-cachentry.ts","../src/live-query/cache/cache-middleware.ts","../src/helpers/vipify.ts","../src/classes/dexie/dexie.ts","../src/classes/observable/observable.ts","../src/classes/dexie/dexie-dom-dependencies.ts","../src/live-query/live-query.ts","../src/classes/dexie/dexie-static-props.ts","../src/live-query/propagate-locally.ts","../src/live-query/enable-broadcast.ts","../src/index.ts","../src/index-umd.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise){\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _global }\n\nexport function extend(obj: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nconst _slice = [].slice;\nexport function slice(args, start?, end?) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn: (...args: any[])=>void, onerror, args?) : void {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath)) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a: (T | T[])[]) : T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n \"Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]);\nconst intrinsicTypes = new Set(intrinsicTypeNames.map(t=>_global[t]));\n\n/** Deep clone a simple object tree.\n * \n * Copies object tree deeply, but does not deep-copy arrays,\n * typed arrays, Dates or other intrinsic types.\n * \n * Does not check for cyclic references.\n * \n * This function is 6 times faster than structuredClone() on chromium 111.\n * \n * This function can safely be used for cloning ObservabilitySets and RangeSets.\n * \n * @param o Object to clone\n * @returns Cloned object\n */\nexport function cloneSimpleObjectTree(o: T): T {\n const rv = {} as T;\n for (const k in o) if (hasOwn(o, k)) {\n const v = o[k];\n rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v);\n }\n return rv;\n}\n\nexport function objectIsEmpty(o: object) {\n for (const k in o) if (hasOwn(o, k)) return false;\n return true;\n}\n\nlet circularRefs: null | WeakMap = null;\n\n/** Deep clone an object or array.\n * \n * \n * @param any \n * @returns \n */\nexport function deepClone(any: T): T {\n circularRefs = new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(x: T): T {\n if (!x || typeof x !== 'object') return x;\n let rv = circularRefs.get(x); // Resolve circular references\n if (rv) return rv;\n if (isArray(x)) {\n rv = [];\n circularRefs.set(x, rv);\n for (var i = 0, l = x.length; i < l; ++i) {\n rv.push(innerDeepClone(x[i]));\n }\n } else if (intrinsicTypes.has(x.constructor)) {\n // For performance, we're less strict than structuredClone - we're only\n // cloning arrays and custom objects.\n // Typed arrays, Dates etc are not cloned.\n rv = x;\n } else {\n // We're nicer to custom classes than what structuredClone() is -\n // we preserve the proto of each object.\n const proto = getProto(x);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs.set(x, rv);\n for (var prop in x) {\n if (hasOwn(x, prop)) {\n rv[prop] = innerDeepClone(x[prop]);\n }\n }\n }\n return rv;\n}\n\nconst {toString} = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\n\nexport function delArrayItem(a: any[], x: any) {\n const i = a.indexOf(x);\n if (i >= 0) a.splice(i, 1);\n return i >= 0;\n}\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : ()=>false;\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch(e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\n// TODO: Replace this in favor of a decorator instead.\nexport function deprecated (what: string, fn: (...args)=>T) {\n return function () {\n console.warn(`${what} is deprecated. See https://dexie.org/docs/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n } as (...args)=>T\n}\n","import { derive, setProp } from '../functions/utils';\nimport { getErrorWithStack, prettyStack } from '../helpers/debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function() {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key=>failures[key].toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, this.failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport { _global } from '../globals/global';\nimport {tryCatch, props, setProp,\n getPropertyDescriptor, getArrayOf, extend, getProto} from '../functions/utils';\nimport {nop, callBoth, mirror} from '../functions/chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from '../errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (()=>{\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nfunction schedulePhysicalTick() {\n queueMicrotask(physicalTick);\n}\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: nop,\n pgp: false,\n env: {},\n finalize: nop\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function DexiePromise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n }\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n \n stack: {\n get: function() {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack (this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function') return new DexiePromise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled) setProp (DexiePromise, \"allSettled\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined') setProp(DexiePromise, \"any\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => resolve(value),\n failure => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }));\n });\n });\n}\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n \n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\nfunction getStack (promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n \n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with queueMicrotask().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n usePSD(globalPSD, ()=>{\n // Make sure to reset the async context to globalPSD before\n // executing any of the microtick subscribers.\n beginMicroTickScope() && endMicroTickScope();\n });\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: DexiePromise, configurable: true, writable: true},\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits() {\n if (!task.awaits) return false;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n return true;\n}\n\nif ((''+nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n if (cleanup) queueMicrotask(decrementExpectedAwaits);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone),\n nativeAwaitCompatibleWrap(onRejected, zone));\n };\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport {DexiePromise};\n","import { PSD, rejection, newScope } from \"../helpers/promise\";\nimport { DexieOptions } from \"../public/types/dexie-constructor\";\nimport { errnames, exceptions } from \"../errors\";\nimport { nop } from \"./chaining-functions\";\nimport { Transaction } from \"../classes/transaction\";\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n*/\nexport function tempTransaction (\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any)\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n{\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n if (mode === 'readwrite') try {trans.idbtrans.commit();} catch {}\n return mode === 'readonly' ? result : trans._completion.then(() => result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","import { Dexie } from \"../classes/dexie\";\n\nexport const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\nexport const STRING_EXPECTED = \"String expected.\";\nexport const connections: Dexie[] = [];\nexport const isIEOrEdge =\n typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nexport const hasIEDeleteObjectStoreBug = isIEOrEdge;\nexport const hangsOnDeleteLargeKeyRange = isIEOrEdge;\nexport const dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n}\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true\n}\n","import { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\n}","import { exceptions } from \"../../errors\";\n\nexport function Entity(){\n throw exceptions.Type();\n}\n","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { DexiePromise as Promise, PSD, newScope, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport { isArray, keys, getByKeyPath, setByKeyPath, extend, getProto } from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\nimport { Entity } from '../entity/Entity';\nimport { UpdateSpec } from '../../public';\nimport { cmp } from '../../functions/cmp';\n\n/** class Table\n * \n * https://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike | void,\n writeLocked?: boolean | string) : PromiseExtended\n {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n \n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db._novip === this.db._novip ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n * \n * https://dexie.org/docs/Table/Table.get()\n * \n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);\n\n return this._trans('readonly', (trans) => {\n return this.core.get({trans, key: keyOrCrit})\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n * \n * https://dexie.org/docs/Table/Table.where()\n * \n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => {\n if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[0];\n \n if (compoundIndex && this.db._maxKey !== maxString) {\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\n\n if (!compoundIndex && debug) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n\n function equals (a, b) {\n return idb.cmp(a,b) === 0; // Works with all indexable types including binary keys.\n }\n\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter\n combine(\n prevFilterFn,\n index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n * \n * https://dexie.org/docs/Table/Table.filter()\n * \n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n * \n * https://dexie.org/docs/Table/Table.count()\n * \n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n * \n * https://dexie.org/docs/Table/Table.offset()\n * \n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n * \n * https://dexie.org/docs/Table/Table.limit()\n * \n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n * \n * https://dexie.org/docs/Table/Table.each()\n * \n **/\n each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n * \n * https://dexie.org/docs/Table/Table.toArray()\n * \n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n * \n * https://dexie.org/docs/Table/Table.toCollection()\n * \n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n * \n * https://dexie.org/docs/Table/Table.orderBy()\n * \n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n\n /** Table.reverse()\n * \n * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://dexie.org/docs/Table/Table.mapToClass()\n * \n **/\n mapToClass(constructor: Function) {\n const {db, name: tableName} = this;\n this.schema.mappedClass = constructor;\n if (constructor.prototype instanceof Entity) {\n constructor = class extends (constructor as any) {\n get db () { return db; }\n table() { return tableName; }\n }\n }\n // Collect all inherited property names (including method names) by\n // walking the prototype chain. This is to avoid overwriting them from\n // database data - so application code can rely on inherited props never\n // becoming shadowed by database object props.\n const inheritedProps = new Set();\n for (let proto = constructor.prototype; proto; proto = getProto(proto)) {\n Object.getOwnPropertyNames(proto).forEach(propName => inheritedProps.add(propName));\n }\n \n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n const readHook = (obj: Object) => {\n if (!obj) return obj; // No valid object. (Value is null or undefined). Return as is.\n // Create a new object that derives from constructor:\n const res = Object.create(constructor.prototype);\n // Clone members (but never those that collide with a property in the prototype\n // hierchary (MUST BE ABLE TO RELY ON Entity methods and props!)):\n for (let m in obj) if (!inheritedProps.has(m)) try { res[m] = obj[m]; } catch (_) { }\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n }\n\n /** @deprecated */\n defineClass() {\n function Class (content){\n extend(this, content);\n };\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n * \n * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n /*// object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly. TODO: Document this change!\n if (!Object.isFrozen(keyOrObject)) try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }*/\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n\n /** Table.put()\n * \n * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://dexie.org/docs/Table/Table.delete()\n * \n **/\n delete(key: IndexableType): PromiseExtended {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'delete', keys: [key]}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.clear()\n * \n * https://dexie.org/docs/Table/Table.clear()\n * \n **/\n clear() {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.bulkGet()\n * \n * https://dexie.org/docs/Table/Table.bulkGet()\n * \n * @param keys \n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n * \n * https://dexie.org/docs/Table/Table.bulkAdd()\n * \n **/\n bulkAdd(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, wantResults}\n )\n .then(({numFailures, results,lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://dexie.org/docs/Table/Table.bulkPut()\n * \n **/\n bulkPut(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, wantResults}\n )\n .then(({numFailures, results, lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkUpdate()\n *\n * https://dexie.org/docs/Table.Table.bulkUpdate()\n */\n bulkUpdate(\n keysAndChanges: readonly { key: any; changes: UpdateSpec }[]\n ): PromiseExtended {\n const coreTable = this.core;\n const keys = keysAndChanges.map((entry) => entry.key);\n const changeSpecs = keysAndChanges.map((entry) => entry.changes);\n const offsetMap: number[] = [];\n return this._trans('readwrite', (trans) => {\n return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => {\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keysAndChanges.forEach(({ key, changes }, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const keyPath of Object.keys(changes)) {\n const value = changes[keyPath];\n if (keyPath === this.schema.primKey.keyPath) {\n if (cmp(value, key) !== 0) {\n throw new exceptions.Constraint(\n `Cannot update primary key in bulkUpdate()`\n );\n }\n } else {\n setByKeyPath(obj, keyPath, value);\n }\n }\n offsetMap.push(idx);\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n const numEntries = resultKeys.length;\n return coreTable\n .mutate({\n trans,\n type: 'put',\n keys: resultKeys,\n values: resultObjs,\n updates: {\n keys,\n changeSpecs\n }\n })\n .then(({ numFailures, failures }) => {\n if (numFailures === 0) return numEntries;\n // Failure. bulkPut() may have a subset of keys\n // so we must translate returned 'failutes' into the offsets of given argument:\n for (const offset of Object.keys(failures)) {\n const mappedOffset = offsetMap[Number(offset)];\n if (mappedOffset != null) {\n const failure = failures[offset];\n delete failures[offset];\n failures[mappedOffset] = failure;\n }\n }\n throw new BulkError(\n `${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`,\n failures\n );\n });\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://dexie.org/docs/Table/Table.bulkDelete()\n * \n **/\n bulkDelete(keys: ReadonlyArray): PromiseExtended {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});\n }).then(({numFailures, lastResult, failures}) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n","import {keys, isArray, asap} from '../functions/utils';\nimport {nop, mirror, reverseStoppableEventChain} from '../functions/chaining-functions';\nimport {exceptions} from '../errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","import { arrayToObject, derive } from './utils';\n\n\nexport function makeClassConstructor (prototype: Object, constructor: Function) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({prototype});\n return constructor as any as TConstructor; \n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport { hookCreatingChain, pureFunctionChain, nop, mirror, hookUpdatingChain, hookDeletingChain } from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (name: string, tableSchema: TableSchema, optionalTrans?: Transaction) : Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor (db: Dexie) {\n return makeClassConstructor(\n Table.prototype,\n\n function Table (this: Table, name: string, tableSchema: TableSchema, trans?: Transaction) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n }) as TableHooks;\n }\n\n );\n}\n","import { combine } from \"../../functions/combine\";\nimport { exceptions } from \"../../errors\";\nimport { hasOwn } from \"../../functions/utils\";\nimport { wrap } from \"../../helpers/promise\";\nimport { Collection } from './';\nimport { DBCoreCursor, DBCoreTable, DBCoreTransaction, DBCoreTableSchema, DBCoreRangeType } from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection[\"_ctx\"];\n\nexport function isPlainKeyRange (ctx: CollectionContext, ignoreLimitFilter?: boolean) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n} \n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter (ctx: CollectionContext, factory, isLimitFilter?) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(ctx: CollectionContext, coreSchema: DBCoreTableSchema) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\n\nexport function openCursor(ctx: CollectionContext, coreTable: DBCoreTable, trans: DBCoreTransaction) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index, \n range: ctx.range\n }\n });\n}\n\nexport function iter (\n ctx: CollectionContext, \n fn: (item, cursor: DBCoreCursor, advance: Function)=>void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable): Promise\n{\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (!filter || filter(cursor, advance, result=>cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\n\nfunction iterate(cursorPromise: Promise, filter, fn, valueMapper): Promise {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n \n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(()=>{\n var c = ()=>cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val=>{cursor.stop(val);c=nop}, e => {cursor.fail(e);c = nop;}))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n","import { Collection as ICollection } from \"../../public/types/collection\";\nimport { Dexie } from \"../dexie\";\nimport { Table } from \"../table\";\nimport { IndexableType, IndexableTypeArrayReadonly } from \"../../public/types/indexable-type\";\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { iter, isPlainKeyRange, getIndexOrStore, addReplayFilter, addFilter, addMatchFilter } from \"./collection-helpers\";\nimport { rejection } from \"../../helpers/promise\";\nimport { combine } from \"../../functions/combine\";\nimport { extend, hasOwn, deepClone, keys, setByKeyPath, getByKeyPath } from \"../../functions/utils\";\nimport { ModifyError } from \"../../errors\";\nimport { hangsOnDeleteLargeKeyRange } from \"../../globals/constants\";\nimport { ThenShortcut } from \"../../public/types/then-shortcut\";\nimport { Transaction } from '../transaction';\nimport { DBCoreCursor, DBCoreTransaction, DBCoreRangeType, DBCoreMutateResponse, DBCoreKeyRange } from '../../public/types/dbcore';\nimport { cmp } from \"../../functions/cmp\";\n\n/** class Collection\n * \n * https://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: \"next\" | \"prev\";\n unique: \"\" | \"unique\";\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number,\n limit: number,\n error: any, // If set, any promise must be rejected with this error\n or: Collection,\n valueMapper: (any) => any\n }\n \n _ondirectionchange?: Function;\n\n _read(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike, cb?): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction) : Promise\n {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n * \n * https://dexie.org/docs/Collection/Collection.clone()\n * \n **/\n clone(props?) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n\n /** Collection.raw()\n * \n * https://dexie.org/docs/Collection/Collection.raw()\n * \n **/\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n * \n * https://dexie.org/docs/Collection/Collection.each()\n * \n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended {\n var ctx = this._ctx;\n\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n * \n * https://dexie.org/docs/Collection/Collection.count()\n * \n **/\n count(cb?) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(()=>count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n * \n * https://dexie.org/docs/Collection/Collection.sortBy()\n * \n **/\n sortBy(keyPath: string): PromiseExtended;\n sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended;\n sortBy(keyPath: string, cb?: ThenShortcut) {\n const parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n }\n\n /** Collection.toArray()\n * \n * https://dexie.org/docs/Collection/Collection.toArray()\n * \n **/\n toArray(cb?): PromiseExtended {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n const {valueMapper} = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({result}) => valueMapper ? result.map(valueMapper) : result);\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(()=>a);\n }\n }, cb);\n }\n\n /** Collection.offset()\n * \n * https://dexie.org/docs/Collection/Collection.offset()\n * \n **/\n offset(offset: number) : Collection{\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n\n /** Collection.limit()\n * \n * https://dexie.org/docs/Collection/Collection.limit()\n * \n **/\n limit(numRows: number) : Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n }\n\n /** Collection.until()\n * \n * https://dexie.org/docs/Collection/Collection.until()\n * \n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n }\n\n /** Collection.first()\n * \n * https://dexie.org/docs/Collection/Collection.first()\n * \n **/\n first(cb?) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.last()\n * \n * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://dexie.org/docs/Collection/Collection.filter()\n * \n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n\n /** Collection.and()\n * \n * https://dexie.org/docs/Collection/Collection.and()\n * \n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n * \n * https://dexie.org/docs/Collection/Collection.or()\n * \n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n * \n * https://dexie.org/docs/Collection/Collection.reverse()\n * \n **/\n reverse() {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n }\n\n /** Collection.desc()\n * \n * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachKey()\n * \n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n\n /** Collection.eachUniqueKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachUniqueKey()\n * \n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n * \n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n\n /** Collection.keys()\n * \n * https://dexie.org/docs/Collection/Collection.keys()\n * \n **/\n keys(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.primaryKeys()\n * \n * https://dexie.org/docs/Collection/Collection.primaryKeys()\n * \n **/\n primaryKeys(cb?) : PromiseExtended {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }});\n }).then(({result})=>result).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.uniqueKeys()\n * \n * https://dexie.org/docs/Collection/Collection.uniqueKeys()\n * \n **/\n uniqueKeys(cb?) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n * \n * https://dexie.org/docs/Collection/Collection.firstKey()\n * \n **/\n firstKey(cb?) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.lastKey()\n * \n * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://dexie.org/docs/Collection/Collection.distinct()\n * \n **/\n distinct() {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor: DBCoreCursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n\n //\n // Methods that mutate storage\n //\n\n /** Collection.modify()\n * \n * https://dexie.org/docs/Collection/Collection.modify()\n * \n **/\n modify(changes: { [keyPath: string]: any }) : PromiseExtended\n modify(changes: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean): PromiseExtended {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n modifyer = changes;\n } else {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n\n const coreTable = ctx.table.core;\n const {outbound, extractKey} = coreTable.schema.primaryKey;\n const limit = this.db._options.modifyChunkSize || 200;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (expectedCount: number, res: DBCoreMutateResponse) => {\n const {failures, numFailures} = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n }\n return this.clone().primaryKeys().then(keys => {\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i=0; i 0 &&\n coreTable.mutate({trans, type: 'add', values: addValues})\n .then(res => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n ).then(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\n }).then(res=>applyMutateResult(deleteKeys.length, res))\n ).then(()=>{\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n }\n\n return nextChunk(0).then(()=>{\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys as IndexableTypeArrayReadonly);\n\n return keys.length;\n });\n });\n\n });\n }\n\n /** Collection.delete()\n * \n * https://dexie.org/docs/Collection/Collection.delete()\n * \n **/\n delete() : PromiseExtended {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === DBCoreRangeType.Any)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write(trans => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const {primaryKey} = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({trans, query: {index: primaryKey, range: coreRange}}).then(count => {\n return ctx.table.core.mutate({trans, type: 'deleteRange', range: coreRange})\n .then(({failures, lastResult, results, numFailures}) => {\n if (numFailures) throw new ModifyError(\"Could not delete some values\",\n Object.keys(failures).map(pos => failures[pos]),\n count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new(whereClause?: WhereClause | null, keyRangeGenerator?: () => DBCoreKeyRange): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange)\n {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport { simpleCompare, simpleCompareReverse } from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(collectionOrWhereClause: Collection | WhereClause, err, T?) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection (whereClause, () => rangeEqual(\"\")).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toUpperCase() :\n (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toLowerCase() :\n (s: string) => s.toUpperCase();\n}\n\nexport function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n}\n\nexport function addIgnoreCaseAlgorithm(whereClause: WhereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new whereClause.Collection (\n whereClause,\n ()=>createRange(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix)\n );\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange (lower: IndexableType, upper: IndexableType, lowerOpen?: boolean, upperOpen?: boolean): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\n\nexport function rangeEqual (value: IndexableType) : DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value\n };\n}\n","import { WhereClause as IWhereClause } from \"../../public/types/where-clause\";\nimport { Collection } from \"../collection\";\nimport { Table } from \"../table\";\nimport { IndexableType } from \"../../public/types/indexable-type\";\nimport { emptyCollection, fail, addIgnoreCaseAlgorithm, createRange, rangeEqual } from './where-clause-helpers';\nimport { INVALID_KEY_ARGUMENT, STRING_EXPECTED, maxString, minKey } from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection} from \"../../public/types/collection\";\n\n/** class WhereClause\n * \n * https://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n }\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.between()\n * \n **/\n between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this.Collection(this, ()=>createRange(lower, upper, !includeLower, !includeUpper));\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.above()\n * \n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n * \n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n\n /** WhereClause.below()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.below()\n * \n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n\n /** WhereClause.belowOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n * \n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWith()\n * \n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n * \n **/\n startsWithIgnoreCase(str: string) {\n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n\n /** WhereClause.equalsIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n * \n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n\n /** WhereClause.anyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n * \n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n * \n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n\n /** WhereClause.anyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOf()\n * \n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.notEqual()\n * \n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.noneOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.noneOf()\n * \n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try { set.sort(this._ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]],\n null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.inAnyRange()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n * \n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType, 1: IndexableType }>,\n options?: { includeLowers?: boolean, includeUppers?: boolean })\n {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(range =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(\n this,\n \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\",\n exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n\n // Join overlapping ranges\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(\n this,\n () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n\n c._ondirectionchange = direction => {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n * \n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(s => typeof s === 'string')) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map((str: string) => [str, str + maxString]));\n }\n\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\nimport { cmp } from '../../functions/cmp';\n\nexport interface WhereClauseConstructor {\n new(table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor(\n WhereClause.prototype,\n\n function WhereClause(this: WhereClause, table: Table, index?: string, orCollection?: Collection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n this._cmp = this._ascending = cmp;\n this._descending = (a, b) => cmp(b, a);\n this._max = (a, b) => cmp(a,b) > 0 ? a : b;\n this._min = (a, b) => cmp(a,b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n if (!this._IDBKeyRange) throw new exceptions.MissingAPI();\n }\n );\n}\n","import { wrap } from \"../helpers/promise\";\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nexport function hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nexport function hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\n\nexport function preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n}\n\n","import Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from \"../../helpers/promise\";\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\n idbtrans: IDBTransaction;\n storeNames: string[];\n explicit?: boolean;\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: {[tableName: string]: Table};\n\n _reculock: number;\n _blockedFuncs: { 0: () => any, 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _lock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n }\n\n /** Transaction._unlock()\n * \n * Internal method.\n */\n _unlock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _locked() {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n\n /** Transaction.create()\n * \n * Internal method.\n * \n */\n create(idbtrans?: IDBTransaction & {[prop: string]: any}) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n }\n\n /** Transaction._promise()\n * \n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike | void,\n bWriteLock?: string | boolean): DexiePromise\n {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n * \n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n * \n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): https://dexie.org/docs/Dexie/Dexie.waitFor()\n * \n **/\n waitFor(promiseLike: PromiseLike) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n } \n\n /** Transaction.abort()\n * \n * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\"); \n }\n\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction) : T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor>(\n Transaction.prototype,\n function Transaction (\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n \n });\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n }\n}\n\nexport function nameFromKeyPath (keyPath?: string | string[]): string {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { createIndexSpec } from './index-spec';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema (\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n}\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor (keyPath: null | string | string[]) : (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { eventRejectHandler, preventDefault } from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\n\nexport function arrayify(arrayLike: {length: number, [index: number]: T}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick(obj: T, props: Prop[]): Pick {\n const result = {} as Pick;\n props.forEach(prop => result[prop] = obj[prop]);\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore (\n db: IDBDatabase,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\n{\n function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const {keyPath, autoIncrement} = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const {name, unique, multiEntry, keyPath} = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579\n };\n }\n\n function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never) throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const {lower, upper, lowerOpen, upperOpen} = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n IdbKeyRange.upperBound(upper, !!upperOpen) : // below\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate ({trans, type, keys, values, range}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error (\"Invalid operation type: \" + type);\n\n const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});\n\n let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\n };\n \n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({numFailures, failures, results: [], lastResult: undefined}); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n\n if (isAddOrPut) {\n for (let i=0; i {\n const lastResult = event.target.result;\n reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\n lastResult\n });\n };\n \n req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n \n req.onsuccess = done;\n });\n }\n \n function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise\n {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n // direction\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n // request\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n \n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = ()=>{throw new Error(\"Cursor not started\");}\n const doThrowCursorIsStopped = ()=>{throw new Error(\"Cursor not stopped\");}\n (cursor as any).trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise((resolveIteration, rejectIteration) =>{\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = ()=>{throw new Error(\"Cursor behind last entry\");}\n cursor.stop();\n }\n }\n req.onsuccess = wrap(ev => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject); \n });\n }\n \n function query (hasGetAll: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {trans, values, limit, query} = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({result: []});\n if (hasGetAll) {\n const req = values ?\n (source as any).getAll(idbKeyRange, nonInfinitLimit) :\n (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({result: event.target.result});\n req.onerror = eventRejectHandler(reject);\n } else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange)\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({result});\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({result});\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n \n return {\n name: tableName,\n schema: tableSchema,\n \n mutate,\n\n getMany ({trans, keys}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & {_pos?: number};\n \n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n \n for (let i=0; i((resolve, reject) => {\n resolve = wrap (resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll),\n \n openCursor,\n\n count ({query, trans}) {\n const {index, range} = query;\n return new Promise((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n\n const {schema, hasGetAll} = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap: {[name: string]: DBCoreTable} = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n \n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema\n\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack(\n stackImpl: {stack: string},\n middlewares: Middleware<{stack: string}>[]): TStack {\n return middlewares.reduce((down, {create}) => ({...down, ...create(down)}), stackImpl) as TStack;\n} \n\nfunction createMiddlewareStacks(\n middlewares: {[StackName in keyof DexieStacks]?: Middleware[]},\n idbdb: IDBDatabase,\n {IDBKeyRange, indexedDB}: DexieDOMDependencies,\n tmpTrans: IDBTransaction): {[StackName in keyof DexieStacks]?: DexieStacks[StackName]}\n{\n const dbcore = createMiddlewareStack(\n createDBCore(idbdb, IDBKeyRange, tmpTrans),\n middlewares.dbcore);\n \n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore!;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, { PSD, newScope, NativePromise, decrementExpectedAwaits, incrementExpectedAwaits } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { hasIEDeleteObjectStoreBug, isIEOrEdge } from '../../globals/constants';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\n\nexport function setApiOnPlace(db: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) { return this.table(tableName); },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {value, writable: true, configurable: true, enumerable: true});\n }\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(db: Dexie, oldVersion: number, idbUpgradeTrans: IDBTransaction, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\n\nexport type UpgradeQueueItem = (idbtrans: IDBTransaction) => PromiseLike | void;\n\nexport function updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction)\n{\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(idx => addIndex(store, idx));\n // Update indexes\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n \n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n Promise.resolve(returnValue) : promiseFollowed.then(()=>returnValue));\n }\n });\n queue.push(idbtrans => {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[],\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string,\n recreate: boolean,\n del: string[],\n add: IndexSpec[],\n change: IndexSpec[]\n}\n\nexport function getSchemaDiff(oldSchema: DbSchema, newSchema: DbSchema): SchemaDiff {\n const diff: SchemaDiff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) // IE has bug reading autoIncrement prop.\n {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\n\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto }\n );\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\n\nexport function deleteRemovedTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\n}\n\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || \"\",\n false,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== \"string\",\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== \"string\",\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(db: Dexie, idbdb: IDBDatabase, tmpTrans: IDBTransaction) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames(db: Dexie, schema: DbSchema, idbtrans: IDBTransaction) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport { removeTablesApi, setApiOnPlace, parseIndexSyntax } from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number,\n storesSource: { [tableName: string]: string | null },\n dbschema: DbSchema,\n tables: {},\n contentUpgrade: Function | null\n }\n\n _parseStoresSpec(stores: { [tableName: string]: string | null }, outSchema: DbSchema): any {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(idx => {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n\n stores(stores: { [key: string]: string | null; }): IVersion {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string; } = {};\n let dbschema = {};\n versions.forEach(version => { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(upgradeFunction: (trans: Transaction) => PromiseLike | void): Version {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new(versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n\n}\n","import { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n infos\n // Select name prop of infos:\n .map((info) => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter((name) => name !== DBNAMES_DB)\n )\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n}\n\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { cloneSimpleObjectTree, deepClone, keys, objectIsEmpty } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n if (target[part]) mergeRanges(target[part], newSet[part]);\n else target[part] = cloneSimpleObjectTree(newSet[part]); // Somewhat faster\n });\n return target;\n}\n","import { rangesOverlap } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\n\nexport function obsSetsOverlap(os1: ObservabilitySet, os2: ObservabilitySet) {\n return Object.keys(os1).some(\n (key) => os2[key] && rangesOverlap(os2[key], os1[key])\n );\n}\n","import { type GlobalQueryCache } from \"../../public/types/cache\";\n\nexport const cache: GlobalQueryCache = {}\n","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport { extendObservabilitySet } from '../extend-observability-set';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { cache } from './cache';\n\nlet unsignaledParts: ObservabilitySet = {};\nlet isTaskEnqueued = false;\n\nexport function signalSubscribersLazily(part: ObservabilitySet) {\n extendObservabilitySet(unsignaledParts, part);\n if (!isTaskEnqueued) {\n isTaskEnqueued = true;\n setTimeout(() => {\n isTaskEnqueued = false;\n const parts = unsignaledParts;\n unsignaledParts = {};\n signalSubscribersNow(parts);\n }, 0);\n }\n}\n\nexport function signalSubscribersNow(\n updatedParts: ObservabilitySet,\n deleteAffectedCacheEntries = false\n) {\n const queriesToSignal = new Set<() => void>();\n for (const key in updatedParts) {\n const parts = /^idb\\:\\/\\/(.*)\\/(.*)\\//.exec(key);\n if (parts) {\n const [, dbName, tableName] = parts;\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (tblCache)\n signalTableSubscribersNow(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n }\n // Now when affected cache entries are removed, signal collected subscribers to requery.\n queriesToSignal.forEach((requery) => requery());\n}\n\nfunction signalTableSubscribersNow(\n tblCache: TblQueryCache,\n updatedParts: ObservabilitySet,\n outQueriesToSignal: Set<() => void>,\n deleteAffectedCacheEntries: boolean\n) {\n const updatedEntryLists: [string, CacheEntry[]][] =\n deleteAffectedCacheEntries && [];\n for (const [indexName, entries] of Object.entries(tblCache.queries.query)) {\n const filteredEntries: CacheEntry[] = deleteAffectedCacheEntries && [];\n for (const entry of entries) {\n if (entry.obsSet && obsSetsOverlap(updatedParts, entry.obsSet)) {\n // This query is affected by the mutation. Remove it from cache\n // and signal all subscribers to requery.\n entry.subscribers.forEach((requery) => outQueriesToSignal.add(requery));\n } else if (deleteAffectedCacheEntries) {\n filteredEntries.push(entry);\n }\n }\n // Collect cache entries to be updated\n if (deleteAffectedCacheEntries)\n updatedEntryLists.push([indexName, filteredEntries]);\n }\n if (deleteAffectedCacheEntries) {\n for (const [indexName, filteredEntries] of updatedEntryLists) {\n tblCache.queries.query[indexName] = filteredEntries;\n }\n }\n}\n","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { eventRejectHandler, preventDefault } from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/constants';\nimport { runUpgraders, readGlobalSchema, adjustToExistingIndexNames, verifyInstalledSchema } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\nimport safari14Workaround from 'safari-14-idb-fix';\nimport { type ObservabilitySet } from '../../public/types/db-events';\nimport { RangeSet } from '../../helpers/rangeset';\nimport { DEXIE_STORAGE_MUTATED_EVENT_NAME, globalEvents } from '../../globals/global-events';\nimport { signalSubscribersNow } from '../../live-query/cache/signalSubscribers';\n\nexport function dexieOpen (db: Dexie) {\n const state = db._state;\n const {indexedDB} = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection (state.dbOpenError) :\n db);\n Debug.debug && (state.openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n \n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: (IDBTransaction | null) = null,\n wasCreated = false;\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([openCanceller, (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(() => new Promise((resolve, reject) => {\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n \n throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\n const dbName = db.name;\n \n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap (e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n wasCreated = oldVer < 1;\n db.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n \n req.onsuccess = wrap (() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = db.idbdb = req.result;\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0) try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n \n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n \n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }))]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>remainders(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n if (state.openCanceller === openCanceller) {\n // Only modify state if not cancelled in the mean time.\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\n }).finally(()=>{\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n }).then(()=>{\n if (wasCreated) {\n // Propagate full range on primary keys and indexes on all tables now that the DB is ready and opened,\n // and all upgraders and on('ready') subscribers have run.\n const everything: ObservabilitySet = {};\n db.tables.forEach(table => {\n table.schema.indexes.forEach(idx => {\n if (idx.name) everything[`idb://${db.name}/${table.name}/${idx.name}`] = new RangeSet(-Infinity, [[[]]]);\n });\n everything[`idb://${db.name}/${table.name}/`] = everything[`idb://${db.name}/${table.name}/:dels`] = new RangeSet(-Infinity, [[[]]]);\n });\n // Database was created. If another tab had it open when it was deleted and reopened, that tab must be updated now.\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything);\n // Wipe the cache and trigger optimistic queries:\n signalSubscribersNow(everything, true);\n }\n // Resolve the db.open() with the db instance.\n return db;\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator (iterator: Iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any)=>any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { errnames, exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(mode: TransactionMode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: ()=>PromiseLike | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n trans.explicit = true;\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\n }\n\n // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(() => returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n }).catch(e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n}\n","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n\n /** LowLevelIndex represents the actual IndexedDB index behind it */\n lowLevelIndex: DBCoreIndex;\n}\n\n// Move into some util:\nexport function pad (a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i=0; i 0;\n const virtualIndex = {\n ...lowLevelIndex,\n name: isVirtual\n ? `${keyPathAlias}(virtual-from:${lowLevelIndex.name})`\n : lowLevelIndex.name,\n lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] : // This is a compound [a, b]. Add a virtual normal index a.\n keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a,b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n \n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n \n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n \n function translateRange (range: DBCoreKeyRange, keyTail: number): DBCoreKeyRange {\n return {\n type: range.type === DBCoreRangeType.Equal ?\n DBCoreRangeType.Range :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true // doesn't matter true or false\n };\n }\n \n function translateRequest (req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest (req: DBCoreOpenCursorRequest): DBCoreOpenCursorRequest;\n function translateRequest (req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual ? {\n ...req,\n query: {\n index: index.lowLevelIndex,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n \n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n\n count(req) {\n return table.count(translateRequest(req));\n }, \n \n query(req) {\n return table.query(translateRequest(req));\n },\n \n openCursor(req) {\n const {keyTail, isVirtual, keyLength} = (req.query.index as VirtualIndex);\n if (!isVirtual) return table.openCursor(req);\n \n function createVirtualCursor(cursor: DBCoreCursor) : DBCoreCursor {\n function _continue (key?: any) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\n cursor.continue()\n }\n const virtualCursor = Object.create(cursor, {\n continue: {value: _continue},\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n }\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1 ?\n key[0] : // Cursor.key should not be an array.\n key.slice(0, keyLength); // Cursor.key should be first part of array.\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n \n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n }\n}\n\nexport const virtualIndexMiddleware : Middleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\n","import { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from \"../public/types/dbcore\";\n\nexport function getEffectiveKeys (\n primaryKey: DBCoreIndex,\n req: (Pick & {keys?: any[]}) | Pick)\n{\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey)\n}\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange\n} from \"../public/types/dbcore\";\nimport { nop } from '../functions/chaining-functions';\nimport { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore: DBCore) => ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const {primaryKey} = downTable.schema;\n \n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req):Promise {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const {deleting, creating, updating} = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>deleteRange(req), true);\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n\n function addPutOrDelete(req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest): Promise {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error(\"Keys missing\");\n // Clone Request and set keys arg\n req = req.type === 'add' || req.type === 'put' ?\n {...req, keys} :\n {...req};\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n \n return getExistingValues(downTable, req, keys).then (existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (req.type === 'add' || existingValue === undefined) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({failures, results, numFailures, lastResult}) => {\n for (let i=0; i {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n \n function deleteRange(req: DBCoreDeleteRangeRequest): Promise {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n \n function deleteNextChunk(trans: DBCoreTransaction, range: DBCoreKeyRange, limit: number) {\n // Query what keys in the DB within the given range\n return downTable.query({trans, values: false, query: {index: primaryKey, range}, limit})\n .then(({result}) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({type: 'delete', keys: result, trans}).then(res => {\n if (res.numFailures > 0) return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {failures: [], numFailures: 0, lastResult: undefined} as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(trans, {...range, lower: result[result.length - 1], lowerOpen: true}, limit);\n }\n });\n })\n }\n }\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore\n};\n\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: readonly any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { DBCore, DBCoreTable } from '../../public/types/dbcore';\nimport { LiveQueryContext } from '../live-query';\n\nexport function isCachableContext(ctx: LiveQueryContext, table: DBCoreTable) {\n return (\n ctx.trans.mode === 'readonly' &&\n !!ctx.subscr &&\n !ctx.trans.explicit &&\n ctx.trans.db._options.cache !== 'disabled' &&\n !table.schema.primaryKey.outbound\n );\n}\n\n","import { DBCoreCountRequest, DBCoreGetManyRequest, DBCoreGetRequest, DBCoreOpenCursorRequest, DBCoreQueryRequest } from '../../public/types/dbcore';\n\n\nexport function isCachableRequest(type: string, req: Partial) {\n switch (type) {\n case 'query':\n return req.values && !req.unique;\n case 'get':\n return false;\n case 'getMany':\n return false;\n case 'count':\n return false;\n case 'openCursor':\n return false;\n }\n}\n","import { LiveQueryContext } from \".\";\nimport { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { getEffectiveKeys } from \"../dbcore/get-effective-keys\";\nimport { exceptions } from \"../errors\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport { isCachableContext } from \"./cache/is-cachable-context\";\nimport { isCachableRequest } from \"./cache/is-cachable-request\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n name: \"Observability\",\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n transaction: (stores, mode, options) => {\n if (PSD.subscr && mode !== 'readonly') {\n throw new exceptions.ReadOnly(`Readwrite transaction in liveQuery context. Querier source: ${(PSD as LiveQueryContext).querier}`);\n }\n return core.transaction(stores, mode, options);\n },\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts = req.mutatedParts || (req.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [getEffectiveKeys(primaryKey, req).filter(id => id), req.values] // keys except autoIncremented - they will be added later on.\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n\n const oldCache = req.trans[\"_cache\"];\n\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n // Individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null;\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs && type !== \"add\") {\n // delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // keys is a DBCoreKeyRange object. Transform it to [from,to]-style range.\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n\n return table.mutate(req).then((res) => {\n // Merge the mutated parts from the request into the transaction's mutatedParts\n // now when the request went fine.\n if (keys && (req.type === 'add' || req.type === 'put')) {\n // Less than 50 requests (keys truthy) (otherwise we've added full range anyway)\n // autoincrement means we might not have got all keys until now\n pkRangeSet.addKeys(res.results);\n }\n trans.mutatedParts = extendObservabilitySet (\n trans.mutatedParts || {},\n mutatedParts\n );\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD as LiveQueryContext;\n const isLiveQuery = !!subscr;\n let cachable = isCachableContext(PSD as LiveQueryContext, table) && isCachableRequest(method, req);\n const obsSet = cachable\n ? req.obsSet = {} // Implicit read transaction - track changes for this query only for the request's duration\n : subscr; // Explicit read transaction - track changes across entire live query\n\n if (isLiveQuery) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (obsSet[part] ||\n (obsSet[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: readonly any[] | undefined,\n newObjs: readonly any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n","import { cmp } from '../../functions/cmp';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function isAboveLower(key: IndexableType, range: DBCoreKeyRange) {\n return range.lower === undefined\n ? true // lower is less than anything because it is undefined\n : range.lowerOpen\n ? cmp(key, range.lower) > 0 // lowerOpen: Exclude lower bound\n : cmp(key, range.lower) >= 0; // !lowerOpen: Include lower bound\n}\n\nexport function isBelowUpper(key: IndexableType, range: DBCoreKeyRange) {\n return range.upper === undefined\n ? true // upper is greater than anything because it is undefined\n : range.upperOpen\n ? cmp(key, range.upper) < 0 // upperOpen: Exclude upper bound\n : cmp(key, range.upper) <= 0; // !upperOpen: Include upper bound\n}\n\nexport function isWithinRange(key: IndexableType, range: DBCoreKeyRange) {\n return isAboveLower(key, range) && isBelowUpper(key, range);\n}\n","import { cmp } from '../../functions/cmp';\nimport { deepClone } from '../../functions/utils';\nimport { RangeSet, rangesOverlap } from '../../helpers/rangeset';\nimport { CacheEntry } from '../../public/types/cache';\nimport {\n DBCoreIndex,\n DBCoreMutateRequest,\n DBCoreQueryRequest,\n DBCoreTable,\n} from '../../public/types/dbcore';\nimport { isWithinRange } from './is-within-range';\n\nexport function applyOptimisticOps(\n result: any[],\n req: DBCoreQueryRequest,\n ops: DBCoreMutateRequest[] | undefined,\n table: DBCoreTable,\n cacheEntry: CacheEntry,\n immutable: boolean\n): any[] {\n if (!ops || ops.length === 0) return result;\n const index = req.query.index;\n const primaryKey = table.schema.primaryKey;\n const extractPrimKey = primaryKey.extractKey;\n const extractIndex = index.extractKey;\n const extractLowLevelIndex = (index.lowLevelIndex || index).extractKey;\n\n let finalResult = ops.reduce((result, op) => {\n let modifedResult = result;\n const includedValues =\n op.type === 'add' || op.type === 'put'\n ? op.values.filter((v) =>\n isWithinRange(extractIndex(v), req.query.range)\n ).map(v => {\n v = deepClone(v);// v might come from user so we can't just freeze it.\n if (immutable) Object.freeze(v);\n return v;\n }) \n : [];\n switch (op.type) {\n case 'add':\n modifedResult = result.concat(\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n case 'put':\n const keySet = new RangeSet().addKeys(\n op.values.map((v) => extractPrimKey(v))\n );\n modifedResult = result\n .filter((item) => {\n const key = req.values ? extractPrimKey(item) : item;\n return !rangesOverlap(new RangeSet(key), keySet);\n })\n .concat(\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n case 'delete':\n const keysToDelete = new RangeSet().addKeys(op.keys);\n modifedResult = result.filter((item) => {\n const key = req.values ? extractPrimKey(item) : item;\n return !rangesOverlap(new RangeSet(key), keysToDelete);\n });\n\n break;\n case 'deleteRange':\n const range = op.range;\n modifedResult = result.filter((item) => !isWithinRange(extractPrimKey(item), range));\n break;\n }\n return modifedResult;\n }, result);\n\n // If no changes were made, we can return the original result.\n if (finalResult === result) return result;\n\n // Sort the result on sortIndex:\n finalResult.sort((a, b) =>\n cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) ||\n cmp(extractPrimKey(a), extractPrimKey(b))\n );\n\n // If we have a limit we need to respect it:\n if (req.limit && req.limit < Infinity) {\n if (finalResult.length > req.limit) {\n finalResult.length = req.limit; // Cut of any extras after sorting correctly.\n } else if (result.length === req.limit && finalResult.length < req.limit) {\n // We're missing some items because of the limit. We need to add them back.\n // The easiest way is to mark the cache entry as dirty, which will cause\n // it to be requeried after the write-transaction successfully completes.\n cacheEntry.dirty = true;\n }\n }\n return immutable ? Object.freeze(finalResult) as any[] : finalResult;\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function areRangesEqual(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n cmp(r1.lower, r2.lower) === 0 &&\n cmp(r1.upper, r2.upper) === 0 &&\n !!r1.lowerOpen === !!r2.lowerOpen &&\n !!r1.upperOpen === !!r2.upperOpen\n );\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function compareLowers(lower1: any, lower2: any, lowerOpen1: boolean, lowerOpen2: boolean) {\n if (lower1 === undefined) return lower2 !== undefined ? -1 : 0;\n if (lower2 === undefined) return 1; // since lower1 !== undefined\n const c = cmp(lower1, lower2);\n if (c === 0) {\n if (lowerOpen1 && lowerOpen2) return 0;\n if (lowerOpen1) return 1\n if (lowerOpen2) return -1;\n }\n return c;\n}\n\nexport function compareUppers(upper1: any, upper2: any, upperOpen1: boolean, upperOpen2: boolean) {\n if (upper1 === undefined) return upper2 !== undefined ? 1 : 0;\n if (upper2 === undefined) return -1; // since upper1 !== undefined\n const c = cmp(upper1, upper2);\n if (c === 0) {\n if (upperOpen1 && upperOpen2) return 0;\n if (upperOpen1) return -1\n if (upperOpen2) return 1;\n }\n return c;\n}\n\nexport function isSuperRange(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 &&\n compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0\n );\n}","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreCountRequest,\n DBCoreQueryRequest,\n} from '../../public/types/dbcore';\nimport { areRangesEqual } from './are-ranges-equal';\nimport { cache } from './cache';\nimport { isSuperRange } from './is-super-range';\n\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query',\n req: DBCoreQueryRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'count',\n req: DBCoreCountRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query' | 'count',\n req: Partial & Partial\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]] {\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return [];\n const queries = tblCache.queries[type];\n if (!queries) return [null, false, tblCache, null];\n const indexName = req.query ? req.query.index.name : null;\n const entries = queries[indexName || ''];\n if (!entries) return [null, false, tblCache, null];\n\n switch (type) {\n case 'query':\n const equalEntry = entries.find(\n (entry) =>\n (entry.req as DBCoreQueryRequest).limit === req.limit &&\n (entry.req as DBCoreQueryRequest).values === req.values &&\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n if (equalEntry)\n return [\n equalEntry,\n true, // exact match\n tblCache,\n entries,\n ];\n const superEntry = entries.find((entry) => {\n const limit = 'limit' in entry.req ? entry.req.limit : Infinity;\n return (\n limit >= req.limit &&\n (req.values ? (entry.req as DBCoreQueryRequest).values : true) &&\n isSuperRange(entry.req.query.range, req.query.range)\n );\n });\n return [superEntry, false, tblCache, entries];\n case 'count':\n const countQuery = entries.find((entry) =>\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n return [countQuery, !!countQuery, tblCache, entries];\n }\n}\n","import { delArrayItem } from \"../../functions/utils\";\nimport { CacheEntry } from \"../../public/types/cache\";\n\nexport function subscribeToCacheEntry(cacheEntry: CacheEntry, container: CacheEntry[], requery: ()=>void, signal: AbortSignal) {\n cacheEntry.subscribers.add(requery);\n signal.addEventListener(\"abort\", () => {\n cacheEntry.subscribers.delete(requery);\n if (cacheEntry.subscribers.size === 0) {\n enqueForDeletion(cacheEntry, container);\n }\n });\n}\n\n\nfunction enqueForDeletion(cacheEntry: CacheEntry, container: CacheEntry[]) {\n setTimeout(() => {\n if (cacheEntry.subscribers.size === 0) { // Still empty (no new subscribers readded after grace time)\n delArrayItem(container, cacheEntry);\n }\n }, 3000);\n}\n","import { LiveQueryContext } from '..';\nimport { getEffectiveKeys } from '../../dbcore/get-effective-keys';\nimport { deepClone, delArrayItem, setByKeyPath } from '../../functions/utils';\nimport DexiePromise, { PSD } from '../../helpers/promise';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport {\n DBCore, DBCoreQueryRequest,\n DBCoreQueryResponse\n} from '../../public/types/dbcore';\nimport { Middleware } from '../../public/types/middleware';\nimport { applyOptimisticOps } from './apply-optimistic-ops';\nimport { cache } from './cache';\nimport { findCompatibleQuery } from './find-compatible-query';\nimport { isCachableContext } from './is-cachable-context';\nimport { isCachableRequest } from './is-cachable-request';\nimport { signalSubscribersLazily } from './signalSubscribers';\nimport { subscribeToCacheEntry } from './subscribe-cachentry';\n\nexport const cacheMiddleware: Middleware = {\n stack: 'dbcore',\n level: 0,\n name: 'Cache',\n create: (core) => {\n const dbName = core.schema.name;\n const coreMW: DBCore = {\n ...core,\n transaction: (stores, mode, options) => {\n const idbtrans = core.transaction(\n stores,\n mode,\n options\n ) as IDBTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n // Maintain TblQueryCache.ops array when transactions commit or abort\n if (mode === 'readwrite') {\n const ac = new AbortController();\n const { signal } = ac;\n const endTransaction = (wasCommitted: boolean) => () => {\n ac.abort();\n if (mode === 'readwrite') {\n // Collect which subscribers to notify:\n const affectedSubscribers = new Set<()=>void>();\n\n // Go through all tables in transaction and check if they have any optimistic updates\n for (const storeName of stores) {\n const tblCache = cache[`idb://${dbName}/${storeName}`];\n const table = core.table(storeName);\n if (tblCache) {\n // Pick optimistic ops that are part of this transaction\n const ops = tblCache.optimisticOps.filter(\n (op) => op.trans === idbtrans\n );\n if (ops.length > 0) {\n // Remove them from the optimisticOps array\n tblCache.optimisticOps = tblCache.optimisticOps.filter(\n (op) => op.trans !== idbtrans\n );\n // Commit or abort the optimistic updates\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (\n entry.res != null && // if entry.promise but not entry.res, we're fine. Query will resume now and get the result.\n idbtrans.mutatedParts/* &&\n obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)*/\n ) {\n if (wasCommitted && !entry.dirty) {\n const freezeResults = Object.isFrozen(entry.res);\n const modRes = applyOptimisticOps(\n entry.res as any[],\n entry.req,\n ops,\n table,\n entry,\n freezeResults\n );\n if (entry.dirty) {\n // Found out at this point that the entry is dirty - not to rely on!\n delArrayItem(entries, entry);\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n } else if (modRes !== entry.res) {\n entry.res = modRes;\n // Update promise\n entry.promise = DexiePromise.resolve({result: modRes} satisfies DBCoreQueryResponse);\n \n // No need to notify subscribers. They already have this value.\n // We have just updated the value of the cache without having to\n // requery the database - because we know the result for this\n // query based on computing the operations and applying them\n // to the previous result.\n }\n } else {\n if (entry.dirty) {\n // If the entry is dirty we need to get rid of it so that\n // a new entry will be created when the query is run again.\n delArrayItem(entries, entry);\n }\n // If we're not committing, we need to notify subscribers that the\n // optimistic updates are no longer valid.\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n }\n }\n }\n }\n }\n }\n }\n affectedSubscribers.forEach((requery) => requery());\n }\n };\n idbtrans.addEventListener('abort', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('error', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('complete', endTransaction(true), {\n signal,\n });\n }\n return idbtrans;\n },\n table(tableName: string) {\n const downTable = core.table(tableName);\n const primKey = downTable.schema.primaryKey;\n const tableMW = {\n ...downTable,\n mutate(req) {\n if (\n primKey.outbound || // Non-inbound tables are harded to apply optimistic updates on because we can't know primary key of results\n PSD.trans.db._options.cache === 'disabled' // User has opted-out from caching\n ) {\n // Just forward the request to the core.\n return downTable.mutate(req);\n }\n // Find the TblQueryCache for this table:\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return downTable.mutate(req);\n\n const promise = downTable.mutate(req);\n if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(key => key == null))) {\n // There are some autoIncremented keys not set yet. Need to wait for completion before we can reliably enqueue the operation.\n // (or there are too many objects so we lazy out to avoid performance bottleneck for large bulk inserts)\n promise.then((res) => { // We need to extract result keys and generate cloned values with the keys set (so that applyOptimisticOps can work)\n // But we have a problem! The req.mutatedParts is still not complete so we have to actively add the keys to the unsignaledParts set manually.\n const reqWithResolvedKeys = {\n ...req,\n values: req.values.map((value, i) => {\n const valueWithKey = primKey.keyPath.includes('.')\n ? deepClone(value)\n : {\n ...value,\n };\n setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]);\n return valueWithKey;\n })\n };\n tblCache.optimisticOps.push(reqWithResolvedKeys);\n // Signal subscribers after the observability middleware has complemented req.mutatedParts with the new keys.\n // We must queue the task so that we get the req.mutatedParts updated by observability middleware first.\n // If we refactor the dependency between observability middleware and this middleware we might not need to queue the task.\n queueMicrotask(()=>signalSubscribersLazily(req.mutatedParts)); // Reason for double laziness: in user awaits put and then does another put, signal once.\n });\n } else {\n // Enque the operation immediately\n tblCache.optimisticOps.push(req);\n // Signal subscribers that there are mutated parts\n signalSubscribersLazily(req.mutatedParts);\n promise.catch(()=> {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n });\n }\n return promise;\n },\n query(req: DBCoreQueryRequest): Promise {\n if (!isCachableContext(PSD, downTable) || !isCachableRequest(\"query\", req)) return downTable.query(req);\n const freezeResults =\n (PSD as LiveQueryContext).trans.db._options.cache === 'immutable';\n const { requery, signal } = PSD as LiveQueryContext;\n let [cacheEntry, exactMatch, tblCache, container] =\n findCompatibleQuery(dbName, tableName, 'query', req);\n if (cacheEntry && exactMatch) {\n cacheEntry.obsSet = req.obsSet; // So that optimistic result is monitored.\n // How? - because observability-middleware will track result where optimistic\n // mutations are applied and record it in the cacheEntry.\n // TODO: CHANGE THIS! The difference is resultKeys only.\n // Wanted behavior:\n // * cacheEntry obsSet should represent the obsSet without optimistic updates (so it can be checked when merging ops in tx commit)\n // * cacheEntry optimisticObsSet should represent the obsSet with current optimistic updates. It should be updated when adding an op\n // by adding the primary keys of the put/add/delete operation to the set.\n // * observability-middleware should stop recording req.obsSet when a cache entry exact match is found because it won't be used anyway.\n // I'm thinking of merging observability-middleware with cache-middleware into one single middleware because the dependencies are too\n // tight between them.\n } else {\n // --> TODO here: If not exact match, check if we have a superset to extract\n // the data from.\n\n // No cached result found. We need to query the database and cache the result.\n const promise = downTable.query(req).then((res) => {\n // Freeze or clone results\n const result = res.result;\n cacheEntry.res = result;\n if (freezeResults) {\n // For performance reasons don't deep freeze.\n // Only freeze the top-level array and its items.\n // This is good enough to teach users that the result must be treated as immutable\n // without enforcing it recursively on the entire result (which is not even possible\n // for things like Date objects and typed arrays)\n for (let i = 0, l = result.length; i < l; ++i) {\n Object.freeze(result[i]);\n }\n Object.freeze(result);\n } else {\n // If not frozen, we need to clone the result to avoid user mutating the cache\n // When we do this, user's must feel conformable with the fact that the result\n // can be mutated deeply - user is not expected to have any respect for immutability.\n res.result = deepClone(result);\n }\n return res;\n }).catch(error => {\n // In case the query operation failed, we need to remove it from the cache\n // so that subsequent calls does not get the same error but re-evaluate\n // the query.\n if (container && cacheEntry) delArrayItem(container, cacheEntry);\n return Promise.reject(error);\n });\n cacheEntry = {\n obsSet: req.obsSet,\n promise,\n subscribers: new Set(),\n type: 'query',\n req,\n dirty: false,\n };\n if (container) {\n container.push(cacheEntry);\n } else {\n container = [cacheEntry];\n if (!tblCache) {\n tblCache = cache[`idb://${dbName}/${tableName}`] = {\n queries: {\n query: {},\n count: {},\n },\n objs: new Map(),\n optimisticOps: [],\n unsignaledParts: {}\n };\n }\n tblCache.queries.query[req.query.index.name || ''] = container;\n }\n }\n subscribeToCacheEntry(cacheEntry, container, requery, signal);\n return cacheEntry.promise.then((res: DBCoreQueryResponse) => {\n return {\n result: applyOptimisticOps(\n res.result,\n req,\n tblCache?.optimisticOps,\n downTable,\n cacheEntry,\n freezeResults\n ) as any[], // readonly any[]\n };\n });\n },\n };\n return tableMW;\n },\n };\n return coreMW;\n },\n};\n\n\n","import { type Dexie } from \"../classes/dexie\";\nimport { type Table } from \"../classes/table\";\nimport { type Transaction } from \"../classes/transaction\";\n\nexport function vipify(\n target: T,\n vipDb: Dexie\n): T {\n return new Proxy(target, {\n get (target, prop, receiver) {\n // The \"db\" prop of the table or transaction is the only one we need to\n // override. The rest of the props can be accessed from the original\n // object.\n if (prop === 'db') return vipDb;\n return Reflect.get(target, prop, receiver);\n }\n });\n}\n","// Import types from the public API\nimport { Dexie as IDexie } from \"../../public/types/dexie\";\nimport { DexieOptions, DexieConstructor } from \"../../public/types/dexie-constructor\";\nimport { DbEvents } from \"../../public/types/db-events\";\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from \"../../public/types/table-schema\";\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from \"../table\";\nimport { Collection, CollectionConstructor, createCollectionConstructor } from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor';\nimport { Version } from \"../version/version\";\nimport { VersionConstructor, createVersionConstructor } from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD, globalPSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport { maxString, connections, READONLY, READWRITE } from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { _onDatabaseDeleted } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport { extractTransactionArgs, enterTransactionScope } from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\nimport { cacheMiddleware } from \"../../live-query/cache/cache-middleware\";\nimport { vipify } from \"../../helpers/vipify\";\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n PR1398_maxLoop?: number;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table; };\n _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema; };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {[StackName in keyof DexieStacks]?: Middleware[]} = {};\n _vip?: boolean;\n _novip: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\n on: DbEvents;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n cache: 'cloned', // Default to cloned for backward compatibility. For best performance and least memory consumption use 'immutable'.\n ...options\n }; \n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange\n };\n const {\n addons,\n } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true,\n PR1398_maxLoop: 3\n };\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] }) as DbEvents;\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n const db = this;\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n this.on(\"versionchange\", ev => {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.close({disableAutoOpen: false});\n this._state.openComplete = false;\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction);\n\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n // Default middlewares:\n this.use(cacheExistingValuesMiddleware);\n this.use(cacheMiddleware);\n this.use(observabilityMiddleware);\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n const vipDB = new Proxy(this, {\n get: (_, prop, receiver) => {\n if (prop === '_vip') return true;\n if (prop === 'table') return (tableName: string) => vipify(this.table(tableName), vipDB);\n const rv = Reflect.get(_, prop, receiver);\n if (rv instanceof Table) return vipify(rv, vipDB);\n if (prop === 'tables') return (rv as Table[]).map(t => vipify(t, vipDB));\n if (prop === '_createTransaction') return function() {\n const tx: Transaction = (rv as typeof this._createTransaction).apply(this, arguments);\n return vipify(tx, vipDB);\n }\n return rv;\n }\n });\n this.vip = vipDB;\n\n // Call each addon:\n addons.forEach(addon => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n v => v._cfg.version === versionNumber)[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady(fn: () => Promise): Promise {\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({stack, create, level, name}: Middleware): this {\n if (name) this.unuse({stack, name}); // Be able to replace existing middleware.\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({stack, create, level: level == null ? 10 : level, name});\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this;\n unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this;\n unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw =>\n create ? mw.create !== create : // Given middleware has a create method. Match that exactly.\n name ? mw.name !== name : // Given middleware spec \n false);\n }\n return this;\n }\n\n open() {\n return usePSD(\n globalPSD, // Enforce global scope here since db.open() can be part of a live query or transaction scope\n () => dexieOpen(this)\n );\n }\n\n _close(): void {\n const state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this.idbdb = null;\n } \n // Reset dbReadyPromise promise:\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n\n close({disableAutoOpen} = {disableAutoOpen: true}): void {\n this._close();\n const state = this._state;\n if (disableAutoOpen) this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n }\n\n delete(): Promise {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close({disableAutoOpen: false});\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n }\n\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables () {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(mode: TransactionMode, tables: Array, scopeFunc: Function) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode,\n storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map(table => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) :\n this._whenReady (enterTransaction));\n }\n\n table(tableName: string): Table;\n table(tableName: string): ITable;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return this._allTables[tableName];\n }\n}\n","import {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { isAsyncFunction, keys, objectIsEmpty } from '../functions/utils';\nimport {\n globalEvents,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport {\n beginMicroTickScope,\n decrementExpectedAwaits,\n endMicroTickScope,\n incrementExpectedAwaits,\n newScope,\n PSD,\n usePSD,\n} from '../helpers/promise';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport {\n Observable as IObservable,\n Subscription,\n} from '../public/types/observable';\nimport { Observable } from '../classes/observable/observable';\nimport { extendObservabilitySet } from './extend-observability-set';\nimport { rangesOverlap } from '../helpers/rangeset';\nimport { domDeps } from '../classes/dexie/dexie-dom-dependencies';\nimport { Transaction } from '../classes/transaction';\nimport { obsSetsOverlap } from './obs-sets-overlap';\n\nexport interface LiveQueryContext {\n subscr: ObservabilitySet;\n signal: AbortSignal;\n requery: () => void;\n trans: null | Transaction;\n querier: Function; // For debugging purposes and Error messages\n}\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(ctx: LiveQueryContext) {\n const wasRootExec = beginMicroTickScope(); // Performance: Avoid starting a new microtick scope within the async context.\n try {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const rv = newScope(querier, ctx);\n if (scopeFuncIsAsync) {\n (rv as Promise).finally(decrementExpectedAwaits);\n }\n return rv;\n } finally {\n wasRootExec && endMicroTickScope(); // Given that we created the microtick scope, we must also end it.\n }\n }\n\n let closed = false;\n let abortController: AbortController;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n if (closed) return;\n closed = true;\n if (abortController) abortController.abort();\n if (startedListening) globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let startedListening = false;\n\n function shouldNotify() {\n return obsSetsOverlap(currentObs, accumMuts);\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const doQuery = () => {\n if (\n closed || // closed - don't run!\n !domDeps.indexedDB) // SSR in sveltekit, nextjs etc\n {\n return;\n }\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n // Abort signal fill three purposes:\n // 1. Abort the query if the observable is unsubscribed.\n // 2. Abort the query if a new query is made before the previous one has completed.\n // 3. For cached queries to know if they should remain in memory or could be enqued for being freed up.\n // (they will remain in memory for a short time and if noone needs them again, they will eventually be freed up)\n if (abortController) abortController.abort(); // Cancel previous query. Last query will be cancelled on unsubscribe().\n abortController = new AbortController();\n \n const ctx: LiveQueryContext = {\n subscr,\n signal: abortController.signal,\n requery: doQuery,\n querier,\n trans: null // Make the scope transactionless (don't reuse transaction from outer scope of the caller of subscribe())\n }\n const ret = execute(ctx);\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n if (closed || ctx.signal.aborted) {\n // closed - no subscriber anymore.\n // signal.aborted - new query was made before this one completed and\n // the querier might have catched AbortError and return successful result.\n // If so, we should not rely in that result because we know we have aborted\n // this run, which means there's another run going on that will handle accumMuts\n // and we must not base currentObs on the half-baked subscr.\n return;\n }\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n if (!objectIsEmpty(currentObs) && !startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n } \n observer.next && observer.next(result);\n },\n (err) => {\n hasValue = false;\n if (!['DatabaseClosedError', 'AbortError'].includes(err?.name)) {\n if (closed) return;\n observer.error && observer.error(err);\n }\n }\n );\n };\n\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } from '../../helpers/database-enumerator';\nimport { PSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { dexieStackFrameFilter, minKey, connections, DEXIE_VERSION } from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\nimport { cache } from '../../live-query/cache/cache';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n// \nprops(Dexie, {\n\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName, {addons: []});\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap,\n //maxKey: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: domDeps,\n cache,\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n // default: Dexie, // Commented because solved in index-umd.ts instead.\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n // Dexie: Dexie // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { isIEOrEdge } from '../globals/constants';\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport { signalSubscribersNow } from './cache/signalSubscribers';\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n } else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\n/** Called from listeners to BroadcastChannel and DOM event to\n * propagate the event locally into dexie's storagemutated event\n * and invalidate cached queries.\n * \n * This function is only called when the event is not originating\n * from this same Dexie module - either from another redundant dexie import\n * or from a foreign tab or worker. That's why we need to invalidate\n * the cache when this happens.\n */\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n // Fire the \"storagemutated\" event.\n globalEvents.storagemutated.fire(updateParts);\n // Invalidate cached queries and signal subscribers to requery.\n signalSubscribersNow(updateParts, true);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n }\n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n bc.onmessage = (ev) => {\n if (ev.data) propagateLocally(ev.data);\n };\n} else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n // DOM verified - when typeof self !== \"undefined\", we are a window or worker. Not a Node process.\n\n //\n // Propagate local changes to remote tabs/windows via storage event and service worker\n // via messages. We have this code here because of https://bugs.webkit.org/show_bug.cgi?id=161472.\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n // We're a browsing window or tab. Propagate to other windows/tabs via storage event:\n localStorage.setItem(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n JSON.stringify({\n trig: Math.random(),\n changedParts,\n })\n );\n }\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n })\n );\n }\n }\n } catch {}\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev: StorageEvent) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data) propagateLocally(data.changedParts);\n }\n });\n }\n\n //\n // Propagate messages from service worker\n //\n const swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\n if (swContainer) {\n // We're a browser window and want to propagate message from the SW:\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\n\nfunction propagateMessageLocally({ data }: MessageEvent) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport { dexieStackFrameFilter } from './globals/constants';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport { liveQuery } from './live-query/live-query';\nimport { Entity } from './classes/entity/Entity';\nimport { cmp } from './functions/cmp';\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport { Entity };\nexport { cmp };\nexport default Dexie;\n","// Issue #1127. Need another index.ts for the UMD module with only a default export\n// like it was before.\n// In practice though, the UMD export will also export the named export in \n// https://github.com/dfahlander/Dexie.js/blob/c9187ae60c0d7a424f85bab3af179fbbc9901c8e/src/classes/dexie/dexie-static-props.ts#L223-L228\nimport Dexie from \"./index\";\nimport * as namedExports from \"./index\";\nimport { __assign } from 'tslib';\n__assign(Dexie, namedExports, {default: Dexie});\nexport default Dexie;\n"],"names":["asap","_a","Promise","Dexie","Debug.debug","Debug.getErrorWithStack","safari14Workaround","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;;;;;;;IAAA;IACA;IAEA;IACA;IAEA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAGA,IAAI,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,EAAE;IACnC,IAAI,aAAa,GAAG,MAAM,CAAC,cAAc;IACzC,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,YAAY,KAAK,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC;IACpF,QAAQ,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC1G,IAAI,OAAO,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/B,CAAC,CAAC;IAEK,SAAS,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE;IAChC,IAAI,IAAI,OAAO,CAAC,KAAK,UAAU,IAAI,CA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B,IAAI,EAAE,8BAA8B;gCACpC,YAAY,cAAA;6BACb,CAAC;yBAAA,CACL,CAAC;qBACH;iBACF;aACF;YAAC,WAAM,GAAE;SACX,CAAC,CAAC;QAKH,IAAI,OAAO,gBAAgB,KAAK,WAAW,EAAE;YACzC,gBAAgB,CAAC,SAAS,EAAE,UAAC,EAAgB;gBAC7C,IAAI,EAAE,CAAC,GAAG,KAAK,8BAA8B,EAAE;oBAC7C,IAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;oBACrC,IAAI,IAAI;wBAAE,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;iBAC/C;aACF,CAAC,CAAC;SACJ;QAKD,IAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC,aAAa,CAAC;QAC7D,IAAI,WAAW,EAAE;YAEf,WAAW,CAAC,gBAAgB,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;SAClE;KACF;IAED,SAAS,uBAAuB,CAAC,EAAsB;YAApB,IAAI,UAAA;QACrC,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,8BAA8B,EAAE;YACxD,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;SACrC;IACH;;IC9EA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCQ,YAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC;;;;;;;;;;;;;;ICflD,QAAQ,CAACD,OAAK,EAAE,YAAY,EAAE,EAAC,OAAO,EAAEA,OAAK,EAAC,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..cb409d01d --- /dev/null +++ b/dist/dexie.min.js @@ -0,0 +1,2 @@ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Dexie=t()})(this,function(){"use strict";var s=function(e,t){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};var _=function(){return(_=Object.assign||function(e){for(var t,n=1,r=arguments.length;n.",lt="String expected.",ft=[],ht="undefined"!=typeof navigator&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),dt=ht,pt=ht,yt="__dbnames",vt="readonly",mt="readwrite";function bt(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}var gt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function wt(t){return"string"!=typeof t||/\./.test(t)?function(e){return e}:function(e){return void 0===e[t]&&t in e&&delete(e=j(e))[t],e}}function _t(){throw Z.Type()}function xt(e,t){try{var n=kt(e),r=kt(t);if(n!==r)return"Array"===n?1:"Array"===r?-1:"binary"===n?1:"binary"===r?-1:"string"===n?1:"string"===r?-1:"Date"===n?1:"Date"!==r?NaN:-1;switch(n){case"number":case"Date":case"string":return tc+l&&h(c+g)})})}return h(0).then(function(){if(0=c}).forEach(function(u){t.push(function(){var t=h,e=u._cfg.dbschema;_n(s,t,f),_n(s,e,f),h=s._dbSchema=e;var n=mn(t,e);n.add.forEach(function(e){bn(f,e[0],e[1].primKey,e[1].indexes)}),n.change.forEach(function(e){if(e.recreate)throw new Z.Upgrade("Not yet support for changing primary key");var t=f.objectStore(e.name);e.add.forEach(function(e){return gn(t,e)}),e.change.forEach(function(e){t.deleteIndex(e.name),gn(t,e)}),e.del.forEach(function(e){return t.deleteIndex(e)})});var r=u._cfg.contentUpgrade;if(r&&u._cfg.version>c){hn(s,f),l._memoizedTables={},d=!0;var i=P(e);n.del.forEach(function(e){i[e]=t[e]}),pn(s,[s.Transaction.prototype]),dn(s,[s.Transaction.prototype],x(i),i),l.schema=i;var o,a=R(r);a&&Je();n=Ae.follow(function(){var e;(o=r(l))&&a&&(e=$e.bind(null,null),o.then(e,e))});return o&&"function"==typeof o.then?Ae.resolve(o):n.then(function(){return o})}}),t.push(function(e){var t,n,r;d&&dt||(t=u._cfg.dbschema,n=t,r=e,[].slice.call(r.db.objectStoreNames).forEach(function(e){return null==n[e]&&r.db.deleteObjectStore(e)})),pn(s,[s.Transaction.prototype]),dn(s,[s.Transaction.prototype],s._storeNames,s._dbSchema),l.schema=s._dbSchema})}),function e(){return t.length?Ae.resolve(t.shift()(l.idbtrans)).then(e):Ae.resolve()}().then(function(){var t,n;n=f,x(t=h).forEach(function(e){n.db.objectStoreNames.contains(e)||bn(n,e,t[e].primKey,t[e].indexes)})}).catch(u))})}function mn(e,t){var n,r={del:[],add:[],change:[]};for(n in e)t[n]||r.del.push(n);for(n in t){var i=e[n],o=t[n];if(i){var a={name:n,def:o,recreate:!1,del:[],add:[],change:[]};if(""+(i.primKey.keyPath||"")!=""+(o.primKey.keyPath||"")||i.primKey.auto!==o.primKey.auto&&!ht)a.recreate=!0,r.change.push(a);else{var u=i.idxByName,s=o.idxByName,c=void 0;for(c in u)s[c]||a.del.push(c);for(c in s){var l=u[c],f=s[c];l?l.src!==f.src&&a.change.push(f):a.add.push(f)}(0Math.pow(2,62)?0:e.oldVersion,p=e<1,f.idbdb=l.result,vn(f,e/10,d,n))},n),l.onsuccess=ze(function(){d=null;var e,t,n,r,i,o=f.idbdb=l.result,a=y(o.objectStoreNames);if(0u.limit?t.length=u.limit:e.length===u.limit&&t.length=r.limit&&(!r.values||e.req.values)&&rr(e.req.query.range,r.query.range)}),!1,i,o];case"count":a=o.find(function(e){return nr(e.req.query.range,r.query.range)});return[a,!!a,i,o]}}(w,c,"query",t),a=o[0],e=o[1],u=o[2],s=o[3];return a&&e?a.obsSet=t.obsSet:(e=l.query(t).then(function(e){var t=e.result;if(a.res=t,i){for(var n=0,r=t.length;n= 0) + a.splice(i, 1); + return i >= 0; +} +var NO_CHAR_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; +} +var isAsyncFunction = typeof Symbol !== 'undefined' + ? function (fn) { return fn[Symbol.toStringTag] === 'AsyncFunction'; } + : function () { return false; }; + +var debug = typeof location !== 'undefined' && + /^(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() { + if (NEEDS_THROW_FOR_STACK) + try { + getErrorWithStack.arguments; + throw new Error(); + } + 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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" +}; +function DexieError(name, msg) { + 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: " + Object.keys(failures) + .map(function (key) { return failures[key].toString(); }) + .filter(function (v, i, s) { return s.indexOf(v) === i; }) + .join('\n'); +} +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + this.message = getMultiErrorMessage(msg, failures); +} +derive(ModifyError).from(DexieError); +function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = Object.keys(failures).map(function (pos) { return failures[pos]; }); + this.failuresByPos = failures; + this.message = getMultiErrorMessage(msg, this.failures); +} +derive(BulkError).from(DexieError); +var errnames = errorList.reduce(function (obj, name) { return (obj[name] = name + "Error", obj); }, {}); +var BaseException = DexieError; +var exceptions = errorList.reduce(function (obj, name) { + 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 = "".concat(msgOrInner).concat(!inner ? '' : '\n ' + inner); + this.inner = inner || null; + } + else if (typeof msgOrInner === 'object') { + this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); + this.inner = msgOrInner; + } + } + derive(DexieError).from(BaseException); + obj[name] = DexieError; + return obj; +}, {}); +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) { + 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) { + 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) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, + onerror = 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, + onerror = 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); + var onsuccess = this.onsuccess, + onerror = 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); + }; +} + +var INTERNAL = {}; +var LONG_STACKS_CLIP_LIMIT = 100, +MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +var patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +function schedulePhysicalTick() { + queueMicrotask(physicalTick); +} +var asap = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; +var isOutsideMicroTick = true, +needsNewPhysicalTick = true, +unhandledErrors = [], +rejectingErrors = [], +currentFulfiller = null, rejectionMapper = mirror; +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: nop, + pgp: false, + env: {}, + finalize: nop +}; +var PSD = globalPSD; +var microtickQueue = []; +var numScheduledCalls = 0; +var tickFinalizers = []; +function DexiePromise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this._lib = false; + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); + return; + } + this._state = null; + this._value = null; + ++psd.ref; + executePromiseTask(this, fn); +} +var thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; + return then; + }, + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : + { + get: function () { + return value; + }, + set: thenProp.set + }); + } +}; +props(DexiePromise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, function (err) { + return err instanceof type ? handler(err) : PromiseReject(err); + }) + : this.then(null, function (err) { + 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; + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + var _this = this; + return ms < Infinity ? + new DexiePromise(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(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); +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; +} +props(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) + .map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); }); + }); + }, + PSD: { + get: function () { return PSD; }, + set: function (value) { return PSD = value; } + }, + totalEchoes: { get: function () { return totalEchoes; } }, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap; }, + set: function (value) { asap = value; } + }, + rejectionMapper: { + get: function () { return rejectionMapper; }, + set: function (value) { rejectionMapper = value; } + }, + follow: function (fn, zoneProps) { + return new DexiePromise(function (resolve, reject) { + return newScope(function (resolve, reject) { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject; + psd.finalize = callBoth(function () { + var _this = this; + 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); + }); + } +}); +if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) + .then(function () { return --remaining || resolve(results); }); }); + }); + }); + if (NativePromise.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); }); + }); + }); +} +function executePromiseTask(promise, fn) { + try { + fn(function (value) { + if (promise._state !== null) + return; + 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 DexiePromise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); + } + 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; + } + }); + }); + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); +} +function propagateAllListeners(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 (numScheduledCalls === 0) { + ++numScheduledCalls; + asap(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } +} +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + currentFulfiller = promise; + var ret, value = promise._value; + if (promise._state) { + ret = cb(value); + } + else { + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); + } + listener.resolve(ret); + } + catch (e) { + listener.reject(e); + } + finally { + 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; + 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) { + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } +} +function physicalTick() { + usePSD(globalPSD, function () { + beginMicroTickScope() && endMicroTickScope(); + }); +} +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} +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); + 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(function () { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); +} +function addPossiblyUnhandledError(promise) { + if (!unhandledErrors.some(function (p) { return p._value === promise._value; })) + unhandledErrors.push(promise); +} +function markErrorAsHandled(promise) { + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + unhandledErrors.splice(i, 1); + return; + } +} +function PromiseReject(reason) { + return new DexiePromise(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(); + } + }; +} +var task = { awaits: 0, echoes: 0, id: 0 }; +var taskCounter = 0; +var zoneStack = []; +var zoneEchoes = 0; +var totalEchoes = 0; +var zone_id_counter = 0; +function newScope(fn, props, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) + } : {}; + if (props) + extend(psd, props); + ++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 incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +function decrementExpectedAwaits() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; +} +if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; +} +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; + } + 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)) { + queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + var GlobalPromise_1 = globalPSD.env.Promise; + var targetEnv = targetZone.env; + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise_1.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + GlobalPromise_1.all = targetEnv.all; + GlobalPromise_1.race = targetEnv.race; + GlobalPromise_1.resolve = targetEnv.resolve; + GlobalPromise_1.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise_1.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise_1.any = targetEnv.any; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + 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 nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { + 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); + if (cleanup) + queueMicrotask(decrementExpectedAwaits); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; +} +var rejection = DexiePromise.reject; + +function tempTransaction(db, mode, storeNames, fn) { + if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { + if (db._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); + } + if (!db._state.isBeingOpened) { + if (!db._options.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); + } + return db._state.dbReadyPromise.then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + else { + var trans = db._createTransaction(mode, storeNames, db._dbSchema); + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return tempTransaction(db, mode, storeNames, fn); }); + } + return rejection(ex); + } + return trans._promise(mode, function (resolve, reject) { + return newScope(function () { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function (result) { + if (mode === 'readwrite') + try { + trans.idbtrans.commit(); + } + catch (_a) { } + return mode === 'readonly' ? result : trans._completion.then(function () { return result; }); + }); + } +} + +var DEXIE_VERSION = '4.0.1-beta.1'; +var maxString = String.fromCharCode(65535); +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 DBNAMES_DB = '__dbnames'; +var READONLY = 'readonly'; +var READWRITE = 'readwrite'; + +function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; +} + +var AnyRange = { + type: 3 , + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false +}; + +function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) + ? function (obj) { + if (obj[keyPath] === undefined && (keyPath in obj)) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } + : function (obj) { return obj; }; +} + +function Entity() { + throw exceptions.Type(); +} + +function cmp(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; +} +function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function type(x) { + var t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + var tsTag = toStringTag(x); + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; +} +function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); +} + +var Table = (function () { + function Table() { + } + Table.prototype._trans = function (mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + var tableName = this.name; + function checkTableInTransaction(resolve, reject, trans) { + if (!trans.schema[tableName]) + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + return fn(trans.idbtrans, trans); + } + var wasRootExec = beginMicroTickScope(); + try { + return trans && trans.db._novip === this.db._novip ? + trans === PSD.trans ? + trans._promise(mode, checkTableInTransaction, writeLocked) : + newScope(function () { return trans._promise(mode, checkTableInTransaction, writeLocked); }, { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + } + finally { + if (wasRootExec) + endMicroTickScope(); + } + }; + Table.prototype.get = function (keyOrCrit, cb) { + var _this = this; + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + return this._trans('readonly', function (trans) { + return _this.core.get({ trans: trans, key: keyOrCrit }) + .then(function (res) { return _this.hook.reading.fire(res); }); + }).then(cb); + }; + Table.prototype.where = function (indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, "[".concat(indexOrCrit.join('+'), "]")); + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function (ix) { + if (ix.compound && + keyPaths.every(function (keyPath) { return ix.keyPath.indexOf(keyPath) >= 0; })) { + for (var i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort(function (a, b) { return a.keyPath.length - b.keyPath.length; })[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this + .where(keyPathsInValidOrder) + .equals(keyPathsInValidOrder.map(function (kp) { return indexOrCrit[kp]; })); + } + if (!compoundIndex && debug) + console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit of a ") + + "compound index [".concat(keyPaths.join('+'), "]")); + var idxByName = this.schema.idxByName; + var idb = this.db._deps.indexedDB; + function equals(a, b) { + return idb.cmp(a, b) === 0; + } + var _a = keyPaths.reduce(function (_a, keyPath) { + var prevIndex = _a[0], prevFilterFn = _a[1]; + var index = idxByName[keyPath]; + var value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? + combine(prevFilterFn, index && index.multi ? + function (x) { + var prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(function (item) { return equals(value, item); }); + } : function (x) { return equals(value, getByKeyPath(x, keyPath)); }) + : prevFilterFn + ]; + }, [null, null]), idx = _a[0], filterFunction = _a[1]; + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(filterFunction) : + compoundIndex ? + this.filter(filterFunction) : + this.where(keyPaths).equals(''); + }; + Table.prototype.filter = function (filterFunction) { + return this.toCollection().and(filterFunction); + }; + Table.prototype.count = function (thenShortcut) { + return this.toCollection().count(thenShortcut); + }; + Table.prototype.offset = function (offset) { + return this.toCollection().offset(offset); + }; + Table.prototype.limit = function (numRows) { + return this.toCollection().limit(numRows); + }; + Table.prototype.each = function (callback) { + return this.toCollection().each(callback); + }; + Table.prototype.toArray = function (thenShortcut) { + return this.toCollection().toArray(thenShortcut); + }; + Table.prototype.toCollection = function () { + return new this.db.Collection(new this.db.WhereClause(this)); + }; + Table.prototype.orderBy = function (index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? + "[".concat(index.join('+'), "]") : + index)); + }; + Table.prototype.reverse = function () { + return this.toCollection().reverse(); + }; + Table.prototype.mapToClass = function (constructor) { + var _a = this, db = _a.db, tableName = _a.name; + this.schema.mappedClass = constructor; + if (constructor.prototype instanceof Entity) { + constructor = (function (_super) { + __extends(class_1, _super); + function class_1() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(class_1.prototype, "db", { + get: function () { return db; }, + enumerable: false, + configurable: true + }); + class_1.prototype.table = function () { return tableName; }; + return class_1; + }(constructor)); + } + var inheritedProps = new Set(); + for (var proto = constructor.prototype; proto; proto = getProto(proto)) { + Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); }); + } + var readHook = function (obj) { + if (!obj) + return obj; + var res = Object.create(constructor.prototype); + for (var m in obj) + if (!inheritedProps.has(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; + }; + Table.prototype.defineClass = function () { + function Class(content) { + extend(this, content); + } + return this.mapToClass(Class); + }; + Table.prototype.add = function (obj, key) { + var _this = this; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); + }).then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + }; + Table.prototype.update = function (keyOrObject, modifications) { + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + 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 { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + }; + Table.prototype.put = function (obj, key) { + var _this = this; + var _a = this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; }) + .then(function (lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + }; + Table.prototype.delete = function (key) { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.clear = function () { + var _this = this; + return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); }) + .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); + }; + Table.prototype.bulkGet = function (keys) { + var _this = this; + return this._trans('readonly', function (trans) { + return _this.core.getMany({ + keys: keys, + trans: trans + }).then(function (result) { return result.map(function (res) { return _this.hook.reading.fire(res); }); }); + }); + }; + Table.prototype.bulkAdd = function (objects, keysOrOptions, options) { + var _this = this; + var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToAdd = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'add', keys: keys, values: objectsToAdd, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); + }); + }); + }; + Table.prototype.bulkPut = function (objects, keysOrOptions, options) { + var _this = this; + var keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + var wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', function (trans) { + var _a = _this.schema.primKey, auto = _a.auto, keyPath = _a.keyPath; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToPut = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return _this.core.mutate({ trans: trans, type: 'put', keys: keys, values: objectsToPut, wantResults: wantResults }) + .then(function (_a) { + var numFailures = _a.numFailures, results = _a.results, lastResult = _a.lastResult, failures = _a.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); + }); + }); + }; + Table.prototype.bulkUpdate = function (keysAndChanges) { + var _this = this; + var coreTable = this.core; + var keys = keysAndChanges.map(function (entry) { return entry.key; }); + var changeSpecs = keysAndChanges.map(function (entry) { return entry.changes; }); + var offsetMap = []; + return this._trans('readwrite', function (trans) { + return coreTable.getMany({ trans: trans, keys: keys, cache: 'clone' }).then(function (objs) { + var resultKeys = []; + var resultObjs = []; + keysAndChanges.forEach(function (_a, idx) { + var key = _a.key, changes = _a.changes; + var obj = objs[idx]; + if (obj) { + for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { + var keyPath = _b[_i]; + var value = changes[keyPath]; + if (keyPath === _this.schema.primKey.keyPath) { + if (cmp(value, key) !== 0) { + throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); + } + } + else { + setByKeyPath(obj, keyPath, value); + } + } + offsetMap.push(idx); + resultKeys.push(key); + resultObjs.push(obj); + } + }); + var numEntries = resultKeys.length; + return coreTable + .mutate({ + trans: trans, + type: 'put', + keys: resultKeys, + values: resultObjs, + updates: { + keys: keys, + changeSpecs: changeSpecs + } + }) + .then(function (_a) { + var numFailures = _a.numFailures, failures = _a.failures; + if (numFailures === 0) + return numEntries; + for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { + var offset = _b[_i]; + var mappedOffset = offsetMap[Number(offset)]; + if (mappedOffset != null) { + var failure = failures[offset]; + delete failures[offset]; + failures[mappedOffset] = failure; + } + } + throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); + }); + }); + }); + }; + Table.prototype.bulkDelete = function (keys) { + var _this = this; + var numKeys = keys.length; + return this._trans('readwrite', function (trans) { + return _this.core.mutate({ trans: trans, type: 'delete', keys: keys }); + }).then(function (_a) { + var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures; + if (numFailures === 0) + return lastResult; + throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); + }); + }; + return Table; +}()); + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + 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 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) { + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + var context = add(eventName, mirror, function fire() { + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + context.subscribers.forEach(function (fn) { + asap$1(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype: prototype }); + return constructor; +} + +function createTableConstructor(db) { + return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) { + this.db = db; + this._tx = trans; + this.name = name; + this.schema = tableSchema; + this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + }); +} + +function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); +} +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); +} +function getIndexOrStore(ctx, coreSchema) { + if (ctx.isPrimKey) + return coreSchema.primaryKey; + var index = coreSchema.getIndexByKeyPath(ctx.index); + if (!index) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); + return index; +} +function openCursor(ctx, coreTable, trans) { + var index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans: trans, + values: !ctx.keysOnly, + reverse: ctx.dir === 'prev', + unique: !!ctx.unique, + query: { + index: index, + range: ctx.range + } + }); +} +function iter(ctx, fn, coreTrans, coreTable) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); + } + else { + var set_1 = {}; + var union = function (item, cursor, advance) { + if (!filter || filter(cursor, advance, function (result) { return cursor.stop(result); }, function (err) { return cursor.fail(err); })) { + var primaryKey = cursor.primaryKey; + var key = '' + primaryKey; + if (key === '[object ArrayBuffer]') + key = '' + new Uint8Array(primaryKey); + if (!hasOwn(set_1, key)) { + set_1[key] = true; + fn(item, cursor, advance); + } + } + }; + return Promise.all([ + ctx.or._iterate(union, coreTrans), + iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) + ]); + } +} +function iterate(cursorPromise, filter, fn, valueMapper) { + var mappedFn = valueMapper ? function (x, c, a) { return fn(valueMapper(x), c, a); } : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(function (cursor) { + if (cursor) { + return cursor.start(function () { + var c = function () { return cursor.continue(); }; + if (!filter || filter(cursor, function (advancer) { return c = advancer; }, function (val) { cursor.stop(val); c = nop; }, function (e) { cursor.fail(e); c = nop; })) + wrappedFn(cursor.value, cursor, function (advancer) { return c = advancer; }); + c(); + }); + } + }); +} + +var Collection = (function () { + function Collection() { + } + Collection.prototype._read = function (fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readonly', fn).then(cb); + }; + Collection.prototype._write = function (fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readwrite', fn, "locked"); + }; + Collection.prototype._addAlgorithm = function (fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }; + Collection.prototype._iterate = function (fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + }; + Collection.prototype.clone = function (props) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props) + extend(ctx, props); + rv._ctx = ctx; + return rv; + }; + Collection.prototype.raw = function () { + this._ctx.valueMapper = null; + return this; + }; + Collection.prototype.each = function (fn) { + var ctx = this._ctx; + return this._read(function (trans) { return iter(ctx, fn, trans, ctx.table.core); }); + }; + Collection.prototype.count = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + var coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans: trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(function (count) { return Math.min(count, ctx.limit); }); + } + else { + var count = 0; + return iter(ctx, function () { ++count; return false; }, trans, coreTable) + .then(function () { return count; }); + } + }).then(cb); + }; + Collection.prototype.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); + }; + Collection.prototype.toArray = function (cb) { + var _this = this; + return this._read(function (trans) { + var ctx = _this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + var valueMapper_1 = ctx.valueMapper; + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + limit: ctx.limit, + values: true, + query: { + index: index, + range: ctx.range + } + }).then(function (_a) { + var result = _a.result; + return valueMapper_1 ? result.map(valueMapper_1) : result; + }); + } + else { + var a_1 = []; + return iter(ctx, function (item) { return a_1.push(item); }, trans, ctx.table.core).then(function () { return a_1; }); + } + }, cb); + }; + Collection.prototype.offset = function (offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + 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; + }; + Collection.prototype.limit = function (numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, function () { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + }; + Collection.prototype.until = function (filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + }; + Collection.prototype.first = function (cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.last = function (cb) { + return this.reverse().first(cb); + }; + Collection.prototype.filter = function (filterFunction) { + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + }; + Collection.prototype.and = function (filter) { + return this.filter(filter); + }; + Collection.prototype.or = function (indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + }; + Collection.prototype.reverse = function () { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }; + Collection.prototype.desc = function () { + return this.reverse(); + }; + Collection.prototype.eachKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + }; + Collection.prototype.eachUniqueKey = function (cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }; + Collection.prototype.eachPrimaryKey = function (cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + }; + Collection.prototype.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); + }; + Collection.prototype.primaryKeys = function (cb) { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(function (trans) { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans: trans, + values: false, + limit: ctx.limit, + query: { + index: index, + range: ctx.range + } + }); + }).then(function (_a) { + var result = _a.result; + return result; + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function (item, cursor) { + a.push(cursor.primaryKey); + }).then(function () { + return a; + }).then(cb); + }; + Collection.prototype.uniqueKeys = function (cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }; + Collection.prototype.firstKey = function (cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + }; + Collection.prototype.lastKey = function (cb) { + return this.reverse().firstKey(cb); + }; + Collection.prototype.distinct = function () { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }; + Collection.prototype.modify = function (changes) { + var _this = this; + var ctx = this._ctx; + return this._write(function (trans) { + var modifyer; + if (typeof changes === 'function') { + modifyer = changes; + } + else { + 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); + anythingModified = true; + } + } + return anythingModified; + }; + } + var coreTable = ctx.table.core; + var _a = coreTable.schema.primaryKey, outbound = _a.outbound, extractKey = _a.extractKey; + var limit = _this.db._options.modifyChunkSize || 200; + var totalFailures = []; + var successCount = 0; + var failedKeys = []; + var applyMutateResult = function (expectedCount, res) { + var failures = res.failures, numFailures = res.numFailures; + successCount += expectedCount - numFailures; + for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) { + var pos = _a[_i]; + totalFailures.push(failures[pos]); + } + }; + return _this.clone().primaryKeys().then(function (keys) { + var nextChunk = function (offset) { + var count = Math.min(limit, keys.length - offset); + return coreTable.getMany({ + trans: trans, + keys: keys.slice(offset, offset + count), + cache: "immutable" + }).then(function (values) { + var addValues = []; + var putValues = []; + var putKeys = outbound ? [] : null; + var deleteKeys = []; + for (var i = 0; i < count; ++i) { + var origValue = values[i]; + var ctx_1 = { + value: deepClone(origValue), + primKey: keys[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) { + deleteKeys.push(keys[offset + i]); + addValues.push(ctx_1.value); + } + else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys[offset + i]); + } + } + } + var criteria = isPlainKeyRange(ctx) && + ctx.limit === Infinity && + (typeof changes !== 'function' || changes === deleteCallback) && { + index: ctx.index, + range: ctx.range + }; + return Promise.resolve(addValues.length > 0 && + coreTable.mutate({ trans: trans, type: 'add', values: addValues }) + .then(function (res) { + for (var pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(function () { return (putValues.length > 0 || (criteria && typeof changes === 'object')) && + coreTable.mutate({ + trans: trans, + type: 'put', + keys: putKeys, + values: putValues, + criteria: criteria, + changeSpec: typeof changes !== 'function' + && changes + }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && + coreTable.mutate({ + trans: trans, + type: 'delete', + keys: deleteKeys, + criteria: criteria + }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () { + return keys.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(function () { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys.length; + }); + }); + }); + }; + Collection.prototype.delete = function () { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 )) + { + return this._write(function (trans) { + var primaryKey = ctx.table.core.schema.primaryKey; + var coreRange = range; + return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) { + return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange }) + .then(function (_a) { + var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures; + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(deleteCallback); + }; + return Collection; +}()); +var deleteCallback = function (value, ctx) { return ctx.value = null; }; + +function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) { + this.db = db; + var keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx; + var table = whereCtx.table; + var readingHook = table.hook.reading.fire; + 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: readingHook !== mirror ? readingHook : null + }; + }); +} + +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 fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new collectionOrWhereClause.Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; +} +function emptyCollection(whereClause) { + return new whereClause.Collection(whereClause, function () { return rangeEqual(""); }).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 whereClause.Collection(whereClause, function () { return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); }); + c._ondirectionchange = function (direction) { + 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; +} +function createRange(lower, upper, lowerOpen, upperOpen) { + return { + type: 2 , + lower: lower, + upper: upper, + lowerOpen: lowerOpen, + upperOpen: upperOpen + }; +} +function rangeEqual(value) { + return { + type: 1 , + lower: value, + upper: value + }; +} + +var WhereClause = (function () { + function WhereClause() { + } + Object.defineProperty(WhereClause.prototype, "Collection", { + get: function () { + return this._ctx.table.db.Collection; + }, + enumerable: false, + configurable: true + }); + WhereClause.prototype.between = function (lower, upper, includeLower, includeUpper) { + includeLower = includeLower !== false; + includeUpper = includeUpper === true; + try { + if ((this._cmp(lower, upper) > 0) || + (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); + return new this.Collection(this, function () { return createRange(lower, upper, !includeLower, !includeUpper); }); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }; + WhereClause.prototype.equals = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return rangeEqual(value); }); + }; + WhereClause.prototype.above = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, true); }); + }; + WhereClause.prototype.aboveOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(value, undefined, false); }); + }; + WhereClause.prototype.below = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value, false, true); }); + }; + WhereClause.prototype.belowOrEqual = function (value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function () { return createRange(undefined, value); }); + }; + WhereClause.prototype.startsWith = function (str) { + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }; + WhereClause.prototype.startsWithIgnoreCase = function (str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function (x, a) { return x.indexOf(a[0]) === 0; }, [str], maxString); + }; + WhereClause.prototype.equalsIgnoreCase = function (str) { + return addIgnoreCaseAlgorithm(this, function (x, a) { return x === a[0]; }, [str], ""); + }; + WhereClause.prototype.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, ""); + }; + WhereClause.prototype.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); + }; + WhereClause.prototype.anyOf = function () { + var _this = this; + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = this._cmp; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new this.Collection(this, function () { return createRange(set[0], set[set.length - 1]); }); + c._ondirectionchange = function (direction) { + compare = (direction === "next" ? + _this._ascending : + _this._descending); + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function (cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + ++i; + if (i === set.length) { + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + return true; + } + else { + advance(function () { cursor.continue(set[i]); }); + return false; + } + }); + return c; + }; + WhereClause.prototype.notEqual = function (value) { + return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.noneOf = function () { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new this.Collection(this); + try { + set.sort(this._ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + 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], this.db._maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + }; + WhereClause.prototype.inAnyRange = function (ranges, options) { + var _this = this; + var cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; + 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; + var includeUppers = options && options.includeUppers === true; + function addRange(ranges, newRange) { + var i = 0, l = ranges.length; + for (; 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]); } + var set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var rangePos = 0; + var keyIsBeyondCurrentEntry = includeUppers ? + function (key) { return ascending(key, set[rangePos][1]) > 0; } : + function (key) { return ascending(key, set[rangePos][1]) >= 0; }; + var keyIsBeforeCurrentEntry = includeLowers ? + function (key) { return descending(key, set[rangePos][0]) > 0; } : + function (key) { return descending(key, set[rangePos][0]) >= 0; }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new this.Collection(this, function () { return createRange(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)) { + ++rangePos; + if (rangePos === set.length) { + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + return true; + } + else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { + return false; + } + else { + advance(function () { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + }; + WhereClause.prototype.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]; })); + }; + return WhereClause; +}()); + +function createWhereClauseConstructor(db) { + return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) { + this.db = db; + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + this._cmp = this._ascending = cmp; + this._descending = function (a, b) { return cmp(b, a); }; + this._max = function (a, b) { return cmp(a, b) > 0 ? a : b; }; + this._min = function (a, b) { return cmp(a, b) < 0 ? a : b; }; + this._IDBKeyRange = db._deps.IDBKeyRange; + if (!this._IDBKeyRange) + throw new exceptions.MissingAPI(); + }); +} + +function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); +} +function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); +} + +var DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; +var STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; +var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + +var Transaction = (function () { + function Transaction() { + } + Transaction.prototype._lock = function () { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }; + Transaction.prototype._unlock = function () { + assert(!PSD.global); + 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; + }; + Transaction.prototype._locked = function () { + return this._reculock && PSD.lockOwnerFor !== this; + }; + Transaction.prototype.create = function (idbtrans) { + var _this = this; + if (!this.mode) + return this; + var idbdb = this.db.idbdb; + var dbOpenError = this.db._state.dbOpenError; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) + throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + idbtrans = this.idbtrans = idbtrans || + (this.db.core + ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) + : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); + idbtrans.onerror = wrap(function (ev) { + preventDefault(ev); + _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(); + if ('mutatedParts' in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + return this; + }; + Transaction.prototype._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 DexiePromise(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 DexiePromise(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 DexiePromise(function (resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }; + Transaction.prototype._root = function () { + return this.parent ? this.parent._root() : this; + }; + Transaction.prototype.waitFor = function (promiseLike) { + var root = this._root(); + var promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(function () { return promise; }); + } + else { + root._waitingFor = promise; + root._waitingQueue = []; + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new DexiePromise(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) { + root._waitingFor = null; + } + }); + }); + }; + Transaction.prototype.abort = function () { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + }; + Transaction.prototype.table = function (tableName) { + var memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + var tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + }; + return Transaction; +}()); + +function createTransactionConstructor(db) { + return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + var _this = this; + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + 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; + this._completion = new DexiePromise(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); + }); + }); +} + +function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { + return { + name: name, + keyPath: keyPath, + unique: unique, + multi: multi, + auto: auto, + compound: compound, + src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) + }; +} +function nameFromKeyPath(keyPath) { + return typeof keyPath === 'string' ? + keyPath : + keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; +} + +function createTableSchema(name, primKey, indexes) { + return { + name: name, + primKey: primKey, + indexes: indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }) + }; +} + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} +var getMaxKey = function (IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + getMaxKey = function () { return [[]]; }; + return [[]]; + } + catch (e) { + getMaxKey = function () { return maxString; }; + return maxString; + } +}; + +function getKeyExtractor(keyPath) { + if (keyPath == null) { + return function () { return undefined; }; + } + else if (typeof keyPath === 'string') { + return getSinglePathKeyExtractor(keyPath); + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } +} +function getSinglePathKeyExtractor(keyPath) { + var split = keyPath.split('.'); + if (split.length === 1) { + return function (obj) { return obj[keyPath]; }; + } + else { + return function (obj) { return getByKeyPath(obj, keyPath); }; + } +} + +function arrayify(arrayLike) { + return [].slice.call(arrayLike); +} +var _id_counter = 0; +function getKeyPathAlias(keyPath) { + return keyPath == null ? + ":id" : + typeof keyPath === 'string' ? + keyPath : + "[".concat(keyPath.join('+'), "]"); +} +function createDBCore(db, IdbKeyRange, tmpTrans) { + function extractSchema(db, trans) { + var tables = arrayify(db.objectStoreNames); + return { + schema: { + name: db.name, + tables: tables.map(function (table) { return trans.objectStore(table); }).map(function (store) { + var keyPath = store.keyPath, autoIncrement = store.autoIncrement; + var compound = isArray(keyPath); + var outbound = keyPath == null; + var indexByKeyPath = {}; + var result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound: outbound, + compound: compound, + keyPath: keyPath, + autoIncrement: autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(function (indexName) { return store.index(indexName); }) + .map(function (index) { + var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath = index.keyPath; + var compound = isArray(keyPath); + var result = { + name: name, + compound: compound, + keyPath: keyPath, + unique: unique, + multiEntry: multiEntry, + extractKey: getKeyExtractor(keyPath) + }; + indexByKeyPath[getKeyPathAlias(keyPath)] = result; + return result; + }), + getIndexByKeyPath: function (keyPath) { return indexByKeyPath[getKeyPathAlias(keyPath)]; } + }; + indexByKeyPath[":id"] = result.primaryKey; + if (keyPath != null) { + indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; + } + return result; + }) + }, + hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && + !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) + }; + } + function makeIDBKeyRange(range) { + if (range.type === 3 ) + return null; + if (range.type === 4 ) + throw new Error("Cannot convert never type to IDBKeyRange"); + var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; + var idbRange = lower === undefined ? + upper === undefined ? + null : + IdbKeyRange.upperBound(upper, !!upperOpen) : + upper === undefined ? + IdbKeyRange.lowerBound(lower, !!lowerOpen) : + IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); + return idbRange; + } + function createDbCoreTable(tableSchema) { + var tableName = tableSchema.name; + function mutate(_a) { + var trans = _a.trans, type = _a.type, keys = _a.keys, values = _a.values, range = _a.range; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var outbound = store.keyPath == null; + var isAddOrPut = type === "put" || type === "add"; + if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') + throw new Error("Invalid operation type: " + type); + var length = (keys || values || { length: 1 }).length; + if (keys && values && keys.length !== values.length) { + throw new Error("Given keys array must have same length as given values array."); + } + if (length === 0) + return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); + var req; + var reqs = []; + var failures = []; + var numFailures = 0; + var errorHandler = function (event) { + ++numFailures; + preventDefault(event); + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures: numFailures, failures: failures, results: [], lastResult: undefined }); + if (range.type === 3 ) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } + else { + var _a = isAddOrPut ? + outbound ? + [values, keys] : + [values, null] : + [keys, null], args1 = _a[0], args2 = _a[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + reqs.push(req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i]))); + req.onerror = errorHandler; + } + } + else { + for (var i = 0; i < length; ++i) { + reqs.push(req = store[type](args1[i])); + req.onerror = errorHandler; + } + } + } + var done = function (event) { + var lastResult = event.target.result; + reqs.forEach(function (req, i) { return req.error != null && (failures[i] = req.error); }); + resolve({ + numFailures: numFailures, + failures: failures, + results: type === "delete" ? keys : reqs.map(function (req) { return req.result; }), + lastResult: lastResult + }); + }; + req.onerror = function (event) { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor(_a) { + var trans = _a.trans, values = _a.values, query = _a.query, reverse = _a.reverse, unique = _a.unique; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? + store : + store.index(index.name); + var direction = reverse ? + unique ? + "prevunique" : + "prev" : + unique ? + "nextunique" : + "next"; + var req = values || !('openKeyCursor' in source) ? + source.openCursor(makeIDBKeyRange(range), direction) : + source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function (ev) { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + var _cursorContinue = cursor.continue.bind(cursor); + var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + var _cursorAdvance = cursor.advance.bind(cursor); + var doThrowCursorIsNotStarted = function () { throw new Error("Cursor not started"); }; + var doThrowCursorIsStopped = function () { throw new Error("Cursor not stopped"); }; + cursor.trans = trans; + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; + cursor.fail = wrap(reject); + cursor.next = function () { + var _this = this; + var gotOne = 1; + return this.start(function () { return gotOne-- ? _this.continue() : _this.stop(); }).then(function () { return _this; }); + }; + cursor.start = function (callback) { + var iterationPromise = new Promise(function (resolveIteration, rejectIteration) { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = function (value) { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + var guardedCallback = function () { + if (req.result) { + try { + callback(); + } + catch (err) { + cursor.fail(err); + } + } + else { + cursor.done = true; + cursor.start = function () { throw new Error("Cursor behind last entry"); }; + cursor.stop(); + } + }; + req.onsuccess = wrap(function (ev) { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll) { + return function (request) { + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var trans = request.trans, values = request.values, limit = request.limit, query = request.query; + var nonInfinitLimit = limit === Infinity ? undefined : limit; + var index = query.index, range = query.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasGetAll) { + var req = values ? + source.getAll(idbKeyRange, nonInfinitLimit) : + source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = function (event) { return resolve({ result: event.target.result }); }; + req.onerror = eventRejectHandler(reject); + } + else { + var count_1 = 0; + var req_1 = values || !('openKeyCursor' in source) ? + source.openCursor(idbKeyRange) : + source.openKeyCursor(idbKeyRange); + var result_1 = []; + req_1.onsuccess = function (event) { + var cursor = req_1.result; + if (!cursor) + return resolve({ result: result_1 }); + result_1.push(values ? cursor.value : cursor.primaryKey); + if (++count_1 === limit) + return resolve({ result: result_1 }); + cursor.continue(); + }; + req_1.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate: mutate, + getMany: function (_a) { + var trans = _a.trans, keys = _a.keys; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var req; + var successHandler = function (event) { + var req = event.target; + if ((result[req._pos] = req.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys[i]; + if (key != null) { + req = store.get(keys[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get: function (_a) { + var trans = _a.trans, key = _a.key; + return new Promise(function (resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var req = store.get(key); + req.onsuccess = function (event) { return resolve(event.target.result); }; + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll), + openCursor: openCursor, + count: function (_a) { + var query = _a.query, trans = _a.trans; + var index = query.index, range = query.range; + return new Promise(function (resolve, reject) { + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(function (ev) { return resolve(ev.target.result); }); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + var _a = extractSchema(db, tmpTrans), schema = _a.schema, hasGetAll = _a.hasGetAll; + var tables = schema.tables.map(function (tableSchema) { return createDbCoreTable(tableSchema); }); + var tableMap = {}; + tables.forEach(function (table) { return tableMap[table.name] = table; }); + return { + stack: "dbcore", + transaction: db.transaction.bind(db), + table: function (name) { + var result = tableMap[name]; + if (!result) + throw new Error("Table '".concat(name, "' not found")); + return tableMap[name]; + }, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema: schema + }; +} + +function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce(function (down, _a) { + var create = _a.create; + return (__assign(__assign({}, down), create(down))); + }, stackImpl); +} +function createMiddlewareStacks(middlewares, idbdb, _a, tmpTrans) { + var IDBKeyRange = _a.IDBKeyRange; _a.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore: dbcore + }; +} +function generateMiddlewareStacks(db, tmpTrans) { + var idbdb = tmpTrans.db; + var stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); + db.core = stacks.dbcore; + db.tables.forEach(function (table) { + var tableName = table.name; + if (db.core.schema.tables.some(function (tbl) { return tbl.name === tableName; })) { + table.core = db.core.table(tableName); + if (db[tableName] instanceof db.Table) { + db[tableName].core = table.core; + } + } + }); +} + +function setApiOnPlace(db, objs, tableNames, dbschema) { + tableNames.forEach(function (tableName) { + var schema = dbschema[tableName]; + objs.forEach(function (obj) { + var propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { + if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { + setProp(obj, tableName, { + get: function () { return this.table(tableName); }, + set: function (value) { + defineProperty(this, tableName, { value: value, writable: true, configurable: true, enumerable: true }); + } + }); + } + else { + obj[tableName] = new db.Table(tableName, schema); + } + } + }); + }); +} +function removeTablesApi(db, objs) { + objs.forEach(function (obj) { + for (var key in obj) { + if (obj[key] instanceof db.Table) + delete obj[key]; + } + }); +} +function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; +} +function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { + var globalSchema = db._dbSchema; + var trans = db._createTransaction('readwrite', db._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + var transless = PSD.transless || PSD; + newScope(function () { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(function (tableName) { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db, idbUpgradeTrans); + DexiePromise.follow(function () { return db.on.populate.fire(trans); }).catch(rejectTransaction); + } + else + updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction); + }); +} +function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { + var queue = []; + var versions = db._versions; + var globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); + 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(db, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); + globalSchema = db._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(function (tuple) { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(function (change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + var store_1 = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(function (idx) { return addIndex(store_1, idx); }); + change.change.forEach(function (idx) { + store_1.deleteIndex(idx.name); + addIndex(store_1, idx); + }); + change.del.forEach(function (idxName) { return store_1.deleteIndex(idxName); }); + } + }); + var contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db, idbUpgradeTrans); + trans._memoizedTables = {}; + anyContentUpgraderHasRun = true; + var upgradeSchema_1 = shallowClone(newSchema); + diff.del.forEach(function (table) { + upgradeSchema_1[table] = oldSchema[table]; + }); + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); + trans.schema = upgradeSchema_1; + var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync_1) { + incrementExpectedAwaits(); + } + var returnValue_1; + var promiseFollowed = DexiePromise.follow(function () { + returnValue_1 = contentUpgrade(trans); + if (returnValue_1) { + if (contentUpgradeIsAsync_1) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue_1.then(decrementor, decrementor); + } + } + }); + return (returnValue_1 && typeof returnValue_1.then === 'function' ? + DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function () { return returnValue_1; })); + } + }); + queue.push(function (idbtrans) { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + var newSchema = version._cfg.dbschema; + deleteRemovedTables(newSchema, idbtrans); + } + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); + trans.schema = db._dbSchema; + }); + }); + function runQueue() { + return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + DexiePromise.resolve(); + } + return runQueue().then(function () { + createMissingTables(globalSchema, idbUpgradeTrans); + }); +} +function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] + }; + var table; + for (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.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || + (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) + { + change.recreate = true; + diff.change.push(change); + } + else { + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + var idxName = void 0; + for (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) { return 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) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(function (storeName) { + return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); + }); +} +function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); +} +function buildGlobalSchema(db, idbdb, tmpTrans) { + var globalSchema = {}; + var dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(function (storeName) { + var store = tmpTrans.objectStore(storeName); + var keyPath = store.keyPath; + var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); + indexes.push(index); + } + globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); + }); + return globalSchema; +} +function readGlobalSchema(db, idbdb, tmpTrans) { + db.verno = idbdb.version / 10; + var globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); + db._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); +} +function verifyInstalledSchema(db, tmpTrans) { + var installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); + var diff = getSchemaDiff(installedSchema, db._dbSchema); + return !(diff.add.length || diff.change.some(function (ch) { return ch.add.length || ch.change.length; })); +} +function adjustToExistingIndexNames(db, schema, idbtrans) { + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + db._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; + delete schema[storeName].idxByName[dexieName]; + schema[storeName].idxByName[indexName] = indexSpec; + } + } + } + } + if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + db._hasGetAll = false; + } +} +function parseIndexSyntax(primKeyAndIndexes) { + return primKeyAndIndexes.split(',').map(function (index, indexNum) { + index = index.trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); + }); +} + +var Version = (function () { + function Version() { + } + Version.prototype._parseStoresSpec = function (stores, outSchema) { + keys(stores).forEach(function (tableName) { + if (stores[tableName] !== null) { + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + 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"); + }); + outSchema[tableName] = createTableSchema(tableName, primKey, indexes); + } + }); + }; + Version.prototype.stores = function (stores) { + var db = this.db; + this._cfg.storesSource = this._cfg.storesSource ? + extend(this._cfg.storesSource, stores) : + stores; + var versions = db._versions; + var storesSpec = {}; + var dbschema = {}; + versions.forEach(function (version) { + extend(storesSpec, version._cfg.storesSource); + dbschema = (version._cfg.dbschema = {}); + version._parseStoresSpec(storesSpec, dbschema); + }); + db._dbSchema = dbschema; + removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); + setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + db._storeNames = keys(dbschema); + return this; + }; + Version.prototype.upgrade = function (upgradeFunction) { + this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + }; + return Version; +}()); + +function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); +} + +function getDbNamesTable(indexedDB, IDBKeyRange) { + var dbNamesDB = indexedDB["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB: indexedDB, + IDBKeyRange: IDBKeyRange, + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); +} +function hasDatabasesNative(indexedDB) { + return indexedDB && typeof indexedDB.databases === "function"; +} +function getDatabaseNames(_a) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + return hasDatabasesNative(indexedDB) + ? Promise.resolve(indexedDB.databases()).then(function (infos) { + return infos + .map(function (info) { return info.name; }) + .filter(function (name) { return name !== DBNAMES_DB; }); + }) + : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); +} +function _onDatabaseCreated(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).put({ name: name }).catch(nop); +} +function _onDatabaseDeleted(_a, name) { + var indexedDB = _a.indexedDB, IDBKeyRange = _a.IDBKeyRange; + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); +} + +function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); +} + +function idbReady() { + var isSafari = !navigator.userAgentData && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function (resolve) { + var tryIdb = function () { return indexedDB.databases().finally(resolve); }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function () { return clearInterval(intervalId); }); +} + +var _a; +function isEmptyRange(node) { + return !("from" in node); +} +var RangeSet = function (fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + var rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } +}; +props(RangeSet.prototype, (_a = { + add: function (rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey: function (key) { + addRange(this, key, key); + return this; + }, + addKeys: function (keys) { + var _this = this; + keys.forEach(function (key) { return addRange(_this, key, key); }); + return this; + } + }, + _a[iteratorSymbol] = function () { + return getRangeSetIterator(this); + }, + _a)); +function addRange(target, from, to) { + var diff = cmp(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from: from, to: to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges(target, left); + } + if (right && rightWasCutOff) { + mergeRanges(target, right); + } +} +function mergeRanges(target, newSet) { + function _addRangeSet(target, _a) { + var from = _a.from, to = _a.to, l = _a.l, r = _a.r; + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); +} +function rangesOverlap(rangeSet1, rangeSet2) { + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) + : (b = (nextResult2 = i2.next(a.from)).value); + } + return false; +} +function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function (key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; +} +function rebalance(target) { + var _a, _b; + var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + var l = r === "r" ? "l" : "r"; + var rootClone = __assign({}, target); + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); +} +function computeDepth(_a) { + var r = _a.r, l = _a.l; + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; +} + +function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(function (part) { + if (target[part]) + mergeRanges(target[part], newSet[part]); + else + target[part] = cloneSimpleObjectTree(newSet[part]); + }); + return target; +} + +function obsSetsOverlap(os1, os2) { + return Object.keys(os1).some(function (key) { return os2[key] && rangesOverlap(os2[key], os1[key]); }); +} + +var cache = {}; + +var unsignaledParts = {}; +var isTaskEnqueued = false; +function signalSubscribersLazily(part) { + extendObservabilitySet(unsignaledParts, part); + if (!isTaskEnqueued) { + isTaskEnqueued = true; + setTimeout(function () { + isTaskEnqueued = false; + var parts = unsignaledParts; + unsignaledParts = {}; + signalSubscribersNow(parts); + }, 0); + } +} +function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { + if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; } + var queriesToSignal = new Set(); + for (var key in updatedParts) { + var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); + if (parts) { + var dbName = parts[1], tableName = parts[2]; + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (tblCache) + signalTableSubscribersNow(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); + } + } + queriesToSignal.forEach(function (requery) { return requery(); }); +} +function signalTableSubscribersNow(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { + var updatedEntryLists = deleteAffectedCacheEntries && []; + for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) { + var _b = _a[_i], indexName = _b[0], entries = _b[1]; + var filteredEntries = deleteAffectedCacheEntries && []; + for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { + var entry = entries_1[_c]; + if (entry.obsSet && obsSetsOverlap(updatedParts, entry.obsSet)) { + entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); }); + } + else if (deleteAffectedCacheEntries) { + filteredEntries.push(entry); + } + } + if (deleteAffectedCacheEntries) + updatedEntryLists.push([indexName, filteredEntries]); + } + if (deleteAffectedCacheEntries) { + for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { + var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; + tblCache.queries.query[indexName] = filteredEntries; + } + } +} + +function dexieOpen(db) { + var state = db._state; + var indexedDB = db._deps.indexedDB; + if (state.isBeingOpened || db.idbdb) + return state.dbReadyPromise.then(function () { return state.dbOpenError ? + rejection(state.dbOpenError) : + db; }); + debug && (state.openCanceller._stackHolder = getErrorWithStack()); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + var openCanceller = state.openCanceller; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed('db.open() was cancelled'); + } + var resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null, wasCreated = false; + return DexiePromise.race([openCanceller, (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(function () { return new DexiePromise(function (resolve, reject) { + throwIfCancelled(); + if (!indexedDB) + throw new exceptions.MissingAPI(); + var dbName = db.name; + var req = state.autoSchema ? + indexedDB.open(dbName) : + indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI(); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db._fireOnBlocked); + req.onupgradeneeded = wrap(function (e) { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + var delreq = indexedDB.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(function () { + reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + wasCreated = oldVer < 1; + db.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function () { + upgradeTransaction = null; + var idbdb = db.idbdb = req.result; + var objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); + if (state.autoSchema) + readGlobalSchema(db, idbdb, tmpTrans); + else { + adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); + if (!verifyInstalledSchema(db, tmpTrans)) { + console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail."); + } + } + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(function (ev) { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(function (ev) { + db.on("close").fire(ev); + }); + if (wasCreated) + _onDatabaseCreated(db._deps, dbName); + resolve(); + }, reject); + }); })]).then(function () { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return db.on.ready.fire(db.vip); })).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function () { return remainders_1(db.vip); })).then(fireRemainders); + } + }); + }).finally(function () { + if (state.openCanceller === openCanceller) { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + } + }).catch(function (err) { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (_a) { } + if (openCanceller === state.openCanceller) { + db._close(); + } + return rejection(err); + }).finally(function () { + state.openComplete = true; + resolveDbReady(); + }).then(function () { + if (wasCreated) { + var everything_1 = {}; + db.tables.forEach(function (table) { + table.schema.indexes.forEach(function (idx) { + if (idx.name) + everything_1["idb://".concat(db.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet(-Infinity, [[[]]]); + }); + everything_1["idb://".concat(db.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db.name, "/").concat(table.name, "/:dels")] = new RangeSet(-Infinity, [[[]]]); + }); + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); + signalSubscribersNow(everything_1, true); + } + return db; + }); +} + +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)(); +} + +function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + scopeFunc = args.pop(); + var tables = flatten(args); + return [mode, tables, scopeFunc]; +} +function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { + return DexiePromise.resolve().then(function () { + var transless = PSD.transless || PSD; + var trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); + trans.explicit = true; + var zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } + else { + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(function () { return enterTransactionScope(db, mode, storeNames, null, scopeFunc); }); + } + return rejection(ex); + } + } + var scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = DexiePromise.follow(function () { + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (scopeFuncIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue).then(function (x) { return trans.active ? + x + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); }) + : promiseFollowed.then(function () { return returnValue; })).then(function (x) { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(function () { return x; }); + }).catch(function (e) { + trans._reject(e); + return rejection(e); + }); + }); +} + +function pad(a, value, count) { + var result = isArray(a) ? a.slice() : [a]; + for (var i = 0; i < count; ++i) + result.push(value); + return result; +} +function createVirtualIndexMiddleware(down) { + return __assign(__assign({}, down), { table: function (tableName) { + var table = down.table(tableName); + var schema = table.schema; + var indexLookup = {}; + var allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + var keyPathAlias = getKeyPathAlias(keyPath); + var indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); + var keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; + var isVirtual = keyTail > 0; + var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual + ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") + : lowLevelIndex.name, lowLevelIndex: lowLevelIndex, isVirtual: isVirtual, keyTail: keyTail, keyLength: keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + var virtualKeyPath = keyLength === 2 ? + keyPath[0] : + keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort(function (a, b) { return a.keyTail - b.keyTail; }); + return virtualIndex; + } + var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) { + var index = _a[_i]; + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + var result = indexLookup[getKeyPathAlias(keyPath)]; + return result && result[0]; + } + function translateRange(range, keyTail) { + return { + type: range.type === 1 ? + 2 : + range.type, + lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), + lowerOpen: true, + upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), + upperOpen: true + }; + } + function translateRequest(req) { + var index = req.query.index; + return index.isVirtual ? __assign(__assign({}, req), { query: { + index: index.lowLevelIndex, + range: translateRange(req.query.range, index.keyTail) + } }) : req; + } + var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey: primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function (req) { + return table.count(translateRequest(req)); + }, query: function (req) { + return table.query(translateRequest(req)); + }, openCursor: function (req) { + var _a = req.query.index, keyTail = _a.keyTail, isVirtual = _a.isVirtual, keyLength = _a.keyLength; + if (!isVirtual) + return table.openCursor(req); + function createVirtualCursor(cursor) { + function _continue(key) { + key != null ? + cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : + req.unique ? + cursor.continue(cursor.key.slice(0, keyLength) + .concat(req.reverse + ? down.MIN_KEY + : down.MAX_KEY, keyTail)) : + cursor.continue(); + } + var virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value: function (key, primaryKey) { + cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); + } + }, + primaryKey: { + get: function () { + return cursor.primaryKey; + } + }, + key: { + get: function () { + var key = cursor.key; + return keyLength === 1 ? + key[0] : + key.slice(0, keyLength); + } + }, + value: { + get: function () { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)) + .then(function (cursor) { return cursor && createVirtualCursor(cursor); }); + } }); + return result; + } }); +} +var virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware +}; + +function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach(function (prop) { + if (!hasOwn(b, prop)) { + rv[prfx + prop] = undefined; + } + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { + var apTypeName = toStringTag(ap); + var bpTypeName = toStringTag(bp); + if (apTypeName !== bpTypeName) { + rv[prfx + prop] = b[prop]; + } + else if (apTypeName === 'Object') { + getObjectDiff(ap, bp, rv, prfx + prop + '.'); + } + else if (ap !== bp) { + rv[prfx + prop] = b[prop]; + } + } + else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach(function (prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; +} + +function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); +} + +var hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: function (downCore) { return (__assign(__assign({}, downCore), { table: function (tableName) { + var downTable = downCore.table(tableName); + var primaryKey = downTable.schema.primaryKey; + var tableMiddleware = __assign(__assign({}, downTable), { mutate: function (req) { + var dxTrans = PSD.trans; + var _a = dxTrans.table(tableName).hook, deleting = _a.deleting, creating = _a.creating, updating = _a.updating; + switch (req.type) { + case 'add': + if (creating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'put': + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'delete': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return addPutOrDelete(req); }, true); + case 'deleteRange': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', function () { return deleteRange(req); }, true); + } + return downTable.mutate(req); + function addPutOrDelete(req) { + var dxTrans = PSD.trans; + var keys = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req); + if (req.type !== 'delete') + req.values = __spreadArray([], req.values, true); + if (req.keys) + req.keys = __spreadArray([], req.keys, true); + return getExistingValues(downTable, req, keys).then(function (existingValues) { + var contexts = keys.map(function (key, i) { + var existingValue = existingValues[i]; + var ctx = { onerror: null, onsuccess: null }; + if (req.type === 'delete') { + deleting.fire.call(ctx, key, existingValue, dxTrans); + } + else if (req.type === 'add' || existingValue === undefined) { + var generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); + if (key == null && generatedPrimaryKey != null) { + key = generatedPrimaryKey; + req.keys[i] = key; + if (!primaryKey.outbound) { + setByKeyPath(req.values[i], primaryKey.keyPath, key); + } + } + } + else { + var objectDiff = getObjectDiff(existingValue, req.values[i]); + var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); + if (additionalChanges_1) { + var requestedValue_1 = req.values[i]; + Object.keys(additionalChanges_1).forEach(function (keyPath) { + if (hasOwn(requestedValue_1, keyPath)) { + requestedValue_1[keyPath] = additionalChanges_1[keyPath]; + } + else { + setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); + } + }); + } + } + return ctx; + }); + return downTable.mutate(req).then(function (_a) { + var failures = _a.failures, results = _a.results, numFailures = _a.numFailures, lastResult = _a.lastResult; + for (var i = 0; i < keys.length; ++i) { + var primKey = results ? results[i] : keys[i]; + var ctx = contexts[i]; + if (primKey == null) { + ctx.onerror && ctx.onerror(failures[i]); + } + else { + ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? + req.values[i] : + primKey + ); + } + } + return { failures: failures, results: results, numFailures: numFailures, lastResult: lastResult }; + }).catch(function (error) { + contexts.forEach(function (ctx) { return ctx.onerror && ctx.onerror(error); }); + return Promise.reject(error); + }); + }); + } + function deleteRange(req) { + return deleteNextChunk(req.trans, req.range, 10000); + } + function deleteNextChunk(trans, range, limit) { + return downTable.query({ trans: trans, values: false, query: { index: primaryKey, range: range }, limit: limit }) + .then(function (_a) { + var result = _a.result; + return addPutOrDelete({ type: 'delete', keys: result, trans: trans }).then(function (res) { + if (res.numFailures > 0) + return Promise.reject(res.failures[0]); + if (result.length < limit) { + return { failures: [], numFailures: 0, lastResult: undefined }; + } + else { + return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); + } + }); + }); + } + } }); + return tableMiddleware; + } })); } +}; +function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" + ? Promise.resolve([]) + : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); +} + +function getFromTransactionCache(keys, cache, clone) { + try { + if (!cache) + return null; + if (cache.keys.length < keys.length) + return null; + var result = []; + for (var i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { + if (cmp(cache.keys[i], keys[j]) !== 0) + continue; + result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); + ++j; + } + return result.length === keys.length ? result : null; + } + catch (_a) { + return null; + } +} +var cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: function (core) { + return { + table: function (tableName) { + var table = core.table(tableName); + return __assign(__assign({}, table), { getMany: function (req) { + if (!req.cache) { + return table.getMany(req); + } + var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then(function (res) { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res, + }; + return res; + }); + }, mutate: function (req) { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + } }); + }, + }; + }, +}; + +function isCachableContext(ctx, table) { + return (ctx.trans.mode === 'readonly' && + !!ctx.subscr && + !ctx.trans.explicit && + ctx.trans.db._options.cache !== 'disabled' && + !table.schema.primaryKey.outbound); +} + +function isCachableRequest(type, req) { + switch (type) { + case 'query': + return req.values && !req.unique; + case 'get': + return false; + case 'getMany': + return false; + case 'count': + return false; + case 'openCursor': + return false; + } +} + +var observabilityMiddleware = { + stack: "dbcore", + level: 0, + name: "Observability", + create: function (core) { + var dbName = core.schema.name; + var FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); + return __assign(__assign({}, core), { transaction: function (stores, mode, options) { + if (PSD.subscr && mode !== 'readonly') { + throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); + } + return core.transaction(stores, mode, options); + }, table: function (tableName) { + var table = core.table(tableName); + var schema = table.schema; + var primaryKey = schema.primaryKey; + var extractKey = primaryKey.extractKey, outbound = primaryKey.outbound; + var tableClone = __assign(__assign({}, table), { mutate: function (req) { + var trans = req.trans; + var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); + var getRangeSet = function (indexName) { + var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); + return (mutatedParts[part] || + (mutatedParts[part] = new RangeSet())); + }; + var pkRangeSet = getRangeSet(""); + var delsRangeSet = getRangeSet(":dels"); + var type = req.type; + var _a = req.type === "deleteRange" + ? [req.range] + : req.type === "delete" + ? [req.keys] + : req.values.length < 50 + ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values] + : [], keys = _a[0], newObjs = _a[1]; + var oldCache = req.trans["_cache"]; + if (isArray(keys)) { + pkRangeSet.addKeys(keys); + var oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null; + if (!oldObjs && type !== "add") { + delsRangeSet.addKeys(keys); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } + else if (keys) { + var range = { from: keys.lower, to: keys.upper }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } + else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(function (idx) { return getRangeSet(idx.name).add(FULL_RANGE); }); + } + return table.mutate(req).then(function (res) { + if (keys && (req.type === 'add' || req.type === 'put')) { + pkRangeSet.addKeys(res.results); + } + trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); + return res; + }); + } }); + var getRange = function (_a) { + var _b, _c; + var _d = _a.query, index = _d.index, range = _d.range; + return [ + index, + new RangeSet((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY), + ]; + }; + var readSubscribers = { + get: function (req) { return [primaryKey, new RangeSet(req.key)]; }, + getMany: function (req) { return [primaryKey, new RangeSet().addKeys(req.keys)]; }, + count: getRange, + query: getRange, + openCursor: getRange, + }; + keys(readSubscribers).forEach(function (method) { + tableClone[method] = function (req) { + var subscr = PSD.subscr; + var isLiveQuery = !!subscr; + var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); + var obsSet = cachable + ? req.obsSet = {} + : subscr; + if (isLiveQuery) { + var getRangeSet = function (indexName) { + var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); + return (obsSet[part] || + (obsSet[part] = new RangeSet())); + }; + var pkRangeSet_1 = getRangeSet(""); + var delsRangeSet_1 = getRangeSet(":dels"); + var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1]; + getRangeSet(queriedIndex.name || "").add(queriedRanges); + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet_1.add(FULL_RANGE); + } + else { + var keysPromise_1 = method === "query" && + outbound && + req.values && + table.query(__assign(__assign({}, req), { values: false })); + return table[method].apply(this, arguments).then(function (res) { + if (method === "query") { + if (outbound && req.values) { + return keysPromise_1.then(function (_a) { + var resultingKeys = _a.result; + pkRangeSet_1.addKeys(resultingKeys); + return res; + }); + } + var pKeys = req.values + ? res.result.map(extractKey) + : res.result; + if (req.values) { + pkRangeSet_1.addKeys(pKeys); + } + else { + delsRangeSet_1.addKeys(pKeys); + } + } + else if (method === "openCursor") { + var cursor_1 = res; + var wantValues_1 = req.values; + return (cursor_1 && + Object.create(cursor_1, { + key: { + get: function () { + delsRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.key; + }, + }, + primaryKey: { + get: function () { + var pkey = cursor_1.primaryKey; + delsRangeSet_1.addKey(pkey); + return pkey; + }, + }, + value: { + get: function () { + wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.value; + }, + }, + })); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + } }); + }, +}; +function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + var rangeSet = getRangeSet(ix.name || ""); + function extractKey(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + var addKeyOrKeys = function (key) { return ix.multiEntry && isArray(key) + ? key.forEach(function (key) { return rangeSet.addKey(key); }) + : rangeSet.addKey(key); }; + (oldObjs || newObjs).forEach(function (_, i) { + var oldKey = oldObjs && extractKey(oldObjs[i]); + var newKey = newObjs && extractKey(newObjs[i]); + if (cmp(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); +} + +function isAboveLower(key, range) { + return range.lower === undefined + ? true + : range.lowerOpen + ? cmp(key, range.lower) > 0 + : cmp(key, range.lower) >= 0; +} +function isBelowUpper(key, range) { + return range.upper === undefined + ? true + : range.upperOpen + ? cmp(key, range.upper) < 0 + : cmp(key, range.upper) <= 0; +} +function isWithinRange(key, range) { + return isAboveLower(key, range) && isBelowUpper(key, range); +} + +function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { + if (!ops || ops.length === 0) + return result; + var index = req.query.index; + var primaryKey = table.schema.primaryKey; + var extractPrimKey = primaryKey.extractKey; + var extractIndex = index.extractKey; + var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; + var finalResult = ops.reduce(function (result, op) { + var modifedResult = result; + var includedValues = op.type === 'add' || op.type === 'put' + ? op.values.filter(function (v) { + return isWithinRange(extractIndex(v), req.query.range); + }).map(function (v) { + v = deepClone(v); + if (immutable) + Object.freeze(v); + return v; + }) + : []; + switch (op.type) { + case 'add': + modifedResult = result.concat(req.values + ? includedValues + : includedValues.map(function (v) { return extractPrimKey(v); })); + break; + case 'put': + var keySet_1 = new RangeSet().addKeys(op.values.map(function (v) { return extractPrimKey(v); })); + modifedResult = result + .filter(function (item) { + var key = req.values ? extractPrimKey(item) : item; + return !rangesOverlap(new RangeSet(key), keySet_1); + }) + .concat(req.values + ? includedValues + : includedValues.map(function (v) { return extractPrimKey(v); })); + break; + case 'delete': + var keysToDelete_1 = new RangeSet().addKeys(op.keys); + modifedResult = result.filter(function (item) { + var key = req.values ? extractPrimKey(item) : item; + return !rangesOverlap(new RangeSet(key), keysToDelete_1); + }); + break; + case 'deleteRange': + var range_1 = op.range; + modifedResult = result.filter(function (item) { return !isWithinRange(extractPrimKey(item), range_1); }); + break; + } + return modifedResult; + }, result); + if (finalResult === result) + return result; + finalResult.sort(function (a, b) { + return cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) || + cmp(extractPrimKey(a), extractPrimKey(b)); + }); + if (req.limit && req.limit < Infinity) { + if (finalResult.length > req.limit) { + finalResult.length = req.limit; + } + else if (result.length === req.limit && finalResult.length < req.limit) { + cacheEntry.dirty = true; + } + } + return immutable ? Object.freeze(finalResult) : finalResult; +} + +function areRangesEqual(r1, r2) { + return (cmp(r1.lower, r2.lower) === 0 && + cmp(r1.upper, r2.upper) === 0 && + !!r1.lowerOpen === !!r2.lowerOpen && + !!r1.upperOpen === !!r2.upperOpen); +} + +function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { + if (lower1 === undefined) + return lower2 !== undefined ? -1 : 0; + if (lower2 === undefined) + return 1; + var c = cmp(lower1, lower2); + if (c === 0) { + if (lowerOpen1 && lowerOpen2) + return 0; + if (lowerOpen1) + return 1; + if (lowerOpen2) + return -1; + } + return c; +} +function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { + if (upper1 === undefined) + return upper2 !== undefined ? 1 : 0; + if (upper2 === undefined) + return -1; + var c = cmp(upper1, upper2); + if (c === 0) { + if (upperOpen1 && upperOpen2) + return 0; + if (upperOpen1) + return -1; + if (upperOpen2) + return 1; + } + return c; +} +function isSuperRange(r1, r2) { + return (compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && + compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0); +} + +function findCompatibleQuery(dbName, tableName, type, req) { + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (!tblCache) + return []; + var queries = tblCache.queries[type]; + if (!queries) + return [null, false, tblCache, null]; + var indexName = req.query ? req.query.index.name : null; + var entries = queries[indexName || '']; + if (!entries) + return [null, false, tblCache, null]; + switch (type) { + case 'query': + var equalEntry = entries.find(function (entry) { + return entry.req.limit === req.limit && + entry.req.values === req.values && + areRangesEqual(entry.req.query.range, req.query.range); + }); + if (equalEntry) + return [ + equalEntry, + true, + tblCache, + entries, + ]; + var superEntry = entries.find(function (entry) { + var limit = 'limit' in entry.req ? entry.req.limit : Infinity; + return (limit >= req.limit && + (req.values ? entry.req.values : true) && + isSuperRange(entry.req.query.range, req.query.range)); + }); + return [superEntry, false, tblCache, entries]; + case 'count': + var countQuery = entries.find(function (entry) { + return areRangesEqual(entry.req.query.range, req.query.range); + }); + return [countQuery, !!countQuery, tblCache, entries]; + } +} + +function subscribeToCacheEntry(cacheEntry, container, requery, signal) { + cacheEntry.subscribers.add(requery); + signal.addEventListener("abort", function () { + cacheEntry.subscribers.delete(requery); + if (cacheEntry.subscribers.size === 0) { + enqueForDeletion(cacheEntry, container); + } + }); +} +function enqueForDeletion(cacheEntry, container) { + setTimeout(function () { + if (cacheEntry.subscribers.size === 0) { + delArrayItem(container, cacheEntry); + } + }, 3000); +} + +var cacheMiddleware = { + stack: 'dbcore', + level: 0, + name: 'Cache', + create: function (core) { + var dbName = core.schema.name; + var coreMW = __assign(__assign({}, core), { transaction: function (stores, mode, options) { + var idbtrans = core.transaction(stores, mode, options); + if (mode === 'readwrite') { + var ac_1 = new AbortController(); + var signal = ac_1.signal; + var endTransaction = function (wasCommitted) { return function () { + ac_1.abort(); + if (mode === 'readwrite') { + var affectedSubscribers_1 = new Set(); + for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { + var storeName = stores_1[_i]; + var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; + var table = core.table(storeName); + if (tblCache) { + var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; }); + if (ops.length > 0) { + tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; }); + for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) { + var entries = _b[_a]; + for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { + var entry = _d[_c]; + if (entry.res != null && + idbtrans.mutatedParts +) { + if (wasCommitted && !entry.dirty) { + var freezeResults = Object.isFrozen(entry.res); + var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); + if (entry.dirty) { + delArrayItem(entries, entry); + entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); + } + else if (modRes !== entry.res) { + entry.res = modRes; + entry.promise = DexiePromise.resolve({ result: modRes }); + } + } + else { + if (entry.dirty) { + delArrayItem(entries, entry); + } + entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); }); + } + } + } + } + } + } + } + affectedSubscribers_1.forEach(function (requery) { return requery(); }); + } + }; }; + idbtrans.addEventListener('abort', endTransaction(false), { + signal: signal, + }); + idbtrans.addEventListener('error', endTransaction(false), { + signal: signal, + }); + idbtrans.addEventListener('complete', endTransaction(true), { + signal: signal, + }); + } + return idbtrans; + }, table: function (tableName) { + var downTable = core.table(tableName); + var primKey = downTable.schema.primaryKey; + var tableMW = __assign(__assign({}, downTable), { mutate: function (req) { + if (primKey.outbound || + PSD.trans.db._options.cache === 'disabled' + ) { + return downTable.mutate(req); + } + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (!tblCache) + return downTable.mutate(req); + var promise = downTable.mutate(req); + if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function (key) { return key == null; }))) { + promise.then(function (res) { + var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function (value, i) { + var valueWithKey = primKey.keyPath.includes('.') + ? deepClone(value) + : __assign({}, value); + setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); + return valueWithKey; + }) }); + tblCache.optimisticOps.push(reqWithResolvedKeys); + queueMicrotask(function () { return signalSubscribersLazily(req.mutatedParts); }); + }); + } + else { + tblCache.optimisticOps.push(req); + signalSubscribersLazily(req.mutatedParts); + promise.catch(function () { + delArrayItem(tblCache.optimisticOps, req); + signalSubscribersLazily(req.mutatedParts); + }); + } + return promise; + }, query: function (req) { + if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) + return downTable.query(req); + var freezeResults = PSD.trans.db._options.cache === 'immutable'; + var _a = PSD, requery = _a.requery, signal = _a.signal; + var _b = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _b[0], exactMatch = _b[1], tblCache = _b[2], container = _b[3]; + if (cacheEntry && exactMatch) { + cacheEntry.obsSet = req.obsSet; + } + else { + var promise = downTable.query(req).then(function (res) { + var result = res.result; + cacheEntry.res = result; + if (freezeResults) { + for (var i = 0, l = result.length; i < l; ++i) { + Object.freeze(result[i]); + } + Object.freeze(result); + } + else { + res.result = deepClone(result); + } + return res; + }).catch(function (error) { + if (container && cacheEntry) + delArrayItem(container, cacheEntry); + return Promise.reject(error); + }); + cacheEntry = { + obsSet: req.obsSet, + promise: promise, + subscribers: new Set(), + type: 'query', + req: req, + dirty: false, + }; + if (container) { + container.push(cacheEntry); + } + else { + container = [cacheEntry]; + if (!tblCache) { + tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { + queries: { + query: {}, + count: {}, + }, + objs: new Map(), + optimisticOps: [], + unsignaledParts: {} + }; + } + tblCache.queries.query[req.query.index.name || ''] = container; + } + } + subscribeToCacheEntry(cacheEntry, container, requery, signal); + return cacheEntry.promise.then(function (res) { + return { + result: applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults), + }; + }); + } }); + return tableMW; + } }); + return coreMW; + }, +}; + +function vipify(target, vipDb) { + return new Proxy(target, { + get: function (target, prop, receiver) { + if (prop === 'db') + return vipDb; + return Reflect.get(target, prop, receiver); + } + }); +} + +var Dexie$1 = (function () { + function Dexie(name, options) { + var _this = this; + this._middlewares = {}; + this.verno = 0; + var deps = Dexie.dependencies; + this._options = options = __assign({ + addons: Dexie.addons, autoOpen: true, + indexedDB: deps.indexedDB, IDBKeyRange: deps.IDBKeyRange, cache: 'cloned' }, options); + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + var addons = options.addons; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + this._novip = this; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3 + }; + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) { + return function (subscriber, bSticky) { + Dexie.vip(function () { + var state = _this._state; + if (state.openComplete) { + if (!state.dbOpenError) + DexiePromise.resolve().then(subscriber); + if (bSticky) + subscribe(subscriber); + } + else if (state.onReadyBeingFired) { + state.onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + subscribe(subscriber); + var db_1 = _this; + if (!bSticky) + subscribe(function unsubscribe() { + db_1.on.ready.unsubscribe(subscriber); + db_1.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.Collection = createCollectionConstructor(this); + this.Table = createTableConstructor(this); + this.Transaction = createTransactionConstructor(this); + this.Version = createVersionConstructor(this); + this.WhereClause = createWhereClauseConstructor(this); + this.on("versionchange", function (ev) { + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); + else + console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); + _this.close({ disableAutoOpen: false }); + _this._state.openComplete = false; + }); + this.on("blocked", function (ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); + else + console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); + }); + this._maxKey = getMaxKey(options.IDBKeyRange); + this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) { return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); }; + this._fireOnBlocked = function (ev) { + _this.on("blocked").fire(ev); + connections + .filter(function (c) { return c.name === _this.name && c !== _this && !c._state.vcFired; }) + .map(function (c) { return c.on("versionchange").fire(ev); }); + }; + this.use(cacheExistingValuesMiddleware); + this.use(cacheMiddleware); + this.use(observabilityMiddleware); + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + var vipDB = new Proxy(this, { + get: function (_, prop, receiver) { + if (prop === '_vip') + return true; + if (prop === 'table') + return function (tableName) { return vipify(_this.table(tableName), vipDB); }; + var rv = Reflect.get(_, prop, receiver); + if (rv instanceof Table) + return vipify(rv, vipDB); + if (prop === 'tables') + return rv.map(function (t) { return vipify(t, vipDB); }); + if (prop === '_createTransaction') + return function () { + var tx = rv.apply(this, arguments); + return vipify(tx, vipDB); + }; + return rv; + } + }); + this.vip = vipDB; + addons.forEach(function (addon) { return addon(_this); }); + } + Dexie.prototype.version = function (versionNumber) { + if (isNaN(versionNumber) || versionNumber < 0.1) + throw new exceptions.Type("Given version is not a positive number"); + versionNumber = Math.round(versionNumber * 10) / 10; + if (this.idbdb || this._state.isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versions = this._versions; + var versionInstance = versions.filter(function (v) { return v._cfg.version === versionNumber; })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new this.Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + versionInstance.stores({}); + this._state.autoSchema = false; + return versionInstance; + }; + Dexie.prototype._whenReady = function (fn) { + var _this = this; + return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise(function (resolve, reject) { + if (_this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); + } + if (!_this._state.isBeingOpened) { + if (!_this._options.autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + _this.open().catch(nop); + } + _this._state.dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + Dexie.prototype.use = function (_a) { + var stack = _a.stack, create = _a.create, level = _a.level, name = _a.name; + if (name) + this.unuse({ stack: stack, name: name }); + var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ stack: stack, create: create, level: level == null ? 10 : level, name: name }); + middlewares.sort(function (a, b) { return a.level - b.level; }); + return this; + }; + Dexie.prototype.unuse = function (_a) { + var stack = _a.stack, name = _a.name, create = _a.create; + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(function (mw) { + return create ? mw.create !== create : + name ? mw.name !== name : + false; + }); + } + return this; + }; + Dexie.prototype.open = function () { + var _this = this; + return usePSD(globalPSD, + function () { return dexieOpen(_this); }); + }; + Dexie.prototype._close = function () { + var state = this._state; + var idx = connections.indexOf(this); + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this.idbdb = null; + } + state.dbReadyPromise = new DexiePromise(function (resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function (_, reject) { + state.cancelOpen = reject; + }); + }; + Dexie.prototype.close = function (_a) { + var _b = _a === void 0 ? { disableAutoOpen: true } : _a, disableAutoOpen = _b.disableAutoOpen; + this._close(); + var state = this._state; + if (disableAutoOpen) + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + }; + Dexie.prototype.delete = function () { + var _this = this; + var hasArguments = arguments.length > 0; + var state = this._state; + return new DexiePromise(function (resolve, reject) { + var doDelete = function () { + _this.close({ disableAutoOpen: false }); + var req = _this._deps.indexedDB.deleteDatabase(_this.name); + req.onsuccess = wrap(function () { + _onDatabaseDeleted(_this._deps, _this.name); + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = _this._fireOnBlocked; + }; + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (state.isBeingOpened) { + state.dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + }); + }; + Dexie.prototype.backendDB = function () { + return this.idbdb; + }; + Dexie.prototype.isOpen = function () { + return this.idbdb !== null; + }; + Dexie.prototype.hasBeenClosed = function () { + var dbOpenError = this._state.dbOpenError; + return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); + }; + Dexie.prototype.hasFailed = function () { + return this._state.dbOpenError !== null; + }; + Dexie.prototype.dynamicallyOpened = function () { + return this._state.autoSchema; + }; + Object.defineProperty(Dexie.prototype, "tables", { + get: function () { + var _this = this; + return keys(this._allTables).map(function (name) { return _this._allTables[name]; }); + }, + enumerable: false, + configurable: true + }); + Dexie.prototype.transaction = function () { + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + Dexie.prototype._transaction = function (mode, tables, scopeFunc) { + var _this = this; + var parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); + var idbMode, storeNames; + try { + storeNames = tables.map(function (table) { + var storeName = table instanceof _this.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; + }); + if (mode == "r" || mode === READONLY) + idbMode = READONLY; + else if (mode == "rw" || mode == READWRITE) + idbMode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + if (parentTransaction.mode === READONLY && idbMode === READWRITE) { + if (onlyIfCompatible) { + 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) { + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, function (_, reject) { reject(e); }) : + rejection(e); + } + var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return (parentTransaction ? + parentTransaction._promise(idbMode, enterTransaction, "lock") : + PSD.trans ? + usePSD(PSD.transless, function () { return _this._whenReady(enterTransaction); }) : + this._whenReady(enterTransaction)); + }; + Dexie.prototype.table = function (tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); + } + return this._allTables[tableName]; + }; + return Dexie; +}()); + +var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol + ? Symbol.observable + : "@@observable"; +var Observable = (function () { + function Observable(subscribe) { + this._subscribe = subscribe; + } + Observable.prototype.subscribe = function (x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error: error, complete: complete } : x); + }; + Observable.prototype[symbolObservable] = function () { + return this; + }; + return Observable; +}()); + +var domDeps; +try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; +} +catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; +} + +function liveQuery(querier) { + var hasValue = false; + var currentValue; + var observable = new Observable(function (observer) { + var scopeFuncIsAsync = isAsyncFunction(querier); + function execute(ctx) { + var wasRootExec = beginMicroTickScope(); + try { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var rv = newScope(querier, ctx); + if (scopeFuncIsAsync) { + rv.finally(decrementExpectedAwaits); + } + return rv; + } + finally { + wasRootExec && endMicroTickScope(); + } + } + var closed = false; + var abortController; + var accumMuts = {}; + var currentObs = {}; + var subscription = { + get closed() { + return closed; + }, + unsubscribe: function () { + if (closed) + return; + closed = true; + if (abortController) + abortController.abort(); + if (startedListening) + globalEvents.storagemutated.unsubscribe(mutationListener); + }, + }; + observer.start && observer.start(subscription); + var startedListening = false; + function shouldNotify() { + return obsSetsOverlap(currentObs, accumMuts); + } + var mutationListener = function (parts) { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + var doQuery = function () { + if (closed || + !domDeps.indexedDB) + { + return; + } + accumMuts = {}; + var subscr = {}; + if (abortController) + abortController.abort(); + abortController = new AbortController(); + var ctx = { + subscr: subscr, + signal: abortController.signal, + requery: doQuery, + querier: querier, + trans: null + }; + var ret = execute(ctx); + Promise.resolve(ret).then(function (result) { + hasValue = true; + currentValue = result; + if (closed || ctx.signal.aborted) { + return; + } + accumMuts = {}; + currentObs = subscr; + if (!objectIsEmpty(currentObs) && !startedListening) { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); + startedListening = true; + } + observer.next && observer.next(result); + }, function (err) { + hasValue = false; + if (!['DatabaseClosedError', 'AbortError'].includes(err === null || err === void 0 ? void 0 : err.name)) { + if (closed) + return; + observer.error && observer.error(err); + } + }); + }; + doQuery(); + return subscription; + }); + observable.hasValue = function () { return hasValue; }; + observable.getValue = function () { return currentValue; }; + return observable; +} + +var Dexie = Dexie$1; +props(Dexie, __assign(__assign({}, fullNameExceptions), { + delete: function (databaseName) { + var db = new Dexie(databaseName, { addons: [] }); + return db.delete(); + }, + exists: function (name) { + return new Dexie(name, { addons: [] }).open().then(function (db) { + db.close(); + return true; + }).catch('NoSuchDatabaseError', function () { return false; }); + }, + getDatabaseNames: function (cb) { + try { + return getDatabaseNames(Dexie.dependencies).then(cb); + } + catch (_a) { + return rejection(new exceptions.MissingAPI()); + } + }, + defineClass: function () { + function Class(content) { + extend(this, content); + } + return Class; + }, ignoreTransaction: function (scopeFunc) { + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : + scopeFunc(); + }, vip: vip, async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return DexiePromise.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 DexiePromise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + currentTransaction: { + get: function () { return PSD.trans || null; } + }, waitFor: function (promiseOrFunction, optionalTimeout) { + var promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? + Dexie.ignoreTransaction(promiseOrFunction) : + promiseOrFunction) + .timeout(optionalTimeout || 60000); + return PSD.trans ? + PSD.trans.waitFor(promise) : + promise; + }, + Promise: DexiePromise, + debug: { + get: function () { return debug; }, + set: function (value) { + setDebug(value, value === 'dexie' ? function () { return true; } : dexieStackFrameFilter); + } + }, + derive: derive, extend: extend, props: props, override: override, + Events: Events, on: globalEvents, liveQuery: liveQuery, extendObservabilitySet: extendObservabilitySet, + getByKeyPath: getByKeyPath, setByKeyPath: setByKeyPath, delByKeyPath: delByKeyPath, shallowClone: shallowClone, deepClone: deepClone, getObjectDiff: getObjectDiff, cmp: cmp, asap: asap$1, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: domDeps, cache: cache, + 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)); }) })); +Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); + +if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (updatedParts) { + if (!propagatingLocally) { + var event_1; + if (isIEOrEdge) { + event_1 = document.createEvent('CustomEvent'); + event_1.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts); + } + else { + event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + } + propagatingLocally = true; + dispatchEvent(event_1); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function (_a) { + var detail = _a.detail; + if (!propagatingLocally) { + propagateLocally(detail); + } + }); +} +function propagateLocally(updateParts) { + var wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + signalSubscribersNow(updateParts, true); + } + finally { + propagatingLocally = wasMe; + } +} +var propagatingLocally = false; + +if (typeof BroadcastChannel !== 'undefined') { + var bc_1 = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + if (typeof bc_1.unref === 'function') { + bc_1.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + if (!propagatingLocally) { + bc_1.postMessage(changedParts); + } + }); + bc_1.onmessage = function (ev) { + if (ev.data) + propagateLocally(ev.data); + }; +} +else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function (changedParts) { + try { + if (!propagatingLocally) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({ + trig: Math.random(), + changedParts: changedParts, + })); + } + if (typeof self['clients'] === 'object') { + __spreadArray([], self['clients'].matchAll({ includeUncontrolled: true }), true).forEach(function (client) { + return client.postMessage({ + type: STORAGE_MUTATED_DOM_EVENT_NAME, + changedParts: changedParts, + }); + }); + } + } + } + catch (_a) { } + }); + if (typeof addEventListener !== 'undefined') { + addEventListener('storage', function (ev) { + if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) { + var data = JSON.parse(ev.newValue); + if (data) + propagateLocally(data.changedParts); + } + }); + } + var swContainer = self.document && navigator.serviceWorker; + if (swContainer) { + swContainer.addEventListener('message', propagateMessageLocally); + } +} +function propagateMessageLocally(_a) { + var data = _a.data; + if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) { + propagateLocally(data.changedParts); + } +} + +DexiePromise.rejectionMapper = mapError; +setDebug(debug, dexieStackFrameFilter); + +export { Dexie$1 as Dexie, Entity, RangeSet, cmp, Dexie$1 as default, liveQuery, mergeRanges, rangesOverlap }; +//# sourceMappingURL=dexie.mjs.map diff --git a/dist/dexie.mjs.map b/dist/dexie.mjs.map new file mode 100644 index 000000000..b29411d85 --- /dev/null +++ b/dist/dexie.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.mjs","sources":["../node_modules/.pnpm/tslib@2.3.1/node_modules/tslib/tslib.es6.js","../src/globals/global.ts","../src/functions/utils.ts","../src/helpers/debug.ts","../src/errors/errors.js","../src/functions/chaining-functions.js","../src/helpers/promise.js","../src/functions/temp-transaction.ts","../src/globals/constants.ts","../src/functions/combine.ts","../src/dbcore/keyrange.ts","../src/functions/workaround-undefined-primkey.ts","../src/classes/entity/Entity.ts","../src/functions/cmp.ts","../src/classes/table/table.ts","../src/helpers/Events.js","../src/functions/make-class-constructor.ts","../src/classes/table/table-constructor.ts","../src/classes/collection/collection-helpers.ts","../src/classes/collection/collection.ts","../src/classes/collection/collection-constructor.ts","../src/functions/compare-functions.ts","../src/classes/where-clause/where-clause-helpers.ts","../src/classes/where-clause/where-clause.ts","../src/classes/where-clause/where-clause-constructor.ts","../src/functions/event-wrappers.ts","../src/globals/global-events.ts","../src/classes/transaction/transaction.ts","../src/classes/transaction/transaction-constructor.ts","../src/helpers/index-spec.ts","../src/helpers/table-schema.ts","../src/functions/quirks.ts","../src/dbcore/get-key-extractor.ts","../src/dbcore/dbcore-indexeddb.ts","../src/classes/dexie/generate-middleware-stacks.ts","../src/classes/version/schema-helpers.ts","../src/classes/version/version.ts","../src/classes/version/version-constructor.ts","../src/helpers/database-enumerator.ts","../src/classes/dexie/vip.ts","../node_modules/.pnpm/safari-14-idb-fix@3.0.0/node_modules/safari-14-idb-fix/dist/index.js","../src/helpers/rangeset.ts","../src/live-query/extend-observability-set.ts","../src/live-query/obs-sets-overlap.ts","../src/live-query/cache/cache.ts","../src/live-query/cache/signalSubscribers.ts","../src/classes/dexie/dexie-open.ts","../src/helpers/yield-support.ts","../src/classes/dexie/transaction-helpers.ts","../src/dbcore/virtual-index-middleware.ts","../src/functions/get-object-diff.ts","../src/dbcore/get-effective-keys.ts","../src/hooks/hooks-middleware.ts","../src/dbcore/cache-existing-values-middleware.ts","../src/live-query/cache/is-cachable-context.ts","../src/live-query/cache/is-cachable-request.ts","../src/live-query/observability-middleware.ts","../src/live-query/cache/is-within-range.ts","../src/live-query/cache/apply-optimistic-ops.ts","../src/live-query/cache/are-ranges-equal.ts","../src/live-query/cache/is-super-range.ts","../src/live-query/cache/find-compatible-query.ts","../src/live-query/cache/subscribe-cachentry.ts","../src/live-query/cache/cache-middleware.ts","../src/helpers/vipify.ts","../src/classes/dexie/dexie.ts","../src/classes/observable/observable.ts","../src/classes/dexie/dexie-dom-dependencies.ts","../src/live-query/live-query.ts","../src/classes/dexie/dexie-static-props.ts","../src/live-query/propagate-locally.ts","../src/live-query/enable-broadcast.ts","../src/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n","declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise){\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _global }\n\nexport function extend(obj: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nconst _slice = [].slice;\nexport function slice(args, start?, end?) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn: (...args: any[])=>void, onerror, args?) : void {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath)) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a: (T | T[])[]) : T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n \"Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]);\nconst intrinsicTypes = new Set(intrinsicTypeNames.map(t=>_global[t]));\n\n/** Deep clone a simple object tree.\n * \n * Copies object tree deeply, but does not deep-copy arrays,\n * typed arrays, Dates or other intrinsic types.\n * \n * Does not check for cyclic references.\n * \n * This function is 6 times faster than structuredClone() on chromium 111.\n * \n * This function can safely be used for cloning ObservabilitySets and RangeSets.\n * \n * @param o Object to clone\n * @returns Cloned object\n */\nexport function cloneSimpleObjectTree(o: T): T {\n const rv = {} as T;\n for (const k in o) if (hasOwn(o, k)) {\n const v = o[k];\n rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v);\n }\n return rv;\n}\n\nexport function objectIsEmpty(o: object) {\n for (const k in o) if (hasOwn(o, k)) return false;\n return true;\n}\n\nlet circularRefs: null | WeakMap = null;\n\n/** Deep clone an object or array.\n * \n * \n * @param any \n * @returns \n */\nexport function deepClone(any: T): T {\n circularRefs = new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(x: T): T {\n if (!x || typeof x !== 'object') return x;\n let rv = circularRefs.get(x); // Resolve circular references\n if (rv) return rv;\n if (isArray(x)) {\n rv = [];\n circularRefs.set(x, rv);\n for (var i = 0, l = x.length; i < l; ++i) {\n rv.push(innerDeepClone(x[i]));\n }\n } else if (intrinsicTypes.has(x.constructor)) {\n // For performance, we're less strict than structuredClone - we're only\n // cloning arrays and custom objects.\n // Typed arrays, Dates etc are not cloned.\n rv = x;\n } else {\n // We're nicer to custom classes than what structuredClone() is -\n // we preserve the proto of each object.\n const proto = getProto(x);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs.set(x, rv);\n for (var prop in x) {\n if (hasOwn(x, prop)) {\n rv[prop] = innerDeepClone(x[prop]);\n }\n }\n }\n return rv;\n}\n\nconst {toString} = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\n\nexport function delArrayItem(a: any[], x: any) {\n const i = a.indexOf(x);\n if (i >= 0) a.splice(i, 1);\n return i >= 0;\n}\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : ()=>false;\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch(e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\n// TODO: Replace this in favor of a decorator instead.\nexport function deprecated (what: string, fn: (...args)=>T) {\n return function () {\n console.warn(`${what} is deprecated. See https://dexie.org/docs/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n } as (...args)=>T\n}\n","import { derive, setProp } from '../functions/utils';\nimport { getErrorWithStack, prettyStack } from '../helpers/debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function() {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key=>failures[key].toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, this.failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport { _global } from '../globals/global';\nimport {tryCatch, props, setProp,\n getPropertyDescriptor, getArrayOf, extend, getProto} from '../functions/utils';\nimport {nop, callBoth, mirror} from '../functions/chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from '../errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (()=>{\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nfunction schedulePhysicalTick() {\n queueMicrotask(physicalTick);\n}\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: nop,\n pgp: false,\n env: {},\n finalize: nop\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function DexiePromise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n }\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n \n stack: {\n get: function() {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack (this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function') return new DexiePromise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled) setProp (DexiePromise, \"allSettled\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined') setProp(DexiePromise, \"any\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => resolve(value),\n failure => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }));\n });\n });\n}\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n \n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\nfunction getStack (promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n \n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with queueMicrotask().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n usePSD(globalPSD, ()=>{\n // Make sure to reset the async context to globalPSD before\n // executing any of the microtick subscribers.\n beginMicroTickScope() && endMicroTickScope();\n });\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: DexiePromise, configurable: true, writable: true},\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits() {\n if (!task.awaits) return false;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n return true;\n}\n\nif ((''+nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n if (cleanup) queueMicrotask(decrementExpectedAwaits);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone),\n nativeAwaitCompatibleWrap(onRejected, zone));\n };\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport {DexiePromise};\n","import { PSD, rejection, newScope } from \"../helpers/promise\";\nimport { DexieOptions } from \"../public/types/dexie-constructor\";\nimport { errnames, exceptions } from \"../errors\";\nimport { nop } from \"./chaining-functions\";\nimport { Transaction } from \"../classes/transaction\";\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n*/\nexport function tempTransaction (\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any)\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n{\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n if (mode === 'readwrite') try {trans.idbtrans.commit();} catch {}\n return mode === 'readonly' ? result : trans._completion.then(() => result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","import { Dexie } from \"../classes/dexie\";\n\nexport const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\nexport const STRING_EXPECTED = \"String expected.\";\nexport const connections: Dexie[] = [];\nexport const isIEOrEdge =\n typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nexport const hasIEDeleteObjectStoreBug = isIEOrEdge;\nexport const hangsOnDeleteLargeKeyRange = isIEOrEdge;\nexport const dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n}\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true\n}\n","import { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\n}","import { exceptions } from \"../../errors\";\n\nexport function Entity(){\n throw exceptions.Type();\n}\n","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { DexiePromise as Promise, PSD, newScope, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport { isArray, keys, getByKeyPath, setByKeyPath, extend, getProto } from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\nimport { Entity } from '../entity/Entity';\nimport { UpdateSpec } from '../../public';\nimport { cmp } from '../../functions/cmp';\n\n/** class Table\n * \n * https://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike | void,\n writeLocked?: boolean | string) : PromiseExtended\n {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n \n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db._novip === this.db._novip ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n * \n * https://dexie.org/docs/Table/Table.get()\n * \n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);\n\n return this._trans('readonly', (trans) => {\n return this.core.get({trans, key: keyOrCrit})\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n * \n * https://dexie.org/docs/Table/Table.where()\n * \n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => {\n if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[0];\n \n if (compoundIndex && this.db._maxKey !== maxString) {\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\n\n if (!compoundIndex && debug) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n\n function equals (a, b) {\n return idb.cmp(a,b) === 0; // Works with all indexable types including binary keys.\n }\n\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter\n combine(\n prevFilterFn,\n index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n * \n * https://dexie.org/docs/Table/Table.filter()\n * \n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n * \n * https://dexie.org/docs/Table/Table.count()\n * \n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n * \n * https://dexie.org/docs/Table/Table.offset()\n * \n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n * \n * https://dexie.org/docs/Table/Table.limit()\n * \n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n * \n * https://dexie.org/docs/Table/Table.each()\n * \n **/\n each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n * \n * https://dexie.org/docs/Table/Table.toArray()\n * \n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n * \n * https://dexie.org/docs/Table/Table.toCollection()\n * \n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n * \n * https://dexie.org/docs/Table/Table.orderBy()\n * \n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n\n /** Table.reverse()\n * \n * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://dexie.org/docs/Table/Table.mapToClass()\n * \n **/\n mapToClass(constructor: Function) {\n const {db, name: tableName} = this;\n this.schema.mappedClass = constructor;\n if (constructor.prototype instanceof Entity) {\n constructor = class extends (constructor as any) {\n get db () { return db; }\n table() { return tableName; }\n }\n }\n // Collect all inherited property names (including method names) by\n // walking the prototype chain. This is to avoid overwriting them from\n // database data - so application code can rely on inherited props never\n // becoming shadowed by database object props.\n const inheritedProps = new Set();\n for (let proto = constructor.prototype; proto; proto = getProto(proto)) {\n Object.getOwnPropertyNames(proto).forEach(propName => inheritedProps.add(propName));\n }\n \n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n const readHook = (obj: Object) => {\n if (!obj) return obj; // No valid object. (Value is null or undefined). Return as is.\n // Create a new object that derives from constructor:\n const res = Object.create(constructor.prototype);\n // Clone members (but never those that collide with a property in the prototype\n // hierchary (MUST BE ABLE TO RELY ON Entity methods and props!)):\n for (let m in obj) if (!inheritedProps.has(m)) try { res[m] = obj[m]; } catch (_) { }\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n }\n\n /** @deprecated */\n defineClass() {\n function Class (content){\n extend(this, content);\n };\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n * \n * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n /*// object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly. TODO: Document this change!\n if (!Object.isFrozen(keyOrObject)) try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }*/\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n\n /** Table.put()\n * \n * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://dexie.org/docs/Table/Table.delete()\n * \n **/\n delete(key: IndexableType): PromiseExtended {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'delete', keys: [key]}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.clear()\n * \n * https://dexie.org/docs/Table/Table.clear()\n * \n **/\n clear() {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.bulkGet()\n * \n * https://dexie.org/docs/Table/Table.bulkGet()\n * \n * @param keys \n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n * \n * https://dexie.org/docs/Table/Table.bulkAdd()\n * \n **/\n bulkAdd(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, wantResults}\n )\n .then(({numFailures, results,lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://dexie.org/docs/Table/Table.bulkPut()\n * \n **/\n bulkPut(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, wantResults}\n )\n .then(({numFailures, results, lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkUpdate()\n *\n * https://dexie.org/docs/Table.Table.bulkUpdate()\n */\n bulkUpdate(\n keysAndChanges: readonly { key: any; changes: UpdateSpec }[]\n ): PromiseExtended {\n const coreTable = this.core;\n const keys = keysAndChanges.map((entry) => entry.key);\n const changeSpecs = keysAndChanges.map((entry) => entry.changes);\n const offsetMap: number[] = [];\n return this._trans('readwrite', (trans) => {\n return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => {\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keysAndChanges.forEach(({ key, changes }, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const keyPath of Object.keys(changes)) {\n const value = changes[keyPath];\n if (keyPath === this.schema.primKey.keyPath) {\n if (cmp(value, key) !== 0) {\n throw new exceptions.Constraint(\n `Cannot update primary key in bulkUpdate()`\n );\n }\n } else {\n setByKeyPath(obj, keyPath, value);\n }\n }\n offsetMap.push(idx);\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n const numEntries = resultKeys.length;\n return coreTable\n .mutate({\n trans,\n type: 'put',\n keys: resultKeys,\n values: resultObjs,\n updates: {\n keys,\n changeSpecs\n }\n })\n .then(({ numFailures, failures }) => {\n if (numFailures === 0) return numEntries;\n // Failure. bulkPut() may have a subset of keys\n // so we must translate returned 'failutes' into the offsets of given argument:\n for (const offset of Object.keys(failures)) {\n const mappedOffset = offsetMap[Number(offset)];\n if (mappedOffset != null) {\n const failure = failures[offset];\n delete failures[offset];\n failures[mappedOffset] = failure;\n }\n }\n throw new BulkError(\n `${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`,\n failures\n );\n });\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://dexie.org/docs/Table/Table.bulkDelete()\n * \n **/\n bulkDelete(keys: ReadonlyArray): PromiseExtended {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});\n }).then(({numFailures, lastResult, failures}) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n","import {keys, isArray, asap} from '../functions/utils';\nimport {nop, mirror, reverseStoppableEventChain} from '../functions/chaining-functions';\nimport {exceptions} from '../errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","import { arrayToObject, derive } from './utils';\n\n\nexport function makeClassConstructor (prototype: Object, constructor: Function) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({prototype});\n return constructor as any as TConstructor; \n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport { hookCreatingChain, pureFunctionChain, nop, mirror, hookUpdatingChain, hookDeletingChain } from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (name: string, tableSchema: TableSchema, optionalTrans?: Transaction) : Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor (db: Dexie) {\n return makeClassConstructor(\n Table.prototype,\n\n function Table (this: Table, name: string, tableSchema: TableSchema, trans?: Transaction) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n }) as TableHooks;\n }\n\n );\n}\n","import { combine } from \"../../functions/combine\";\nimport { exceptions } from \"../../errors\";\nimport { hasOwn } from \"../../functions/utils\";\nimport { wrap } from \"../../helpers/promise\";\nimport { Collection } from './';\nimport { DBCoreCursor, DBCoreTable, DBCoreTransaction, DBCoreTableSchema, DBCoreRangeType } from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection[\"_ctx\"];\n\nexport function isPlainKeyRange (ctx: CollectionContext, ignoreLimitFilter?: boolean) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n} \n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter (ctx: CollectionContext, factory, isLimitFilter?) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(ctx: CollectionContext, coreSchema: DBCoreTableSchema) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\n\nexport function openCursor(ctx: CollectionContext, coreTable: DBCoreTable, trans: DBCoreTransaction) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index, \n range: ctx.range\n }\n });\n}\n\nexport function iter (\n ctx: CollectionContext, \n fn: (item, cursor: DBCoreCursor, advance: Function)=>void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable): Promise\n{\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (!filter || filter(cursor, advance, result=>cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\n\nfunction iterate(cursorPromise: Promise, filter, fn, valueMapper): Promise {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n \n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(()=>{\n var c = ()=>cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val=>{cursor.stop(val);c=nop}, e => {cursor.fail(e);c = nop;}))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n","import { Collection as ICollection } from \"../../public/types/collection\";\nimport { Dexie } from \"../dexie\";\nimport { Table } from \"../table\";\nimport { IndexableType, IndexableTypeArrayReadonly } from \"../../public/types/indexable-type\";\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { iter, isPlainKeyRange, getIndexOrStore, addReplayFilter, addFilter, addMatchFilter } from \"./collection-helpers\";\nimport { rejection } from \"../../helpers/promise\";\nimport { combine } from \"../../functions/combine\";\nimport { extend, hasOwn, deepClone, keys, setByKeyPath, getByKeyPath } from \"../../functions/utils\";\nimport { ModifyError } from \"../../errors\";\nimport { hangsOnDeleteLargeKeyRange } from \"../../globals/constants\";\nimport { ThenShortcut } from \"../../public/types/then-shortcut\";\nimport { Transaction } from '../transaction';\nimport { DBCoreCursor, DBCoreTransaction, DBCoreRangeType, DBCoreMutateResponse, DBCoreKeyRange } from '../../public/types/dbcore';\nimport { cmp } from \"../../functions/cmp\";\n\n/** class Collection\n * \n * https://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: \"next\" | \"prev\";\n unique: \"\" | \"unique\";\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number,\n limit: number,\n error: any, // If set, any promise must be rejected with this error\n or: Collection,\n valueMapper: (any) => any\n }\n \n _ondirectionchange?: Function;\n\n _read(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike, cb?): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction) : Promise\n {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n * \n * https://dexie.org/docs/Collection/Collection.clone()\n * \n **/\n clone(props?) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n\n /** Collection.raw()\n * \n * https://dexie.org/docs/Collection/Collection.raw()\n * \n **/\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n * \n * https://dexie.org/docs/Collection/Collection.each()\n * \n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended {\n var ctx = this._ctx;\n\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n * \n * https://dexie.org/docs/Collection/Collection.count()\n * \n **/\n count(cb?) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(()=>count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n * \n * https://dexie.org/docs/Collection/Collection.sortBy()\n * \n **/\n sortBy(keyPath: string): PromiseExtended;\n sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended;\n sortBy(keyPath: string, cb?: ThenShortcut) {\n const parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n }\n\n /** Collection.toArray()\n * \n * https://dexie.org/docs/Collection/Collection.toArray()\n * \n **/\n toArray(cb?): PromiseExtended {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n const {valueMapper} = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({result}) => valueMapper ? result.map(valueMapper) : result);\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(()=>a);\n }\n }, cb);\n }\n\n /** Collection.offset()\n * \n * https://dexie.org/docs/Collection/Collection.offset()\n * \n **/\n offset(offset: number) : Collection{\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n\n /** Collection.limit()\n * \n * https://dexie.org/docs/Collection/Collection.limit()\n * \n **/\n limit(numRows: number) : Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n }\n\n /** Collection.until()\n * \n * https://dexie.org/docs/Collection/Collection.until()\n * \n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n }\n\n /** Collection.first()\n * \n * https://dexie.org/docs/Collection/Collection.first()\n * \n **/\n first(cb?) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.last()\n * \n * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://dexie.org/docs/Collection/Collection.filter()\n * \n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n\n /** Collection.and()\n * \n * https://dexie.org/docs/Collection/Collection.and()\n * \n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n * \n * https://dexie.org/docs/Collection/Collection.or()\n * \n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n * \n * https://dexie.org/docs/Collection/Collection.reverse()\n * \n **/\n reverse() {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n }\n\n /** Collection.desc()\n * \n * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachKey()\n * \n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n\n /** Collection.eachUniqueKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachUniqueKey()\n * \n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n * \n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n\n /** Collection.keys()\n * \n * https://dexie.org/docs/Collection/Collection.keys()\n * \n **/\n keys(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.primaryKeys()\n * \n * https://dexie.org/docs/Collection/Collection.primaryKeys()\n * \n **/\n primaryKeys(cb?) : PromiseExtended {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }});\n }).then(({result})=>result).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.uniqueKeys()\n * \n * https://dexie.org/docs/Collection/Collection.uniqueKeys()\n * \n **/\n uniqueKeys(cb?) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n * \n * https://dexie.org/docs/Collection/Collection.firstKey()\n * \n **/\n firstKey(cb?) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.lastKey()\n * \n * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://dexie.org/docs/Collection/Collection.distinct()\n * \n **/\n distinct() {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor: DBCoreCursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n\n //\n // Methods that mutate storage\n //\n\n /** Collection.modify()\n * \n * https://dexie.org/docs/Collection/Collection.modify()\n * \n **/\n modify(changes: { [keyPath: string]: any }) : PromiseExtended\n modify(changes: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean): PromiseExtended {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n modifyer = changes;\n } else {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n\n const coreTable = ctx.table.core;\n const {outbound, extractKey} = coreTable.schema.primaryKey;\n const limit = this.db._options.modifyChunkSize || 200;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (expectedCount: number, res: DBCoreMutateResponse) => {\n const {failures, numFailures} = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n }\n return this.clone().primaryKeys().then(keys => {\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i=0; i 0 &&\n coreTable.mutate({trans, type: 'add', values: addValues})\n .then(res => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n ).then(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\n }).then(res=>applyMutateResult(deleteKeys.length, res))\n ).then(()=>{\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n }\n\n return nextChunk(0).then(()=>{\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys as IndexableTypeArrayReadonly);\n\n return keys.length;\n });\n });\n\n });\n }\n\n /** Collection.delete()\n * \n * https://dexie.org/docs/Collection/Collection.delete()\n * \n **/\n delete() : PromiseExtended {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === DBCoreRangeType.Any)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write(trans => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const {primaryKey} = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({trans, query: {index: primaryKey, range: coreRange}}).then(count => {\n return ctx.table.core.mutate({trans, type: 'deleteRange', range: coreRange})\n .then(({failures, lastResult, results, numFailures}) => {\n if (numFailures) throw new ModifyError(\"Could not delete some values\",\n Object.keys(failures).map(pos => failures[pos]),\n count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new(whereClause?: WhereClause | null, keyRangeGenerator?: () => DBCoreKeyRange): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange)\n {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport { simpleCompare, simpleCompareReverse } from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(collectionOrWhereClause: Collection | WhereClause, err, T?) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection (whereClause, () => rangeEqual(\"\")).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toUpperCase() :\n (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toLowerCase() :\n (s: string) => s.toUpperCase();\n}\n\nexport function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n}\n\nexport function addIgnoreCaseAlgorithm(whereClause: WhereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new whereClause.Collection (\n whereClause,\n ()=>createRange(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix)\n );\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange (lower: IndexableType, upper: IndexableType, lowerOpen?: boolean, upperOpen?: boolean): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\n\nexport function rangeEqual (value: IndexableType) : DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value\n };\n}\n","import { WhereClause as IWhereClause } from \"../../public/types/where-clause\";\nimport { Collection } from \"../collection\";\nimport { Table } from \"../table\";\nimport { IndexableType } from \"../../public/types/indexable-type\";\nimport { emptyCollection, fail, addIgnoreCaseAlgorithm, createRange, rangeEqual } from './where-clause-helpers';\nimport { INVALID_KEY_ARGUMENT, STRING_EXPECTED, maxString, minKey } from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection} from \"../../public/types/collection\";\n\n/** class WhereClause\n * \n * https://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n }\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.between()\n * \n **/\n between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this.Collection(this, ()=>createRange(lower, upper, !includeLower, !includeUpper));\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.above()\n * \n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n * \n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n\n /** WhereClause.below()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.below()\n * \n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n\n /** WhereClause.belowOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n * \n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWith()\n * \n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n * \n **/\n startsWithIgnoreCase(str: string) {\n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n\n /** WhereClause.equalsIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n * \n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n\n /** WhereClause.anyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n * \n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n * \n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n\n /** WhereClause.anyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOf()\n * \n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.notEqual()\n * \n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.noneOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.noneOf()\n * \n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try { set.sort(this._ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]],\n null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.inAnyRange()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n * \n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType, 1: IndexableType }>,\n options?: { includeLowers?: boolean, includeUppers?: boolean })\n {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(range =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(\n this,\n \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\",\n exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n\n // Join overlapping ranges\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(\n this,\n () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n\n c._ondirectionchange = direction => {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n * \n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(s => typeof s === 'string')) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map((str: string) => [str, str + maxString]));\n }\n\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\nimport { cmp } from '../../functions/cmp';\n\nexport interface WhereClauseConstructor {\n new(table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor(\n WhereClause.prototype,\n\n function WhereClause(this: WhereClause, table: Table, index?: string, orCollection?: Collection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n this._cmp = this._ascending = cmp;\n this._descending = (a, b) => cmp(b, a);\n this._max = (a, b) => cmp(a,b) > 0 ? a : b;\n this._min = (a, b) => cmp(a,b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n if (!this._IDBKeyRange) throw new exceptions.MissingAPI();\n }\n );\n}\n","import { wrap } from \"../helpers/promise\";\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nexport function hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nexport function hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\n\nexport function preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n}\n\n","import Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from \"../../helpers/promise\";\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\n idbtrans: IDBTransaction;\n storeNames: string[];\n explicit?: boolean;\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: {[tableName: string]: Table};\n\n _reculock: number;\n _blockedFuncs: { 0: () => any, 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _lock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n }\n\n /** Transaction._unlock()\n * \n * Internal method.\n */\n _unlock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _locked() {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n\n /** Transaction.create()\n * \n * Internal method.\n * \n */\n create(idbtrans?: IDBTransaction & {[prop: string]: any}) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n }\n\n /** Transaction._promise()\n * \n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike | void,\n bWriteLock?: string | boolean): DexiePromise\n {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n * \n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n * \n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): https://dexie.org/docs/Dexie/Dexie.waitFor()\n * \n **/\n waitFor(promiseLike: PromiseLike) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n } \n\n /** Transaction.abort()\n * \n * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\"); \n }\n\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction) : T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor>(\n Transaction.prototype,\n function Transaction (\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n \n });\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n }\n}\n\nexport function nameFromKeyPath (keyPath?: string | string[]): string {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { createIndexSpec } from './index-spec';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema (\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n}\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor (keyPath: null | string | string[]) : (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { eventRejectHandler, preventDefault } from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\n\nexport function arrayify(arrayLike: {length: number, [index: number]: T}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick(obj: T, props: Prop[]): Pick {\n const result = {} as Pick;\n props.forEach(prop => result[prop] = obj[prop]);\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore (\n db: IDBDatabase,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\n{\n function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const {keyPath, autoIncrement} = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const {name, unique, multiEntry, keyPath} = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579\n };\n }\n\n function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never) throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const {lower, upper, lowerOpen, upperOpen} = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n IdbKeyRange.upperBound(upper, !!upperOpen) : // below\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate ({trans, type, keys, values, range}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error (\"Invalid operation type: \" + type);\n\n const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});\n\n let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\n };\n \n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({numFailures, failures, results: [], lastResult: undefined}); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n\n if (isAddOrPut) {\n for (let i=0; i {\n const lastResult = event.target.result;\n reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\n lastResult\n });\n };\n \n req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n \n req.onsuccess = done;\n });\n }\n \n function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise\n {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n // direction\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n // request\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n \n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = ()=>{throw new Error(\"Cursor not started\");}\n const doThrowCursorIsStopped = ()=>{throw new Error(\"Cursor not stopped\");}\n (cursor as any).trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise((resolveIteration, rejectIteration) =>{\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = ()=>{throw new Error(\"Cursor behind last entry\");}\n cursor.stop();\n }\n }\n req.onsuccess = wrap(ev => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject); \n });\n }\n \n function query (hasGetAll: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {trans, values, limit, query} = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({result: []});\n if (hasGetAll) {\n const req = values ?\n (source as any).getAll(idbKeyRange, nonInfinitLimit) :\n (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({result: event.target.result});\n req.onerror = eventRejectHandler(reject);\n } else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange)\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({result});\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({result});\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n \n return {\n name: tableName,\n schema: tableSchema,\n \n mutate,\n\n getMany ({trans, keys}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & {_pos?: number};\n \n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n \n for (let i=0; i((resolve, reject) => {\n resolve = wrap (resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll),\n \n openCursor,\n\n count ({query, trans}) {\n const {index, range} = query;\n return new Promise((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n\n const {schema, hasGetAll} = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap: {[name: string]: DBCoreTable} = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n \n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema\n\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack(\n stackImpl: {stack: string},\n middlewares: Middleware<{stack: string}>[]): TStack {\n return middlewares.reduce((down, {create}) => ({...down, ...create(down)}), stackImpl) as TStack;\n} \n\nfunction createMiddlewareStacks(\n middlewares: {[StackName in keyof DexieStacks]?: Middleware[]},\n idbdb: IDBDatabase,\n {IDBKeyRange, indexedDB}: DexieDOMDependencies,\n tmpTrans: IDBTransaction): {[StackName in keyof DexieStacks]?: DexieStacks[StackName]}\n{\n const dbcore = createMiddlewareStack(\n createDBCore(idbdb, IDBKeyRange, tmpTrans),\n middlewares.dbcore);\n \n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore!;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, { PSD, newScope, NativePromise, decrementExpectedAwaits, incrementExpectedAwaits } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { hasIEDeleteObjectStoreBug, isIEOrEdge } from '../../globals/constants';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\n\nexport function setApiOnPlace(db: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) { return this.table(tableName); },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {value, writable: true, configurable: true, enumerable: true});\n }\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(db: Dexie, oldVersion: number, idbUpgradeTrans: IDBTransaction, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\n\nexport type UpgradeQueueItem = (idbtrans: IDBTransaction) => PromiseLike | void;\n\nexport function updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction)\n{\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(idx => addIndex(store, idx));\n // Update indexes\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n \n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n Promise.resolve(returnValue) : promiseFollowed.then(()=>returnValue));\n }\n });\n queue.push(idbtrans => {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[],\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string,\n recreate: boolean,\n del: string[],\n add: IndexSpec[],\n change: IndexSpec[]\n}\n\nexport function getSchemaDiff(oldSchema: DbSchema, newSchema: DbSchema): SchemaDiff {\n const diff: SchemaDiff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) // IE has bug reading autoIncrement prop.\n {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\n\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto }\n );\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\n\nexport function deleteRemovedTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\n}\n\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || \"\",\n false,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== \"string\",\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== \"string\",\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(db: Dexie, idbdb: IDBDatabase, tmpTrans: IDBTransaction) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames(db: Dexie, schema: DbSchema, idbtrans: IDBTransaction) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport { removeTablesApi, setApiOnPlace, parseIndexSyntax } from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number,\n storesSource: { [tableName: string]: string | null },\n dbschema: DbSchema,\n tables: {},\n contentUpgrade: Function | null\n }\n\n _parseStoresSpec(stores: { [tableName: string]: string | null }, outSchema: DbSchema): any {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(idx => {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n\n stores(stores: { [key: string]: string | null; }): IVersion {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string; } = {};\n let dbschema = {};\n versions.forEach(version => { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(upgradeFunction: (trans: Transaction) => PromiseLike | void): Version {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new(versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n\n}\n","import { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n infos\n // Select name prop of infos:\n .map((info) => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter((name) => name !== DBNAMES_DB)\n )\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n}\n\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { cloneSimpleObjectTree, deepClone, keys, objectIsEmpty } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n if (target[part]) mergeRanges(target[part], newSet[part]);\n else target[part] = cloneSimpleObjectTree(newSet[part]); // Somewhat faster\n });\n return target;\n}\n","import { rangesOverlap } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\n\nexport function obsSetsOverlap(os1: ObservabilitySet, os2: ObservabilitySet) {\n return Object.keys(os1).some(\n (key) => os2[key] && rangesOverlap(os2[key], os1[key])\n );\n}\n","import { type GlobalQueryCache } from \"../../public/types/cache\";\n\nexport const cache: GlobalQueryCache = {}\n","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport { extendObservabilitySet } from '../extend-observability-set';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { cache } from './cache';\n\nlet unsignaledParts: ObservabilitySet = {};\nlet isTaskEnqueued = false;\n\nexport function signalSubscribersLazily(part: ObservabilitySet) {\n extendObservabilitySet(unsignaledParts, part);\n if (!isTaskEnqueued) {\n isTaskEnqueued = true;\n setTimeout(() => {\n isTaskEnqueued = false;\n const parts = unsignaledParts;\n unsignaledParts = {};\n signalSubscribersNow(parts);\n }, 0);\n }\n}\n\nexport function signalSubscribersNow(\n updatedParts: ObservabilitySet,\n deleteAffectedCacheEntries = false\n) {\n const queriesToSignal = new Set<() => void>();\n for (const key in updatedParts) {\n const parts = /^idb\\:\\/\\/(.*)\\/(.*)\\//.exec(key);\n if (parts) {\n const [, dbName, tableName] = parts;\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (tblCache)\n signalTableSubscribersNow(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n }\n // Now when affected cache entries are removed, signal collected subscribers to requery.\n queriesToSignal.forEach((requery) => requery());\n}\n\nfunction signalTableSubscribersNow(\n tblCache: TblQueryCache,\n updatedParts: ObservabilitySet,\n outQueriesToSignal: Set<() => void>,\n deleteAffectedCacheEntries: boolean\n) {\n const updatedEntryLists: [string, CacheEntry[]][] =\n deleteAffectedCacheEntries && [];\n for (const [indexName, entries] of Object.entries(tblCache.queries.query)) {\n const filteredEntries: CacheEntry[] = deleteAffectedCacheEntries && [];\n for (const entry of entries) {\n if (entry.obsSet && obsSetsOverlap(updatedParts, entry.obsSet)) {\n // This query is affected by the mutation. Remove it from cache\n // and signal all subscribers to requery.\n entry.subscribers.forEach((requery) => outQueriesToSignal.add(requery));\n } else if (deleteAffectedCacheEntries) {\n filteredEntries.push(entry);\n }\n }\n // Collect cache entries to be updated\n if (deleteAffectedCacheEntries)\n updatedEntryLists.push([indexName, filteredEntries]);\n }\n if (deleteAffectedCacheEntries) {\n for (const [indexName, filteredEntries] of updatedEntryLists) {\n tblCache.queries.query[indexName] = filteredEntries;\n }\n }\n}\n","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { eventRejectHandler, preventDefault } from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/constants';\nimport { runUpgraders, readGlobalSchema, adjustToExistingIndexNames, verifyInstalledSchema } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\nimport safari14Workaround from 'safari-14-idb-fix';\nimport { type ObservabilitySet } from '../../public/types/db-events';\nimport { RangeSet } from '../../helpers/rangeset';\nimport { DEXIE_STORAGE_MUTATED_EVENT_NAME, globalEvents } from '../../globals/global-events';\nimport { signalSubscribersNow } from '../../live-query/cache/signalSubscribers';\n\nexport function dexieOpen (db: Dexie) {\n const state = db._state;\n const {indexedDB} = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection (state.dbOpenError) :\n db);\n Debug.debug && (state.openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n \n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: (IDBTransaction | null) = null,\n wasCreated = false;\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([openCanceller, (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(() => new Promise((resolve, reject) => {\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n \n throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\n const dbName = db.name;\n \n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap (e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n wasCreated = oldVer < 1;\n db.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n \n req.onsuccess = wrap (() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = db.idbdb = req.result;\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0) try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n \n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n \n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }))]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>remainders(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n if (state.openCanceller === openCanceller) {\n // Only modify state if not cancelled in the mean time.\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\n }).finally(()=>{\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n }).then(()=>{\n if (wasCreated) {\n // Propagate full range on primary keys and indexes on all tables now that the DB is ready and opened,\n // and all upgraders and on('ready') subscribers have run.\n const everything: ObservabilitySet = {};\n db.tables.forEach(table => {\n table.schema.indexes.forEach(idx => {\n if (idx.name) everything[`idb://${db.name}/${table.name}/${idx.name}`] = new RangeSet(-Infinity, [[[]]]);\n });\n everything[`idb://${db.name}/${table.name}/`] = everything[`idb://${db.name}/${table.name}/:dels`] = new RangeSet(-Infinity, [[[]]]);\n });\n // Database was created. If another tab had it open when it was deleted and reopened, that tab must be updated now.\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything);\n // Wipe the cache and trigger optimistic queries:\n signalSubscribersNow(everything, true);\n }\n // Resolve the db.open() with the db instance.\n return db;\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator (iterator: Iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any)=>any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { errnames, exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(mode: TransactionMode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: ()=>PromiseLike | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n trans.explicit = true;\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\n }\n\n // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(() => returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n }).catch(e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n}\n","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n\n /** LowLevelIndex represents the actual IndexedDB index behind it */\n lowLevelIndex: DBCoreIndex;\n}\n\n// Move into some util:\nexport function pad (a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i=0; i 0;\n const virtualIndex = {\n ...lowLevelIndex,\n name: isVirtual\n ? `${keyPathAlias}(virtual-from:${lowLevelIndex.name})`\n : lowLevelIndex.name,\n lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] : // This is a compound [a, b]. Add a virtual normal index a.\n keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a,b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n \n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n \n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n \n function translateRange (range: DBCoreKeyRange, keyTail: number): DBCoreKeyRange {\n return {\n type: range.type === DBCoreRangeType.Equal ?\n DBCoreRangeType.Range :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true // doesn't matter true or false\n };\n }\n \n function translateRequest (req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest (req: DBCoreOpenCursorRequest): DBCoreOpenCursorRequest;\n function translateRequest (req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual ? {\n ...req,\n query: {\n index: index.lowLevelIndex,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n \n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n\n count(req) {\n return table.count(translateRequest(req));\n }, \n \n query(req) {\n return table.query(translateRequest(req));\n },\n \n openCursor(req) {\n const {keyTail, isVirtual, keyLength} = (req.query.index as VirtualIndex);\n if (!isVirtual) return table.openCursor(req);\n \n function createVirtualCursor(cursor: DBCoreCursor) : DBCoreCursor {\n function _continue (key?: any) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\n cursor.continue()\n }\n const virtualCursor = Object.create(cursor, {\n continue: {value: _continue},\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n }\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1 ?\n key[0] : // Cursor.key should not be an array.\n key.slice(0, keyLength); // Cursor.key should be first part of array.\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n \n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n }\n}\n\nexport const virtualIndexMiddleware : Middleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\n","import { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from \"../public/types/dbcore\";\n\nexport function getEffectiveKeys (\n primaryKey: DBCoreIndex,\n req: (Pick & {keys?: any[]}) | Pick)\n{\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey)\n}\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange\n} from \"../public/types/dbcore\";\nimport { nop } from '../functions/chaining-functions';\nimport { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore: DBCore) => ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const {primaryKey} = downTable.schema;\n \n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req):Promise {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const {deleting, creating, updating} = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>deleteRange(req), true);\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n\n function addPutOrDelete(req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest): Promise {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error(\"Keys missing\");\n // Clone Request and set keys arg\n req = req.type === 'add' || req.type === 'put' ?\n {...req, keys} :\n {...req};\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n \n return getExistingValues(downTable, req, keys).then (existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (req.type === 'add' || existingValue === undefined) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({failures, results, numFailures, lastResult}) => {\n for (let i=0; i {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n \n function deleteRange(req: DBCoreDeleteRangeRequest): Promise {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n \n function deleteNextChunk(trans: DBCoreTransaction, range: DBCoreKeyRange, limit: number) {\n // Query what keys in the DB within the given range\n return downTable.query({trans, values: false, query: {index: primaryKey, range}, limit})\n .then(({result}) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({type: 'delete', keys: result, trans}).then(res => {\n if (res.numFailures > 0) return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {failures: [], numFailures: 0, lastResult: undefined} as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(trans, {...range, lower: result[result.length - 1], lowerOpen: true}, limit);\n }\n });\n })\n }\n }\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore\n};\n\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: readonly any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { DBCore, DBCoreTable } from '../../public/types/dbcore';\nimport { LiveQueryContext } from '../live-query';\n\nexport function isCachableContext(ctx: LiveQueryContext, table: DBCoreTable) {\n return (\n ctx.trans.mode === 'readonly' &&\n !!ctx.subscr &&\n !ctx.trans.explicit &&\n ctx.trans.db._options.cache !== 'disabled' &&\n !table.schema.primaryKey.outbound\n );\n}\n\n","import { DBCoreCountRequest, DBCoreGetManyRequest, DBCoreGetRequest, DBCoreOpenCursorRequest, DBCoreQueryRequest } from '../../public/types/dbcore';\n\n\nexport function isCachableRequest(type: string, req: Partial) {\n switch (type) {\n case 'query':\n return req.values && !req.unique;\n case 'get':\n return false;\n case 'getMany':\n return false;\n case 'count':\n return false;\n case 'openCursor':\n return false;\n }\n}\n","import { LiveQueryContext } from \".\";\nimport { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { getEffectiveKeys } from \"../dbcore/get-effective-keys\";\nimport { exceptions } from \"../errors\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport { isCachableContext } from \"./cache/is-cachable-context\";\nimport { isCachableRequest } from \"./cache/is-cachable-request\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n name: \"Observability\",\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n transaction: (stores, mode, options) => {\n if (PSD.subscr && mode !== 'readonly') {\n throw new exceptions.ReadOnly(`Readwrite transaction in liveQuery context. Querier source: ${(PSD as LiveQueryContext).querier}`);\n }\n return core.transaction(stores, mode, options);\n },\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts = req.mutatedParts || (req.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [getEffectiveKeys(primaryKey, req).filter(id => id), req.values] // keys except autoIncremented - they will be added later on.\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n\n const oldCache = req.trans[\"_cache\"];\n\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n // Individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null;\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs && type !== \"add\") {\n // delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // keys is a DBCoreKeyRange object. Transform it to [from,to]-style range.\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n\n return table.mutate(req).then((res) => {\n // Merge the mutated parts from the request into the transaction's mutatedParts\n // now when the request went fine.\n if (keys && (req.type === 'add' || req.type === 'put')) {\n // Less than 50 requests (keys truthy) (otherwise we've added full range anyway)\n // autoincrement means we might not have got all keys until now\n pkRangeSet.addKeys(res.results);\n }\n trans.mutatedParts = extendObservabilitySet (\n trans.mutatedParts || {},\n mutatedParts\n );\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD as LiveQueryContext;\n const isLiveQuery = !!subscr;\n let cachable = isCachableContext(PSD as LiveQueryContext, table) && isCachableRequest(method, req);\n const obsSet = cachable\n ? req.obsSet = {} // Implicit read transaction - track changes for this query only for the request's duration\n : subscr; // Explicit read transaction - track changes across entire live query\n\n if (isLiveQuery) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (obsSet[part] ||\n (obsSet[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: readonly any[] | undefined,\n newObjs: readonly any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n","import { cmp } from '../../functions/cmp';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function isAboveLower(key: IndexableType, range: DBCoreKeyRange) {\n return range.lower === undefined\n ? true // lower is less than anything because it is undefined\n : range.lowerOpen\n ? cmp(key, range.lower) > 0 // lowerOpen: Exclude lower bound\n : cmp(key, range.lower) >= 0; // !lowerOpen: Include lower bound\n}\n\nexport function isBelowUpper(key: IndexableType, range: DBCoreKeyRange) {\n return range.upper === undefined\n ? true // upper is greater than anything because it is undefined\n : range.upperOpen\n ? cmp(key, range.upper) < 0 // upperOpen: Exclude upper bound\n : cmp(key, range.upper) <= 0; // !upperOpen: Include upper bound\n}\n\nexport function isWithinRange(key: IndexableType, range: DBCoreKeyRange) {\n return isAboveLower(key, range) && isBelowUpper(key, range);\n}\n","import { cmp } from '../../functions/cmp';\nimport { deepClone } from '../../functions/utils';\nimport { RangeSet, rangesOverlap } from '../../helpers/rangeset';\nimport { CacheEntry } from '../../public/types/cache';\nimport {\n DBCoreIndex,\n DBCoreMutateRequest,\n DBCoreQueryRequest,\n DBCoreTable,\n} from '../../public/types/dbcore';\nimport { isWithinRange } from './is-within-range';\n\nexport function applyOptimisticOps(\n result: any[],\n req: DBCoreQueryRequest,\n ops: DBCoreMutateRequest[] | undefined,\n table: DBCoreTable,\n cacheEntry: CacheEntry,\n immutable: boolean\n): any[] {\n if (!ops || ops.length === 0) return result;\n const index = req.query.index;\n const primaryKey = table.schema.primaryKey;\n const extractPrimKey = primaryKey.extractKey;\n const extractIndex = index.extractKey;\n const extractLowLevelIndex = (index.lowLevelIndex || index).extractKey;\n\n let finalResult = ops.reduce((result, op) => {\n let modifedResult = result;\n const includedValues =\n op.type === 'add' || op.type === 'put'\n ? op.values.filter((v) =>\n isWithinRange(extractIndex(v), req.query.range)\n ).map(v => {\n v = deepClone(v);// v might come from user so we can't just freeze it.\n if (immutable) Object.freeze(v);\n return v;\n }) \n : [];\n switch (op.type) {\n case 'add':\n modifedResult = result.concat(\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n case 'put':\n const keySet = new RangeSet().addKeys(\n op.values.map((v) => extractPrimKey(v))\n );\n modifedResult = result\n .filter((item) => {\n const key = req.values ? extractPrimKey(item) : item;\n return !rangesOverlap(new RangeSet(key), keySet);\n })\n .concat(\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n case 'delete':\n const keysToDelete = new RangeSet().addKeys(op.keys);\n modifedResult = result.filter((item) => {\n const key = req.values ? extractPrimKey(item) : item;\n return !rangesOverlap(new RangeSet(key), keysToDelete);\n });\n\n break;\n case 'deleteRange':\n const range = op.range;\n modifedResult = result.filter((item) => !isWithinRange(extractPrimKey(item), range));\n break;\n }\n return modifedResult;\n }, result);\n\n // If no changes were made, we can return the original result.\n if (finalResult === result) return result;\n\n // Sort the result on sortIndex:\n finalResult.sort((a, b) =>\n cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) ||\n cmp(extractPrimKey(a), extractPrimKey(b))\n );\n\n // If we have a limit we need to respect it:\n if (req.limit && req.limit < Infinity) {\n if (finalResult.length > req.limit) {\n finalResult.length = req.limit; // Cut of any extras after sorting correctly.\n } else if (result.length === req.limit && finalResult.length < req.limit) {\n // We're missing some items because of the limit. We need to add them back.\n // The easiest way is to mark the cache entry as dirty, which will cause\n // it to be requeried after the write-transaction successfully completes.\n cacheEntry.dirty = true;\n }\n }\n return immutable ? Object.freeze(finalResult) as any[] : finalResult;\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function areRangesEqual(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n cmp(r1.lower, r2.lower) === 0 &&\n cmp(r1.upper, r2.upper) === 0 &&\n !!r1.lowerOpen === !!r2.lowerOpen &&\n !!r1.upperOpen === !!r2.upperOpen\n );\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function compareLowers(lower1: any, lower2: any, lowerOpen1: boolean, lowerOpen2: boolean) {\n if (lower1 === undefined) return lower2 !== undefined ? -1 : 0;\n if (lower2 === undefined) return 1; // since lower1 !== undefined\n const c = cmp(lower1, lower2);\n if (c === 0) {\n if (lowerOpen1 && lowerOpen2) return 0;\n if (lowerOpen1) return 1\n if (lowerOpen2) return -1;\n }\n return c;\n}\n\nexport function compareUppers(upper1: any, upper2: any, upperOpen1: boolean, upperOpen2: boolean) {\n if (upper1 === undefined) return upper2 !== undefined ? 1 : 0;\n if (upper2 === undefined) return -1; // since upper1 !== undefined\n const c = cmp(upper1, upper2);\n if (c === 0) {\n if (upperOpen1 && upperOpen2) return 0;\n if (upperOpen1) return -1\n if (upperOpen2) return 1;\n }\n return c;\n}\n\nexport function isSuperRange(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 &&\n compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0\n );\n}","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreCountRequest,\n DBCoreQueryRequest,\n} from '../../public/types/dbcore';\nimport { areRangesEqual } from './are-ranges-equal';\nimport { cache } from './cache';\nimport { isSuperRange } from './is-super-range';\n\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query',\n req: DBCoreQueryRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'count',\n req: DBCoreCountRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query' | 'count',\n req: Partial & Partial\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]] {\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return [];\n const queries = tblCache.queries[type];\n if (!queries) return [null, false, tblCache, null];\n const indexName = req.query ? req.query.index.name : null;\n const entries = queries[indexName || ''];\n if (!entries) return [null, false, tblCache, null];\n\n switch (type) {\n case 'query':\n const equalEntry = entries.find(\n (entry) =>\n (entry.req as DBCoreQueryRequest).limit === req.limit &&\n (entry.req as DBCoreQueryRequest).values === req.values &&\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n if (equalEntry)\n return [\n equalEntry,\n true, // exact match\n tblCache,\n entries,\n ];\n const superEntry = entries.find((entry) => {\n const limit = 'limit' in entry.req ? entry.req.limit : Infinity;\n return (\n limit >= req.limit &&\n (req.values ? (entry.req as DBCoreQueryRequest).values : true) &&\n isSuperRange(entry.req.query.range, req.query.range)\n );\n });\n return [superEntry, false, tblCache, entries];\n case 'count':\n const countQuery = entries.find((entry) =>\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n return [countQuery, !!countQuery, tblCache, entries];\n }\n}\n","import { delArrayItem } from \"../../functions/utils\";\nimport { CacheEntry } from \"../../public/types/cache\";\n\nexport function subscribeToCacheEntry(cacheEntry: CacheEntry, container: CacheEntry[], requery: ()=>void, signal: AbortSignal) {\n cacheEntry.subscribers.add(requery);\n signal.addEventListener(\"abort\", () => {\n cacheEntry.subscribers.delete(requery);\n if (cacheEntry.subscribers.size === 0) {\n enqueForDeletion(cacheEntry, container);\n }\n });\n}\n\n\nfunction enqueForDeletion(cacheEntry: CacheEntry, container: CacheEntry[]) {\n setTimeout(() => {\n if (cacheEntry.subscribers.size === 0) { // Still empty (no new subscribers readded after grace time)\n delArrayItem(container, cacheEntry);\n }\n }, 3000);\n}\n","import { LiveQueryContext } from '..';\nimport { getEffectiveKeys } from '../../dbcore/get-effective-keys';\nimport { deepClone, delArrayItem, setByKeyPath } from '../../functions/utils';\nimport DexiePromise, { PSD } from '../../helpers/promise';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport {\n DBCore, DBCoreQueryRequest,\n DBCoreQueryResponse\n} from '../../public/types/dbcore';\nimport { Middleware } from '../../public/types/middleware';\nimport { applyOptimisticOps } from './apply-optimistic-ops';\nimport { cache } from './cache';\nimport { findCompatibleQuery } from './find-compatible-query';\nimport { isCachableContext } from './is-cachable-context';\nimport { isCachableRequest } from './is-cachable-request';\nimport { signalSubscribersLazily } from './signalSubscribers';\nimport { subscribeToCacheEntry } from './subscribe-cachentry';\n\nexport const cacheMiddleware: Middleware = {\n stack: 'dbcore',\n level: 0,\n name: 'Cache',\n create: (core) => {\n const dbName = core.schema.name;\n const coreMW: DBCore = {\n ...core,\n transaction: (stores, mode, options) => {\n const idbtrans = core.transaction(\n stores,\n mode,\n options\n ) as IDBTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n // Maintain TblQueryCache.ops array when transactions commit or abort\n if (mode === 'readwrite') {\n const ac = new AbortController();\n const { signal } = ac;\n const endTransaction = (wasCommitted: boolean) => () => {\n ac.abort();\n if (mode === 'readwrite') {\n // Collect which subscribers to notify:\n const affectedSubscribers = new Set<()=>void>();\n\n // Go through all tables in transaction and check if they have any optimistic updates\n for (const storeName of stores) {\n const tblCache = cache[`idb://${dbName}/${storeName}`];\n const table = core.table(storeName);\n if (tblCache) {\n // Pick optimistic ops that are part of this transaction\n const ops = tblCache.optimisticOps.filter(\n (op) => op.trans === idbtrans\n );\n if (ops.length > 0) {\n // Remove them from the optimisticOps array\n tblCache.optimisticOps = tblCache.optimisticOps.filter(\n (op) => op.trans !== idbtrans\n );\n // Commit or abort the optimistic updates\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (\n entry.res != null && // if entry.promise but not entry.res, we're fine. Query will resume now and get the result.\n idbtrans.mutatedParts/* &&\n obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)*/\n ) {\n if (wasCommitted && !entry.dirty) {\n const freezeResults = Object.isFrozen(entry.res);\n const modRes = applyOptimisticOps(\n entry.res as any[],\n entry.req,\n ops,\n table,\n entry,\n freezeResults\n );\n if (entry.dirty) {\n // Found out at this point that the entry is dirty - not to rely on!\n delArrayItem(entries, entry);\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n } else if (modRes !== entry.res) {\n entry.res = modRes;\n // Update promise\n entry.promise = DexiePromise.resolve({result: modRes} satisfies DBCoreQueryResponse);\n \n // No need to notify subscribers. They already have this value.\n // We have just updated the value of the cache without having to\n // requery the database - because we know the result for this\n // query based on computing the operations and applying them\n // to the previous result.\n }\n } else {\n if (entry.dirty) {\n // If the entry is dirty we need to get rid of it so that\n // a new entry will be created when the query is run again.\n delArrayItem(entries, entry);\n }\n // If we're not committing, we need to notify subscribers that the\n // optimistic updates are no longer valid.\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n }\n }\n }\n }\n }\n }\n }\n affectedSubscribers.forEach((requery) => requery());\n }\n };\n idbtrans.addEventListener('abort', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('error', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('complete', endTransaction(true), {\n signal,\n });\n }\n return idbtrans;\n },\n table(tableName: string) {\n const downTable = core.table(tableName);\n const primKey = downTable.schema.primaryKey;\n const tableMW = {\n ...downTable,\n mutate(req) {\n if (\n primKey.outbound || // Non-inbound tables are harded to apply optimistic updates on because we can't know primary key of results\n PSD.trans.db._options.cache === 'disabled' // User has opted-out from caching\n ) {\n // Just forward the request to the core.\n return downTable.mutate(req);\n }\n // Find the TblQueryCache for this table:\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return downTable.mutate(req);\n\n const promise = downTable.mutate(req);\n if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(key => key == null))) {\n // There are some autoIncremented keys not set yet. Need to wait for completion before we can reliably enqueue the operation.\n // (or there are too many objects so we lazy out to avoid performance bottleneck for large bulk inserts)\n promise.then((res) => { // We need to extract result keys and generate cloned values with the keys set (so that applyOptimisticOps can work)\n // But we have a problem! The req.mutatedParts is still not complete so we have to actively add the keys to the unsignaledParts set manually.\n const reqWithResolvedKeys = {\n ...req,\n values: req.values.map((value, i) => {\n const valueWithKey = primKey.keyPath.includes('.')\n ? deepClone(value)\n : {\n ...value,\n };\n setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]);\n return valueWithKey;\n })\n };\n tblCache.optimisticOps.push(reqWithResolvedKeys);\n // Signal subscribers after the observability middleware has complemented req.mutatedParts with the new keys.\n // We must queue the task so that we get the req.mutatedParts updated by observability middleware first.\n // If we refactor the dependency between observability middleware and this middleware we might not need to queue the task.\n queueMicrotask(()=>signalSubscribersLazily(req.mutatedParts)); // Reason for double laziness: in user awaits put and then does another put, signal once.\n });\n } else {\n // Enque the operation immediately\n tblCache.optimisticOps.push(req);\n // Signal subscribers that there are mutated parts\n signalSubscribersLazily(req.mutatedParts);\n promise.catch(()=> {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n });\n }\n return promise;\n },\n query(req: DBCoreQueryRequest): Promise {\n if (!isCachableContext(PSD, downTable) || !isCachableRequest(\"query\", req)) return downTable.query(req);\n const freezeResults =\n (PSD as LiveQueryContext).trans.db._options.cache === 'immutable';\n const { requery, signal } = PSD as LiveQueryContext;\n let [cacheEntry, exactMatch, tblCache, container] =\n findCompatibleQuery(dbName, tableName, 'query', req);\n if (cacheEntry && exactMatch) {\n cacheEntry.obsSet = req.obsSet; // So that optimistic result is monitored.\n // How? - because observability-middleware will track result where optimistic\n // mutations are applied and record it in the cacheEntry.\n // TODO: CHANGE THIS! The difference is resultKeys only.\n // Wanted behavior:\n // * cacheEntry obsSet should represent the obsSet without optimistic updates (so it can be checked when merging ops in tx commit)\n // * cacheEntry optimisticObsSet should represent the obsSet with current optimistic updates. It should be updated when adding an op\n // by adding the primary keys of the put/add/delete operation to the set.\n // * observability-middleware should stop recording req.obsSet when a cache entry exact match is found because it won't be used anyway.\n // I'm thinking of merging observability-middleware with cache-middleware into one single middleware because the dependencies are too\n // tight between them.\n } else {\n // --> TODO here: If not exact match, check if we have a superset to extract\n // the data from.\n\n // No cached result found. We need to query the database and cache the result.\n const promise = downTable.query(req).then((res) => {\n // Freeze or clone results\n const result = res.result;\n cacheEntry.res = result;\n if (freezeResults) {\n // For performance reasons don't deep freeze.\n // Only freeze the top-level array and its items.\n // This is good enough to teach users that the result must be treated as immutable\n // without enforcing it recursively on the entire result (which is not even possible\n // for things like Date objects and typed arrays)\n for (let i = 0, l = result.length; i < l; ++i) {\n Object.freeze(result[i]);\n }\n Object.freeze(result);\n } else {\n // If not frozen, we need to clone the result to avoid user mutating the cache\n // When we do this, user's must feel conformable with the fact that the result\n // can be mutated deeply - user is not expected to have any respect for immutability.\n res.result = deepClone(result);\n }\n return res;\n }).catch(error => {\n // In case the query operation failed, we need to remove it from the cache\n // so that subsequent calls does not get the same error but re-evaluate\n // the query.\n if (container && cacheEntry) delArrayItem(container, cacheEntry);\n return Promise.reject(error);\n });\n cacheEntry = {\n obsSet: req.obsSet,\n promise,\n subscribers: new Set(),\n type: 'query',\n req,\n dirty: false,\n };\n if (container) {\n container.push(cacheEntry);\n } else {\n container = [cacheEntry];\n if (!tblCache) {\n tblCache = cache[`idb://${dbName}/${tableName}`] = {\n queries: {\n query: {},\n count: {},\n },\n objs: new Map(),\n optimisticOps: [],\n unsignaledParts: {}\n };\n }\n tblCache.queries.query[req.query.index.name || ''] = container;\n }\n }\n subscribeToCacheEntry(cacheEntry, container, requery, signal);\n return cacheEntry.promise.then((res: DBCoreQueryResponse) => {\n return {\n result: applyOptimisticOps(\n res.result,\n req,\n tblCache?.optimisticOps,\n downTable,\n cacheEntry,\n freezeResults\n ) as any[], // readonly any[]\n };\n });\n },\n };\n return tableMW;\n },\n };\n return coreMW;\n },\n};\n\n\n","import { type Dexie } from \"../classes/dexie\";\nimport { type Table } from \"../classes/table\";\nimport { type Transaction } from \"../classes/transaction\";\n\nexport function vipify(\n target: T,\n vipDb: Dexie\n): T {\n return new Proxy(target, {\n get (target, prop, receiver) {\n // The \"db\" prop of the table or transaction is the only one we need to\n // override. The rest of the props can be accessed from the original\n // object.\n if (prop === 'db') return vipDb;\n return Reflect.get(target, prop, receiver);\n }\n });\n}\n","// Import types from the public API\nimport { Dexie as IDexie } from \"../../public/types/dexie\";\nimport { DexieOptions, DexieConstructor } from \"../../public/types/dexie-constructor\";\nimport { DbEvents } from \"../../public/types/db-events\";\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from \"../../public/types/table-schema\";\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from \"../table\";\nimport { Collection, CollectionConstructor, createCollectionConstructor } from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor';\nimport { Version } from \"../version/version\";\nimport { VersionConstructor, createVersionConstructor } from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD, globalPSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport { maxString, connections, READONLY, READWRITE } from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { _onDatabaseDeleted } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport { extractTransactionArgs, enterTransactionScope } from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\nimport { cacheMiddleware } from \"../../live-query/cache/cache-middleware\";\nimport { vipify } from \"../../helpers/vipify\";\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n PR1398_maxLoop?: number;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table; };\n _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema; };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {[StackName in keyof DexieStacks]?: Middleware[]} = {};\n _vip?: boolean;\n _novip: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\n on: DbEvents;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n cache: 'cloned', // Default to cloned for backward compatibility. For best performance and least memory consumption use 'immutable'.\n ...options\n }; \n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange\n };\n const {\n addons,\n } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true,\n PR1398_maxLoop: 3\n };\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] }) as DbEvents;\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n const db = this;\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n this.on(\"versionchange\", ev => {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.close({disableAutoOpen: false});\n this._state.openComplete = false;\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction);\n\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n // Default middlewares:\n this.use(cacheExistingValuesMiddleware);\n this.use(cacheMiddleware);\n this.use(observabilityMiddleware);\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n const vipDB = new Proxy(this, {\n get: (_, prop, receiver) => {\n if (prop === '_vip') return true;\n if (prop === 'table') return (tableName: string) => vipify(this.table(tableName), vipDB);\n const rv = Reflect.get(_, prop, receiver);\n if (rv instanceof Table) return vipify(rv, vipDB);\n if (prop === 'tables') return (rv as Table[]).map(t => vipify(t, vipDB));\n if (prop === '_createTransaction') return function() {\n const tx: Transaction = (rv as typeof this._createTransaction).apply(this, arguments);\n return vipify(tx, vipDB);\n }\n return rv;\n }\n });\n this.vip = vipDB;\n\n // Call each addon:\n addons.forEach(addon => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n v => v._cfg.version === versionNumber)[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady(fn: () => Promise): Promise {\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({stack, create, level, name}: Middleware): this {\n if (name) this.unuse({stack, name}); // Be able to replace existing middleware.\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({stack, create, level: level == null ? 10 : level, name});\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this;\n unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this;\n unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw =>\n create ? mw.create !== create : // Given middleware has a create method. Match that exactly.\n name ? mw.name !== name : // Given middleware spec \n false);\n }\n return this;\n }\n\n open() {\n return usePSD(\n globalPSD, // Enforce global scope here since db.open() can be part of a live query or transaction scope\n () => dexieOpen(this)\n );\n }\n\n _close(): void {\n const state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this.idbdb = null;\n } \n // Reset dbReadyPromise promise:\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n\n close({disableAutoOpen} = {disableAutoOpen: true}): void {\n this._close();\n const state = this._state;\n if (disableAutoOpen) this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n }\n\n delete(): Promise {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close({disableAutoOpen: false});\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n }\n\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables () {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(mode: TransactionMode, tables: Array, scopeFunc: Function) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode,\n storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map(table => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) :\n this._whenReady (enterTransaction));\n }\n\n table(tableName: string): Table;\n table(tableName: string): ITable;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return this._allTables[tableName];\n }\n}\n","import {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { isAsyncFunction, keys, objectIsEmpty } from '../functions/utils';\nimport {\n globalEvents,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport {\n beginMicroTickScope,\n decrementExpectedAwaits,\n endMicroTickScope,\n incrementExpectedAwaits,\n newScope,\n PSD,\n usePSD,\n} from '../helpers/promise';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport {\n Observable as IObservable,\n Subscription,\n} from '../public/types/observable';\nimport { Observable } from '../classes/observable/observable';\nimport { extendObservabilitySet } from './extend-observability-set';\nimport { rangesOverlap } from '../helpers/rangeset';\nimport { domDeps } from '../classes/dexie/dexie-dom-dependencies';\nimport { Transaction } from '../classes/transaction';\nimport { obsSetsOverlap } from './obs-sets-overlap';\n\nexport interface LiveQueryContext {\n subscr: ObservabilitySet;\n signal: AbortSignal;\n requery: () => void;\n trans: null | Transaction;\n querier: Function; // For debugging purposes and Error messages\n}\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(ctx: LiveQueryContext) {\n const wasRootExec = beginMicroTickScope(); // Performance: Avoid starting a new microtick scope within the async context.\n try {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const rv = newScope(querier, ctx);\n if (scopeFuncIsAsync) {\n (rv as Promise).finally(decrementExpectedAwaits);\n }\n return rv;\n } finally {\n wasRootExec && endMicroTickScope(); // Given that we created the microtick scope, we must also end it.\n }\n }\n\n let closed = false;\n let abortController: AbortController;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n if (closed) return;\n closed = true;\n if (abortController) abortController.abort();\n if (startedListening) globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let startedListening = false;\n\n function shouldNotify() {\n return obsSetsOverlap(currentObs, accumMuts);\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const doQuery = () => {\n if (\n closed || // closed - don't run!\n !domDeps.indexedDB) // SSR in sveltekit, nextjs etc\n {\n return;\n }\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n // Abort signal fill three purposes:\n // 1. Abort the query if the observable is unsubscribed.\n // 2. Abort the query if a new query is made before the previous one has completed.\n // 3. For cached queries to know if they should remain in memory or could be enqued for being freed up.\n // (they will remain in memory for a short time and if noone needs them again, they will eventually be freed up)\n if (abortController) abortController.abort(); // Cancel previous query. Last query will be cancelled on unsubscribe().\n abortController = new AbortController();\n \n const ctx: LiveQueryContext = {\n subscr,\n signal: abortController.signal,\n requery: doQuery,\n querier,\n trans: null // Make the scope transactionless (don't reuse transaction from outer scope of the caller of subscribe())\n }\n const ret = execute(ctx);\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n if (closed || ctx.signal.aborted) {\n // closed - no subscriber anymore.\n // signal.aborted - new query was made before this one completed and\n // the querier might have catched AbortError and return successful result.\n // If so, we should not rely in that result because we know we have aborted\n // this run, which means there's another run going on that will handle accumMuts\n // and we must not base currentObs on the half-baked subscr.\n return;\n }\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n if (!objectIsEmpty(currentObs) && !startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n } \n observer.next && observer.next(result);\n },\n (err) => {\n hasValue = false;\n if (!['DatabaseClosedError', 'AbortError'].includes(err?.name)) {\n if (closed) return;\n observer.error && observer.error(err);\n }\n }\n );\n };\n\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } from '../../helpers/database-enumerator';\nimport { PSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { dexieStackFrameFilter, minKey, connections, DEXIE_VERSION } from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\nimport { cache } from '../../live-query/cache/cache';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n// \nprops(Dexie, {\n\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName, {addons: []});\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap,\n //maxKey: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: domDeps,\n cache,\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n // default: Dexie, // Commented because solved in index-umd.ts instead.\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n // Dexie: Dexie // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { isIEOrEdge } from '../globals/constants';\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport { signalSubscribersNow } from './cache/signalSubscribers';\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n } else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\n/** Called from listeners to BroadcastChannel and DOM event to\n * propagate the event locally into dexie's storagemutated event\n * and invalidate cached queries.\n * \n * This function is only called when the event is not originating\n * from this same Dexie module - either from another redundant dexie import\n * or from a foreign tab or worker. That's why we need to invalidate\n * the cache when this happens.\n */\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n // Fire the \"storagemutated\" event.\n globalEvents.storagemutated.fire(updateParts);\n // Invalidate cached queries and signal subscribers to requery.\n signalSubscribersNow(updateParts, true);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n }\n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n bc.onmessage = (ev) => {\n if (ev.data) propagateLocally(ev.data);\n };\n} else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n // DOM verified - when typeof self !== \"undefined\", we are a window or worker. Not a Node process.\n\n //\n // Propagate local changes to remote tabs/windows via storage event and service worker\n // via messages. We have this code here because of https://bugs.webkit.org/show_bug.cgi?id=161472.\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n // We're a browsing window or tab. Propagate to other windows/tabs via storage event:\n localStorage.setItem(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n JSON.stringify({\n trig: Math.random(),\n changedParts,\n })\n );\n }\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n })\n );\n }\n }\n } catch {}\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev: StorageEvent) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data) propagateLocally(data.changedParts);\n }\n });\n }\n\n //\n // Propagate messages from service worker\n //\n const swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\n if (swContainer) {\n // We're a browser window and want to propagate message from the SW:\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\n\nfunction propagateMessageLocally({ data }: MessageEvent) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport { dexieStackFrameFilter } from './globals/constants';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport { liveQuery } from './live-query/live-query';\nimport { Entity } from './classes/entity/Entity';\nimport { cmp } from './functions/cmp';\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport { Entity };\nexport { c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gBAC7C,IAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;gBACrC,IAAI,IAAI;oBAAE,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;aAC/C;SACF,CAAC,CAAC;KACJ;IAKD,IAAM,WAAW,GAAG,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC,aAAa,CAAC;IAC7D,IAAI,WAAW,EAAE;QAEf,WAAW,CAAC,gBAAgB,CAAC,SAAS,EAAE,uBAAuB,CAAC,CAAC;KAClE;CACF;AAED,SAAS,uBAAuB,CAAC,EAAsB;QAApB,IAAI,UAAA;IACrC,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,8BAA8B,EAAE;QACxD,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACrC;AACH;;AC9EA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCQ,QAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC;;;;"} \ No newline at end of file diff --git a/dist/modern/dexie.min.mjs b/dist/modern/dexie.min.mjs new file mode 100644 index 000000000..9ad2a65b5 --- /dev/null +++ b/dist/modern/dexie.min.mjs @@ -0,0 +1,2 @@ +const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,t=Object.keys,n=Array.isArray;function r(e,n){return"object"!=typeof n||t(n).forEach((function(t){e[t]=n[t]})),e}"undefined"==typeof Promise||e.Promise||(e.Promise=Promise);const s=Object.getPrototypeOf,i={}.hasOwnProperty;function o(e,t){return i.call(e,t)}function a(e,n){"function"==typeof n&&(n=n(s(e))),("undefined"==typeof Reflect?t:Reflect.ownKeys)(n).forEach((t=>{l(e,t,n[t])}))}const u=Object.defineProperty;function l(e,t,n,s){u(e,t,r(n&&o(n,"get")&&"function"==typeof n.get?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},s))}function c(e){return{from:function(t){return e.prototype=Object.create(t.prototype),l(e.prototype,"constructor",e),{extend:a.bind(null,e.prototype)}}}}const h=Object.getOwnPropertyDescriptor;function d(e,t){let n;return h(e,t)||(n=s(e))&&d(n,t)}const f=[].slice;function p(e,t,n){return f.call(e,t,n)}function y(e,t){return t(e)}function m(e){if(!e)throw new Error("Assertion Failed")}function b(t){e.setImmediate?setImmediate(t):setTimeout(t,0)}function g(e,t){if("string"==typeof t&&o(e,t))return e[t];if(!t)return e;if("string"!=typeof t){for(var n=[],r=0,s=t.length;r["Int","Uint","Float"].map((t=>t+e+"Array")))))).filter((t=>e[t])),O=new Set(k.map((t=>e[t])));function P(e){const t={};for(const n in e)if(o(e,n)){const r=e[n];t[n]=!r||"object"!=typeof r||O.has(r.constructor)?r:P(r)}return t}let E=null;function K(e){E=new WeakMap;const t=S(e);return E=null,t}function S(e){if(!e||"object"!=typeof e)return e;let t=E.get(e);if(t)return t;if(n(e)){t=[],E.set(e,t);for(var r=0,i=e.length;r=0&&e.splice(n,1),n>=0}const I={};function B(e){var t,r,s,i;if(1===arguments.length){if(n(e))return e.slice();if(this===I&&"string"==typeof e)return[e];if(i=q(e)){for(r=[];!(s=i.next()).done;)r.push(s.value);return r}if(null==e)return[e];if("number"==typeof(t=e.length)){for(r=new Array(t);t--;)r[t]=e[t];return r}return[e]}for(t=arguments.length,r=new Array(t);t--;)r[t]=arguments[t];return r}const T="undefined"!=typeof Symbol?e=>"AsyncFunction"===e[Symbol.toStringTag]:()=>!1;var R="undefined"!=typeof location&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function F(e,t){R=e,M=t}var M=()=>!0;const N=!new Error("").stack;function $(){if(N)try{throw $.arguments,new Error}catch(e){return e}return new Error}function L(e,t){var n=e.stack;return n?(t=t||0,0===n.indexOf(e.name)&&(t+=(e.name+e.message).split("\n").length),n.split("\n").slice(t).filter(M).map((e=>"\n"+e)).join("")):""}var U=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],V=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(U),z={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function W(e,t){this._e=$(),this.name=e,this.message=t}function Y(e,t){return e+". Errors: "+Object.keys(t).map((e=>t[e].toString())).filter(((e,t,n)=>n.indexOf(e)===t)).join("\n")}function G(e,t,n,r){this._e=$(),this.failures=t,this.failedKeys=r,this.successCount=n,this.message=Y(e,t)}function H(e,t){this._e=$(),this.name="BulkError",this.failures=Object.keys(t).map((e=>t[e])),this.failuresByPos=t,this.message=Y(e,this.failures)}c(W).from(Error).extend({stack:{get:function(){return this._stack||(this._stack=this.name+": "+this.message+L(this._e,2))}},toString:function(){return this.name+": "+this.message}}),c(G).from(W),c(H).from(W);var Q=V.reduce(((e,t)=>(e[t]=t+"Error",e)),{});const X=W;var J=V.reduce(((e,t)=>{var n=t+"Error";function r(e,r){this._e=$(),this.name=n,e?"string"==typeof e?(this.message=`${e}${r?"\n "+r:""}`,this.inner=r||null):"object"==typeof e&&(this.message=`${e.name} ${e.message}`,this.inner=e):(this.message=z[t]||n,this.inner=null)}return c(r).from(X),e[t]=r,e}),{});J.Syntax=SyntaxError,J.Type=TypeError,J.Range=RangeError;var Z=U.reduce(((e,t)=>(e[t+"Error"]=J[t],e)),{});var ee=V.reduce(((e,t)=>(-1===["Syntax","Type","Range"].indexOf(t)&&(e[t+"Error"]=J[t]),e)),{});function te(){}function ne(e){return e}function re(e,t){return null==e||e===ne?t:function(n){return t(e(n))}}function se(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function ie(e,t){return e===te?t:function(){var n=e.apply(this,arguments);void 0!==n&&(arguments[0]=n);var r=this.onsuccess,s=this.onerror;this.onsuccess=null,this.onerror=null;var i=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?se(r,this.onsuccess):r),s&&(this.onerror=this.onerror?se(s,this.onerror):s),void 0!==i?i:n}}function oe(e,t){return e===te?t:function(){e.apply(this,arguments);var n=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?se(n,this.onsuccess):n),r&&(this.onerror=this.onerror?se(r,this.onerror):r)}}function ae(e,t){return e===te?t:function(n){var s=e.apply(this,arguments);r(n,s);var i=this.onsuccess,o=this.onerror;this.onsuccess=null,this.onerror=null;var a=t.apply(this,arguments);return i&&(this.onsuccess=this.onsuccess?se(i,this.onsuccess):i),o&&(this.onerror=this.onerror?se(o,this.onerror):o),void 0===s?void 0===a?void 0:a:r(s,a)}}function ue(e,t){return e===te?t:function(){return!1!==t.apply(this,arguments)&&e.apply(this,arguments)}}function le(e,t){return e===te?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then((function(){return t.apply(r,i)}))}return t.apply(this,arguments)}}ee.ModifyError=G,ee.DexieError=W,ee.BulkError=H;var ce={};const[he,de,fe]="undefined"==typeof Promise?[]:(()=>{let e=Promise.resolve();if("undefined"==typeof crypto||!crypto.subtle)return[e,s(e),e];const t=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[t,s(t),e]})(),pe=de&&de.then,ye=he&&he.constructor,me=!!fe;var be=!1;var ge=function(e,t){Ke.push([e,t]),we&&(queueMicrotask(Ne),we=!1)},ve=!0,we=!0,_e=[],xe=[],ke=null,Oe=ne,Pe={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:te,pgp:!1,env:{},finalize:te},Ee=Pe,Ke=[],Se=0,Ae=[];function Ce(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var t=this._PSD=Ee;if(R&&(this._stackHolder=$(),this._prev=null,this._numPrev=0),"function"!=typeof e){if(e!==ce)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(!1===this._state&&Ie(this,this._value))}this._state=null,this._value=null,++t.ref,De(this,e)}const je={get:function(){var e=Ee,t=Qe;function n(n,r){var s=!e.global&&(e!==Ee||t!==Qe);const i=s&&!et();var o=new Ce(((t,o)=>{Te(this,new qe(at(n,e,s,i),at(r,e,s,i),t,o,e))}));return R&&Me(o,this),o}return n.prototype=ce,n},set:function(e){l(this,"then",e&&e.prototype===ce?je:{get:function(){return e},set:je.set})}};function qe(e,t,n,r,s){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.resolve=n,this.reject=r,this.psd=s}function De(e,t){try{t((t=>{if(null===e._state){if(t===e)throw new TypeError("A promise cannot be resolved with itself.");var n=e._lib&&$e();t&&"function"==typeof t.then?De(e,((e,n)=>{t instanceof Ce?t._then(e,n):t.then(e,n)})):(e._state=!0,e._value=t,Be(e)),n&&Le()}}),Ie.bind(null,e))}catch(t){Ie(e,t)}}function Ie(e,t){if(xe.push(t),null===e._state){var n=e._lib&&$e();t=Oe(t),e._state=!1,e._value=t,R&&null!==t&&"object"==typeof t&&!t._promise&&function(e,t,n){try{e.apply(null,n)}catch(e){t&&t(e)}}((()=>{var n=d(t,"stack");t._promise=e,l(t,"stack",{get:()=>be?n&&(n.get?n.get.apply(t):n.value):e.stack})})),function(e){_e.some((t=>t._value===e._value))||_e.push(e)}(e),Be(e),n&&Le()}}function Be(e){var t=e._listeners;e._listeners=[];for(var n=0,r=t.length;n{0==--Se&&Ue()}),[]))}function Te(e,t){if(null!==e._state){var n=e._state?t.onFulfilled:t.onRejected;if(null===n)return(e._state?t.resolve:t.reject)(e._value);++t.psd.ref,++Se,ge(Re,[n,e,t])}else e._listeners.push(t)}function Re(e,t,n){try{ke=t;var r,s=t._value;t._state?r=e(s):(xe.length&&(xe=[]),r=e(s),-1===xe.indexOf(s)&&function(e){var t=_e.length;for(;t;)if(_e[--t]._value===e._value)return void _e.splice(t,1)}(t)),n.resolve(r)}catch(e){n.reject(e)}finally{ke=null,0==--Se&&Ue(),--n.psd.ref||n.psd.finalize()}}function Fe(e,t,n){if(t.length===n)return t;var r="";if(!1===e._state){var s,i,o=e._value;null!=o?(s=o.name||"Error",i=o.message||o,r=L(o,0)):(s=o,i=""),t.push(s+(i?": "+i:"")+r)}return R&&((r=L(e._stackHolder,2))&&-1===t.indexOf(r)&&t.push(r),e._prev&&Fe(e._prev,t,n)),t}function Me(e,t){var n=t?t._numPrev+1:0;n<100&&(e._prev=t,e._numPrev=n)}function Ne(){ot(Pe,(()=>{$e()&&Le()}))}function $e(){var e=ve;return ve=!1,we=!1,e}function Le(){var e,t,n;do{for(;Ke.length>0;)for(e=Ke,Ke=[],n=e.length,t=0;t0);ve=!0,we=!0}function Ue(){var e=_e;_e=[],e.forEach((e=>{e._PSD.onunhandled.call(null,e._value,e)}));for(var t=Ae.slice(0),n=t.length;n;)t[--n]()}function Ve(e){return new Ce(ce,!1,e)}function ze(e,t){var n=Ee;return function(){var r=$e(),s=Ee;try{return st(n,!0),e.apply(this,arguments)}catch(e){t&&t(e)}finally{st(s,!1),r&&Le()}}}a(Ce.prototype,{then:je,_then:function(e,t){Te(this,new qe(null,null,e,t,Ee))},catch:function(e){if(1===arguments.length)return this.then(null,e);var t=arguments[0],n=arguments[1];return"function"==typeof t?this.then(null,(e=>e instanceof t?n(e):Ve(e))):this.then(null,(e=>e&&e.name===t?n(e):Ve(e)))},finally:function(e){return this.then((t=>(e(),t)),(t=>(e(),Ve(t))))},stack:{get:function(){if(this._stack)return this._stack;try{be=!0;var e=Fe(this,[],20).join("\nFrom previous: ");return null!==this._state&&(this._stack=e),e}finally{be=!1}}},timeout:function(e,t){return e<1/0?new Ce(((n,r)=>{var s=setTimeout((()=>r(new J.Timeout(t))),e);this.then(n,r).finally(clearTimeout.bind(null,s))})):this}}),"undefined"!=typeof Symbol&&Symbol.toStringTag&&l(Ce.prototype,Symbol.toStringTag,"Dexie.Promise"),Pe.env=it(),a(Ce,{all:function(){var e=B.apply(null,arguments).map(tt);return new Ce((function(t,n){0===e.length&&t([]);var r=e.length;e.forEach(((s,i)=>Ce.resolve(s).then((n=>{e[i]=n,--r||t(e)}),n)))}))},resolve:e=>{if(e instanceof Ce)return e;if(e&&"function"==typeof e.then)return new Ce(((t,n)=>{e.then(t,n)}));var t=new Ce(ce,!0,e);return Me(t,ke),t},reject:Ve,race:function(){var e=B.apply(null,arguments).map(tt);return new Ce(((t,n)=>{e.map((e=>Ce.resolve(e).then(t,n)))}))},PSD:{get:()=>Ee,set:e=>Ee=e},totalEchoes:{get:()=>Qe},newPSD:Je,usePSD:ot,scheduler:{get:()=>ge,set:e=>{ge=e}},rejectionMapper:{get:()=>Oe,set:e=>{Oe=e}},follow:(e,t)=>new Ce(((n,r)=>Je(((t,n)=>{var r=Ee;r.unhandleds=[],r.onunhandled=n,r.finalize=se((function(){!function(e){function t(){e(),Ae.splice(Ae.indexOf(t),1)}Ae.push(t),++Se,ge((()=>{0==--Se&&Ue()}),[])}((()=>{0===this.unhandleds.length?t():n(this.unhandleds[0])}))}),r.finalize),e()}),t,n,r)))}),ye&&(ye.allSettled&&l(Ce,"allSettled",(function(){const e=B.apply(null,arguments).map(tt);return new Ce((t=>{0===e.length&&t([]);let n=e.length;const r=new Array(n);e.forEach(((e,s)=>Ce.resolve(e).then((e=>r[s]={status:"fulfilled",value:e}),(e=>r[s]={status:"rejected",reason:e})).then((()=>--n||t(r)))))}))})),ye.any&&"undefined"!=typeof AggregateError&&l(Ce,"any",(function(){const e=B.apply(null,arguments).map(tt);return new Ce(((t,n)=>{0===e.length&&n(new AggregateError([]));let r=e.length;const s=new Array(r);e.forEach(((e,i)=>Ce.resolve(e).then((e=>t(e)),(e=>{s[i]=e,--r||n(new AggregateError(s))}))))}))})));const We={awaits:0,echoes:0,id:0};var Ye=0,Ge=[],He=0,Qe=0,Xe=0;function Je(e,t,n,s){var i=Ee,o=Object.create(i);o.parent=i,o.ref=0,o.global=!1,o.id=++Xe;var a=Pe.env;o.env=me?{Promise:Ce,PromiseProp:{value:Ce,configurable:!0,writable:!0},all:Ce.all,race:Ce.race,allSettled:Ce.allSettled,any:Ce.any,resolve:Ce.resolve,reject:Ce.reject,nthen:ut(a.nthen,o),gthen:ut(a.gthen,o)}:{},t&&r(o,t),++i.ref,o.finalize=function(){--this.parent.ref||this.parent.finalize()};var u=ot(o,e,n,s);return 0===o.ref&&o.finalize(),u}function Ze(){return We.id||(We.id=++Ye),++We.awaits,We.echoes+=100,We.id}function et(){return!!We.awaits&&(0==--We.awaits&&(We.id=0),We.echoes=100*We.awaits,!0)}function tt(e){return We.echoes&&e&&e.constructor===ye?(Ze(),e.then((e=>(et(),e)),(e=>(et(),lt(e))))):e}function nt(e){++Qe,We.echoes&&0!=--We.echoes||(We.echoes=We.id=0),Ge.push(Ee),st(e,!0)}function rt(){var e=Ge[Ge.length-1];Ge.pop(),st(e,!1)}function st(t,n){var r=Ee;if((n?!We.echoes||He++&&t===Ee:!He||--He&&t===Ee)||queueMicrotask(n?nt.bind(null,t):rt),t!==Ee&&(Ee=t,r===Pe&&(Pe.env=it()),me)){var s=Pe.env.Promise,i=t.env;de.then=i.nthen,s.prototype.then=i.gthen,(r.global||t.global)&&(Object.defineProperty(e,"Promise",i.PromiseProp),s.all=i.all,s.race=i.race,s.resolve=i.resolve,s.reject=i.reject,i.allSettled&&(s.allSettled=i.allSettled),i.any&&(s.any=i.any))}}function it(){var t=e.Promise;return me?{Promise:t,PromiseProp:Object.getOwnPropertyDescriptor(e,"Promise"),all:t.all,race:t.race,allSettled:t.allSettled,any:t.any,resolve:t.resolve,reject:t.reject,nthen:de.then,gthen:t.prototype.then}:{}}function ot(e,t,n,r,s){var i=Ee;try{return st(e,!0),t(n,r,s)}finally{st(i,!1)}}function at(e,t,n,r){return"function"!=typeof e?e:function(){var s=Ee;n&&Ze(),st(t,!0);try{return e.apply(this,arguments)}finally{st(s,!1),r&&queueMicrotask(et)}}}function ut(e,t){return function(n,r){return e.call(this,at(n,t),at(r,t))}}-1===(""+pe).indexOf("[native code]")&&(Ze=et=te);var lt=Ce.reject;function ct(e,t,n,r){if(e.idbdb&&(e._state.openComplete||Ee.letThrough||e._vip)){var s=e._createTransaction(t,n,e._dbSchema);try{s.create(),e._state.PR1398_maxLoop=3}catch(s){return s.name===Q.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then((()=>ct(e,t,n,r)))):lt(s)}return s._promise(t,((e,t)=>Je((()=>(Ee.trans=s,r(e,t,s)))))).then((e=>{if("readwrite"===t)try{s.idbtrans.commit()}catch(e){}return"readonly"===t?e:s._completion.then((()=>e))}))}if(e._state.openComplete)return lt(new J.DatabaseClosed(e._state.dbOpenError));if(!e._state.isBeingOpened){if(!e._options.autoOpen)return lt(new J.DatabaseClosed);e.open().catch(te)}return e._state.dbReadyPromise.then((()=>ct(e,t,n,r)))}const ht=String.fromCharCode(65535),dt="Invalid key provided. Keys must be of type string, number, Date or Array.",ft=[],pt="undefined"!=typeof navigator&&/(MSIE|Trident|Edge)/.test(navigator.userAgent),yt=pt,mt=pt,bt=e=>!/(dexie\.js|dexie\.min\.js)/.test(e);function gt(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}const vt={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function wt(e){return"string"!=typeof e||/\./.test(e)?e=>e:t=>(void 0===t[e]&&e in t&&delete(t=K(t))[e],t)}function _t(){throw J.Type()}function xt(e,t){try{const n=kt(e),r=kt(t);if(n!==r)return"Array"===n?1:"Array"===r?-1:"binary"===n?1:"binary"===r?-1:"string"===n?1:"string"===r?-1:"Date"===n?1:"Date"!==r?NaN:-1;switch(n){case"number":case"Date":case"string":return e>t?1:er._promise(e,i,n)),{trans:r,transless:Ee.transless||Ee}):ct(this.db,e,[this.name],i)}finally{o&&Le()}}get(e,t){return e&&e.constructor===Object?this.where(e).first(t):this._trans("readonly",(t=>this.core.get({trans:t,key:e}).then((e=>this.hook.reading.fire(e))))).then(t)}where(e){if("string"==typeof e)return new this.db.WhereClause(this,e);if(n(e))return new this.db.WhereClause(this,`[${e.join("+")}]`);const r=t(e);if(1===r.length)return this.where(r[0]).equals(e[r[0]]);const s=this.schema.indexes.concat(this.schema.primKey).filter((e=>{if(e.compound&&r.every((t=>e.keyPath.indexOf(t)>=0))){for(let t=0;te.keyPath.length-t.keyPath.length))[0];if(s&&this.db._maxKey!==ht){const t=s.keyPath.slice(0,r.length);return this.where(t).equals(t.map((t=>e[t])))}!s&&R&&console.warn(`The query ${JSON.stringify(e)} on ${this.name} would benefit of a compound index [${r.join("+")}]`);const{idxByName:i}=this.schema,o=this.db._deps.indexedDB;function a(e,t){return 0===o.cmp(e,t)}const[u,l]=r.reduce((([t,r],s)=>{const o=i[s],u=e[s];return[t||o,t||!o?gt(r,o&&o.multi?e=>{const t=g(e,s);return n(t)&&t.some((e=>a(u,e)))}:e=>a(u,g(e,s))):r]}),[null,null]);return u?this.where(u.name).equals(e[u.keyPath]).filter(l):s?this.filter(l):this.where(r).equals("")}filter(e){return this.toCollection().and(e)}count(e){return this.toCollection().count(e)}offset(e){return this.toCollection().offset(e)}limit(e){return this.toCollection().limit(e)}each(e){return this.toCollection().each(e)}toArray(e){return this.toCollection().toArray(e)}toCollection(){return new this.db.Collection(new this.db.WhereClause(this))}orderBy(e){return new this.db.Collection(new this.db.WhereClause(this,n(e)?`[${e.join("+")}]`:e))}reverse(){return this.toCollection().reverse()}mapToClass(e){const{db:t,name:n}=this;this.schema.mappedClass=e,e.prototype instanceof _t&&(e=class extends e{get db(){return t}table(){return n}});const r=new Set;for(let t=e.prototype;t;t=s(t))Object.getOwnPropertyNames(t).forEach((e=>r.add(e)));const i=t=>{if(!t)return t;const n=Object.create(e.prototype);for(let e in t)if(!r.has(e))try{n[e]=t[e]}catch(e){}return n};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=i,this.hook("reading",i),e}defineClass(){return this.mapToClass((function(e){r(this,e)}))}add(e,t){const{auto:n,keyPath:r}=this.schema.primKey;let s=e;return r&&n&&(s=wt(r)(e)),this._trans("readwrite",(e=>this.core.mutate({trans:e,type:"add",keys:null!=t?[t]:null,values:[s]}))).then((e=>e.numFailures?Ce.reject(e.failures[0]):e.lastResult)).then((t=>{if(r)try{v(e,r,t)}catch(e){}return t}))}update(e,t){if("object"!=typeof e||n(e))return this.where(":id").equals(e).modify(t);{const n=g(e,this.schema.primKey.keyPath);return void 0===n?lt(new J.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(n).modify(t)}}put(e,t){const{auto:n,keyPath:r}=this.schema.primKey;let s=e;return r&&n&&(s=wt(r)(e)),this._trans("readwrite",(e=>this.core.mutate({trans:e,type:"put",values:[s],keys:null!=t?[t]:null}))).then((e=>e.numFailures?Ce.reject(e.failures[0]):e.lastResult)).then((t=>{if(r)try{v(e,r,t)}catch(e){}return t}))}delete(e){return this._trans("readwrite",(t=>this.core.mutate({trans:t,type:"delete",keys:[e]}))).then((e=>e.numFailures?Ce.reject(e.failures[0]):void 0))}clear(){return this._trans("readwrite",(e=>this.core.mutate({trans:e,type:"deleteRange",range:vt}))).then((e=>e.numFailures?Ce.reject(e.failures[0]):void 0))}bulkGet(e){return this._trans("readonly",(t=>this.core.getMany({keys:e,trans:t}).then((e=>e.map((e=>this.hook.reading.fire(e)))))))}bulkAdd(e,t,n){const r=Array.isArray(t)?t:void 0,s=(n=n||(r?void 0:t))?n.allKeys:void 0;return this._trans("readwrite",(t=>{const{auto:n,keyPath:i}=this.schema.primKey;if(i&&r)throw new J.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(r&&r.length!==e.length)throw new J.InvalidArgument("Arguments objects and keys must have the same length");const o=e.length;let a=i&&n?e.map(wt(i)):e;return this.core.mutate({trans:t,type:"add",keys:r,values:a,wantResults:s}).then((({numFailures:e,results:t,lastResult:n,failures:r})=>{if(0===e)return s?t:n;throw new H(`${this.name}.bulkAdd(): ${e} of ${o} operations failed`,r)}))}))}bulkPut(e,t,n){const r=Array.isArray(t)?t:void 0,s=(n=n||(r?void 0:t))?n.allKeys:void 0;return this._trans("readwrite",(t=>{const{auto:n,keyPath:i}=this.schema.primKey;if(i&&r)throw new J.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(r&&r.length!==e.length)throw new J.InvalidArgument("Arguments objects and keys must have the same length");const o=e.length;let a=i&&n?e.map(wt(i)):e;return this.core.mutate({trans:t,type:"put",keys:r,values:a,wantResults:s}).then((({numFailures:e,results:t,lastResult:n,failures:r})=>{if(0===e)return s?t:n;throw new H(`${this.name}.bulkPut(): ${e} of ${o} operations failed`,r)}))}))}bulkUpdate(e){const t=this.core,n=e.map((e=>e.key)),r=e.map((e=>e.changes)),s=[];return this._trans("readwrite",(i=>t.getMany({trans:i,keys:n,cache:"clone"}).then((o=>{const a=[],u=[];e.forEach((({key:e,changes:t},n)=>{const r=o[n];if(r){for(const n of Object.keys(t)){const s=t[n];if(n===this.schema.primKey.keyPath){if(0!==xt(s,e))throw new J.Constraint("Cannot update primary key in bulkUpdate()")}else v(r,n,s)}s.push(n),a.push(e),u.push(r)}}));const l=a.length;return t.mutate({trans:i,type:"put",keys:a,values:u,updates:{keys:n,changeSpecs:r}}).then((({numFailures:e,failures:t})=>{if(0===e)return l;for(const e of Object.keys(t)){const n=s[Number(e)];if(null!=n){const r=t[e];delete t[e],t[n]=r}}throw new H(`${this.name}.bulkUpdate(): ${e} of ${l} operations failed`,t)}))}))))}bulkDelete(e){const t=e.length;return this._trans("readwrite",(t=>this.core.mutate({trans:t,type:"delete",keys:e}))).then((({numFailures:e,lastResult:n,failures:r})=>{if(0===e)return n;throw new H(`${this.name}.bulkDelete(): ${e} of ${t} operations failed`,r)}))}}function Et(e){var r={},s=function(t,n){if(n){for(var s=arguments.length,i=new Array(s-1);--s;)i[s-1]=arguments[s];return r[t].subscribe.apply(null,i),e}if("string"==typeof t)return r[t]};s.addEventType=a;for(var i=1,o=arguments.length;igt(r(),t()):t,e.justLimit=n&&!r}function jt(e,t){if(e.isPrimKey)return t.primaryKey;const n=t.getIndexByKeyPath(e.index);if(!n)throw new J.Schema("KeyPath "+e.index+" on object store "+t.name+" is not indexed");return n}function qt(e,t,n){const r=jt(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:"prev"===e.dir,unique:!!e.unique,query:{index:r,range:e.range}})}function Dt(e,t,n,r){const s=e.replayFilter?gt(e.filter,e.replayFilter()):e.filter;if(e.or){const i={},a=(e,n,r)=>{if(!s||s(n,r,(e=>n.stop(e)),(e=>n.fail(e)))){var a=n.primaryKey,u=""+a;"[object ArrayBuffer]"===u&&(u=""+new Uint8Array(a)),o(i,u)||(i[u]=!0,t(e,n,r))}};return Promise.all([e.or._iterate(a,n),It(qt(e,r,n),e.algorithm,a,!e.keysOnly&&e.valueMapper)])}return It(qt(e,r,n),gt(e.algorithm,s),t,!e.keysOnly&&e.valueMapper)}function It(e,t,n,r){var s=ze(r?(e,t,s)=>n(r(e),t,s):n);return e.then((e=>{if(e)return e.start((()=>{var n=()=>e.continue();t&&!t(e,(e=>n=e),(t=>{e.stop(t),n=te}),(t=>{e.fail(t),n=te}))||s(e.value,e,(e=>n=e)),n()}))}))}class Bt{_read(e,t){var n=this._ctx;return n.error?n.table._trans(null,lt.bind(null,n.error)):n.table._trans("readonly",e).then(t)}_write(e){var t=this._ctx;return t.error?t.table._trans(null,lt.bind(null,t.error)):t.table._trans("readwrite",e,"locked")}_addAlgorithm(e){var t=this._ctx;t.algorithm=gt(t.algorithm,e)}_iterate(e,t){return Dt(this._ctx,e,t,this._ctx.table.core)}clone(e){var t=Object.create(this.constructor.prototype),n=Object.create(this._ctx);return e&&r(n,e),t._ctx=n,t}raw(){return this._ctx.valueMapper=null,this}each(e){var t=this._ctx;return this._read((n=>Dt(t,e,n,t.table.core)))}count(e){return this._read((e=>{const t=this._ctx,n=t.table.core;if(St(t,!0))return n.count({trans:e,query:{index:jt(t,n.schema),range:t.range}}).then((e=>Math.min(e,t.limit)));var r=0;return Dt(t,(()=>(++r,!1)),e,n).then((()=>r))})).then(e)}sortBy(e,t){const n=e.split(".").reverse(),r=n[0],s=n.length-1;function i(e,t){return t?i(e[n[t]],t-1):e[r]}var o="next"===this._ctx.dir?1:-1;function a(e,t){var n=i(e,s),r=i(t,s);return nr?o:0}return this.toArray((function(e){return e.sort(a)})).then(t)}toArray(e){return this._read((e=>{var t=this._ctx;if("next"===t.dir&&St(t,!0)&&t.limit>0){const{valueMapper:n}=t,r=jt(t,t.table.core.schema);return t.table.core.query({trans:e,limit:t.limit,values:!0,query:{index:r,range:t.range}}).then((({result:e})=>n?e.map(n):e))}{const n=[];return Dt(t,(e=>n.push(e)),e,t.table.core).then((()=>n))}}),e)}offset(e){var t=this._ctx;return e<=0||(t.offset+=e,St(t)?Ct(t,(()=>{var t=e;return(e,n)=>0===t||(1===t?(--t,!1):(n((()=>{e.advance(t),t=0})),!1))})):Ct(t,(()=>{var t=e;return()=>--t<0}))),this}limit(e){return this._ctx.limit=Math.min(this._ctx.limit,e),Ct(this._ctx,(()=>{var t=e;return function(e,n,r){return--t<=0&&n(r),t>=0}}),!0),this}until(e,t){return At(this._ctx,(function(n,r,s){return!e(n.value)||(r(s),t)})),this}first(e){return this.limit(1).toArray((function(e){return e[0]})).then(e)}last(e){return this.reverse().first(e)}filter(e){var t,n;return At(this._ctx,(function(t){return e(t.value)})),t=this._ctx,n=e,t.isMatch=gt(t.isMatch,n),this}and(e){return this.filter(e)}or(e){return new this.db.WhereClause(this._ctx.table,e,this)}reverse(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this}desc(){return this.reverse()}eachKey(e){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each((function(t,n){e(n.key,n)}))}eachUniqueKey(e){return this._ctx.unique="unique",this.eachKey(e)}eachPrimaryKey(e){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each((function(t,n){e(n.primaryKey,n)}))}keys(e){var t=this._ctx;t.keysOnly=!t.isMatch;var n=[];return this.each((function(e,t){n.push(t.key)})).then((function(){return n})).then(e)}primaryKeys(e){var t=this._ctx;if("next"===t.dir&&St(t,!0)&&t.limit>0)return this._read((e=>{var n=jt(t,t.table.core.schema);return t.table.core.query({trans:e,values:!1,limit:t.limit,query:{index:n,range:t.range}})})).then((({result:e})=>e)).then(e);t.keysOnly=!t.isMatch;var n=[];return this.each((function(e,t){n.push(t.primaryKey)})).then((function(){return n})).then(e)}uniqueKeys(e){return this._ctx.unique="unique",this.keys(e)}firstKey(e){return this.limit(1).keys((function(e){return e[0]})).then(e)}lastKey(e){return this.reverse().firstKey(e)}distinct(){var e=this._ctx,t=e.index&&e.table.schema.idxByName[e.index];if(!t||!t.multi)return this;var n={};return At(this._ctx,(function(e){var t=e.primaryKey.toString(),r=o(n,t);return n[t]=!0,!r})),this}modify(e){var n=this._ctx;return this._write((r=>{var s;if("function"==typeof e)s=e;else{var i=t(e),o=i.length;s=function(t){for(var n=!1,r=0;r{const{failures:r,numFailures:s}=n;d+=e-s;for(let e of t(r))h.push(r[e])};return this.clone().primaryKeys().then((t=>{const i=o=>{const h=Math.min(c,t.length-o);return a.getMany({trans:r,keys:t.slice(o,o+h),cache:"immutable"}).then((d=>{const f=[],y=[],m=u?[]:null,b=[];for(let e=0;e0&&a.mutate({trans:r,type:"add",values:f}).then((e=>{for(let t in e.failures)b.splice(parseInt(t),1);p(f.length,e)}))).then((()=>(y.length>0||g&&"object"==typeof e)&&a.mutate({trans:r,type:"put",keys:m,values:y,criteria:g,changeSpec:"function"!=typeof e&&e}).then((e=>p(y.length,e))))).then((()=>(b.length>0||g&&e===Tt)&&a.mutate({trans:r,type:"delete",keys:b,criteria:g}).then((e=>p(b.length,e))))).then((()=>t.length>o+h&&i(o+c)))}))};return i(0).then((()=>{if(h.length>0)throw new G("Error modifying one or more objects",h,d,f);return t.length}))}))}))}delete(){var e=this._ctx,t=e.range;return St(e)&&(e.isPrimKey&&!mt||3===t.type)?this._write((n=>{const{primaryKey:r}=e.table.core.schema,s=t;return e.table.core.count({trans:n,query:{index:r,range:s}}).then((t=>e.table.core.mutate({trans:n,type:"deleteRange",range:s}).then((({failures:e,lastResult:n,results:r,numFailures:s})=>{if(s)throw new G("Could not delete some values",Object.keys(e).map((t=>e[t])),t-s);return t-s}))))})):this.modify(Tt)}}const Tt=(e,t)=>t.value=null;function Rt(e,t){return et?-1:e===t?0:1}function Mt(e,t,n){var r=e instanceof zt?new e.Collection(e):e;return r._ctx.error=n?new n(t):new TypeError(t),r}function Nt(e){return new e.Collection(e,(()=>Vt(""))).limit(0)}function $t(e,t,n,r,s,i){for(var o=Math.min(e.length,r.length),a=-1,u=0;u=0?e.substr(0,a)+t[a]+n.substr(a+1):null;s(e[u],l)<0&&(a=u)}return o"string"==typeof e)))return Mt(e,"String expected.");function d(e){s=function(e){return"next"===e?e=>e.toUpperCase():e=>e.toLowerCase()}(e),i=function(e){return"next"===e?e=>e.toLowerCase():e=>e.toUpperCase()}(e),o="next"===e?Rt:Ft;var t=n.map((function(e){return{lower:i(e),upper:s(e)}})).sort((function(e,t){return o(e.lower,t.lower)}));a=t.map((function(e){return e.upper})),u=t.map((function(e){return e.lower})),l=e,c="next"===e?"":r}d("next");var f=new e.Collection(e,(()=>Ut(a[0],u[h-1]+r)));f._ondirectionchange=function(e){d(e)};var p=0;return f._addAlgorithm((function(e,n,r){var s=e.key;if("string"!=typeof s)return!1;var d=i(s);if(t(d,u,p))return!0;for(var f=null,y=p;y0)&&(f=m)}return n(null!==f?function(){e.continue(f+c)}:r),!1})),f}function Ut(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function Vt(e){return{type:1,lower:e,upper:e}}class zt{get Collection(){return this._ctx.table.db.Collection}between(e,t,n,r){n=!1!==n,r=!0===r;try{return this._cmp(e,t)>0||0===this._cmp(e,t)&&(n||r)&&(!n||!r)?Nt(this):new this.Collection(this,(()=>Ut(e,t,!n,!r)))}catch(e){return Mt(this,dt)}}equals(e){return null==e?Mt(this,dt):new this.Collection(this,(()=>Vt(e)))}above(e){return null==e?Mt(this,dt):new this.Collection(this,(()=>Ut(e,void 0,!0)))}aboveOrEqual(e){return null==e?Mt(this,dt):new this.Collection(this,(()=>Ut(e,void 0,!1)))}below(e){return null==e?Mt(this,dt):new this.Collection(this,(()=>Ut(void 0,e,!1,!0)))}belowOrEqual(e){return null==e?Mt(this,dt):new this.Collection(this,(()=>Ut(void 0,e)))}startsWith(e){return"string"!=typeof e?Mt(this,"String expected."):this.between(e,e+ht,!0,!0)}startsWithIgnoreCase(e){return""===e?this.startsWith(e):Lt(this,((e,t)=>0===e.indexOf(t[0])),[e],ht)}equalsIgnoreCase(e){return Lt(this,((e,t)=>e===t[0]),[e],"")}anyOfIgnoreCase(){var e=B.apply(I,arguments);return 0===e.length?Nt(this):Lt(this,((e,t)=>-1!==t.indexOf(e)),e,"")}startsWithAnyOfIgnoreCase(){var e=B.apply(I,arguments);return 0===e.length?Nt(this):Lt(this,((e,t)=>t.some((t=>0===e.indexOf(t)))),e,ht)}anyOf(){const e=B.apply(I,arguments);let t=this._cmp;try{e.sort(t)}catch(e){return Mt(this,dt)}if(0===e.length)return Nt(this);const n=new this.Collection(this,(()=>Ut(e[0],e[e.length-1])));n._ondirectionchange=n=>{t="next"===n?this._ascending:this._descending,e.sort(t)};let r=0;return n._addAlgorithm(((n,s,i)=>{const o=n.key;for(;t(o,e[r])>0;)if(++r,r===e.length)return s(i),!1;return 0===t(o,e[r])||(s((()=>{n.continue(e[r])})),!1)})),n}notEqual(e){return this.inAnyRange([[-(1/0),e],[e,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})}noneOf(){const e=B.apply(I,arguments);if(0===e.length)return new this.Collection(this);try{e.sort(this._ascending)}catch(e){return Mt(this,dt)}const t=e.reduce(((e,t)=>e?e.concat([[e[e.length-1][1],t]]):[[-(1/0),t]]),null);return t.push([e[e.length-1],this.db._maxKey]),this.inAnyRange(t,{includeLowers:!1,includeUppers:!1})}inAnyRange(e,t){const n=this._cmp,r=this._ascending,s=this._descending,i=this._min,o=this._max;if(0===e.length)return Nt(this);if(!e.every((e=>void 0!==e[0]&&void 0!==e[1]&&r(e[0],e[1])<=0)))return Mt(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",J.InvalidArgument);const a=!t||!1!==t.includeLowers,u=t&&!0===t.includeUppers;let l,c=r;function h(e,t){return c(e[0],t[0])}try{l=e.reduce((function(e,t){let r=0,s=e.length;for(;r0){s[0]=i(s[0],t[0]),s[1]=o(s[1],t[1]);break}}return r===s&&e.push(t),e}),[]),l.sort(h)}catch(e){return Mt(this,dt)}let d=0;const f=u?e=>r(e,l[d][1])>0:e=>r(e,l[d][1])>=0,p=a?e=>s(e,l[d][0])>0:e=>s(e,l[d][0])>=0;let y=f;const m=new this.Collection(this,(()=>Ut(l[0][0],l[l.length-1][1],!a,!u)));return m._ondirectionchange=e=>{"next"===e?(y=f,c=r):(y=p,c=s),l.sort(h)},m._addAlgorithm(((e,t,n)=>{for(var s=e.key;y(s);)if(++d,d===l.length)return t(n),!1;return!!function(e){return!f(e)&&!p(e)}(s)||(0===this._cmp(s,l[d][1])||0===this._cmp(s,l[d][0])||t((()=>{c===r?e.continue(l[d][0]):e.continue(l[d][1])})),!1)})),m}startsWithAnyOf(){const e=B.apply(I,arguments);return e.every((e=>"string"==typeof e))?0===e.length?Nt(this):this.inAnyRange(e.map((e=>[e,e+ht]))):Mt(this,"startsWithAnyOf() only works with strings")}}function Wt(e){return ze((function(t){return Yt(t),e(t.target.error),!1}))}function Yt(e){e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}const Gt=Et(null,"storagemutated");class Ht{_lock(){return m(!Ee.global),++this._reculock,1!==this._reculock||Ee.global||(Ee.lockOwnerFor=this),this}_unlock(){if(m(!Ee.global),0==--this._reculock)for(Ee.global||(Ee.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var e=this._blockedFuncs.shift();try{ot(e[1],e[0])}catch(e){}}return this}_locked(){return this._reculock&&Ee.lockOwnerFor!==this}create(e){if(!this.mode)return this;const t=this.db.idbdb,n=this.db._state.dbOpenError;if(m(!this.idbtrans),!e&&!t)switch(n&&n.name){case"DatabaseClosedError":throw new J.DatabaseClosed(n);case"MissingAPIError":throw new J.MissingAPI(n.message,n);default:throw new J.OpenFailed(n)}if(!this.active)throw new J.TransactionInactive;return m(null===this._completion._state),(e=this.idbtrans=e||(this.db.core?this.db.core.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}):t.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}))).onerror=ze((t=>{Yt(t),this._reject(e.error)})),e.onabort=ze((t=>{Yt(t),this.active&&this._reject(new J.Abort(e.error)),this.active=!1,this.on("abort").fire(t)})),e.oncomplete=ze((()=>{this.active=!1,this._resolve(),"mutatedParts"in e&&Gt.storagemutated.fire(e.mutatedParts)})),this}_promise(e,t,n){if("readwrite"===e&&"readwrite"!==this.mode)return lt(new J.ReadOnly("Transaction is readonly"));if(!this.active)return lt(new J.TransactionInactive);if(this._locked())return new Ce(((r,s)=>{this._blockedFuncs.push([()=>{this._promise(e,t,n).then(r,s)},Ee])}));if(n)return Je((()=>{var e=new Ce(((e,n)=>{this._lock();const r=t(e,n,this);r&&r.then&&r.then(e,n)}));return e.finally((()=>this._unlock())),e._lib=!0,e}));var r=new Ce(((e,n)=>{var r=t(e,n,this);r&&r.then&&r.then(e,n)}));return r._lib=!0,r}_root(){return this.parent?this.parent._root():this}waitFor(e){var t=this._root();const n=Ce.resolve(e);if(t._waitingFor)t._waitingFor=t._waitingFor.then((()=>n));else{t._waitingFor=n,t._waitingQueue=[];var r=t.idbtrans.objectStore(t.storeNames[0]);!function e(){for(++t._spinCount;t._waitingQueue.length;)t._waitingQueue.shift()();t._waitingFor&&(r.get(-1/0).onsuccess=e)}()}var s=t._waitingFor;return new Ce(((e,r)=>{n.then((n=>t._waitingQueue.push(ze(e.bind(null,n)))),(e=>t._waitingQueue.push(ze(r.bind(null,e))))).finally((()=>{t._waitingFor===s&&(t._waitingFor=null)}))}))}abort(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new J.Abort))}table(e){const t=this._memoizedTables||(this._memoizedTables={});if(o(t,e))return t[e];const n=this.schema[e];if(!n)throw new J.NotFound("Table "+e+" not part of transaction");const r=new this.db.Table(e,n,this);return r.core=this.db.core.table(e),t[e]=r,r}}function Qt(e,t,n,r,s,i,o){return{name:e,keyPath:t,unique:n,multi:r,auto:s,compound:i,src:(n&&!o?"&":"")+(r?"*":"")+(s?"++":"")+Xt(t)}}function Xt(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}function Jt(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:(r=n,s=e=>[e.name,e],r.reduce(((e,t,n)=>{var r=s(t,n);return r&&(e[r[0]]=r[1]),e}),{}))};var r,s}let Zt=e=>{try{return e.only([[]]),Zt=()=>[[]],[[]]}catch(e){return Zt=()=>ht,ht}};function en(e){return null==e?()=>{}:"string"==typeof e?function(e){return 1===e.split(".").length?t=>t[e]:t=>g(t,e)}(e):t=>g(t,e)}function tn(e){return[].slice.call(e)}let nn=0;function rn(e){return null==e?":id":"string"==typeof e?e:`[${e.join("+")}]`}function sn(e,t,r){function s(e){if(3===e.type)return null;if(4===e.type)throw new Error("Cannot convert never type to IDBKeyRange");const{lower:n,upper:r,lowerOpen:s,upperOpen:i}=e;return void 0===n?void 0===r?null:t.upperBound(r,!!i):void 0===r?t.lowerBound(n,!!s):t.bound(n,r,!!s,!!i)}const{schema:i,hasGetAll:o}=function(e,t){const r=tn(e.objectStoreNames);return{schema:{name:e.name,tables:r.map((e=>t.objectStore(e))).map((e=>{const{keyPath:t,autoIncrement:r}=e,s=n(t),i=null==t,o={},a={name:e.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:i,compound:s,keyPath:t,autoIncrement:r,unique:!0,extractKey:en(t)},indexes:tn(e.indexNames).map((t=>e.index(t))).map((e=>{const{name:t,unique:r,multiEntry:s,keyPath:i}=e,a={name:t,compound:n(i),keyPath:i,unique:r,multiEntry:s,extractKey:en(i)};return o[rn(i)]=a,a})),getIndexByKeyPath:e=>o[rn(e)]};return o[":id"]=a.primaryKey,null!=t&&(o[rn(t)]=a.primaryKey),a}))},hasGetAll:r.length>0&&"getAll"in t.objectStore(r[0])&&!("undefined"!=typeof navigator&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}(e,r),a=i.tables.map((e=>function(e){const t=e.name;return{name:t,schema:e,mutate:function({trans:e,type:n,keys:r,values:i,range:o}){return new Promise(((a,u)=>{a=ze(a);const l=e.objectStore(t),c=null==l.keyPath,h="put"===n||"add"===n;if(!h&&"delete"!==n&&"deleteRange"!==n)throw new Error("Invalid operation type: "+n);const{length:d}=r||i||{length:1};if(r&&i&&r.length!==i.length)throw new Error("Given keys array must have same length as given values array.");if(0===d)return a({numFailures:0,failures:{},results:[],lastResult:void 0});let f;const p=[],y=[];let m=0;const b=e=>{++m,Yt(e)};if("deleteRange"===n){if(4===o.type)return a({numFailures:m,failures:y,results:[],lastResult:void 0});3===o.type?p.push(f=l.clear()):p.push(f=l.delete(s(o)))}else{const[e,t]=h?c?[i,r]:[i,null]:[r,null];if(h)for(let r=0;r{const t=e.target.result;p.forEach(((e,t)=>null!=e.error&&(y[t]=e.error))),a({numFailures:m,failures:y,results:"delete"===n?r:p.map((e=>e.result)),lastResult:t})};f.onerror=e=>{b(e),g(e)},f.onsuccess=g}))},getMany:({trans:e,keys:n})=>new Promise(((r,s)=>{r=ze(r);const i=e.objectStore(t),o=n.length,a=new Array(o);let u,l=0,c=0;const h=e=>{const t=e.target;a[t._pos]=t.result,++c===l&&r(a)},d=Wt(s);for(let e=0;enew Promise(((r,s)=>{r=ze(r);const i=e.objectStore(t).get(n);i.onsuccess=e=>r(e.target.result),i.onerror=Wt(s)})),query:function(e){return n=>new Promise(((r,i)=>{r=ze(r);const{trans:o,values:a,limit:u,query:l}=n,c=u===1/0?void 0:u,{index:h,range:d}=l,f=o.objectStore(t),p=h.isPrimaryKey?f:f.index(h.name),y=s(d);if(0===u)return r({result:[]});if(e){const e=a?p.getAll(y,c):p.getAllKeys(y,c);e.onsuccess=e=>r({result:e.target.result}),e.onerror=Wt(i)}else{let e=0;const t=a||!("openKeyCursor"in p)?p.openCursor(y):p.openKeyCursor(y),n=[];t.onsuccess=s=>{const i=t.result;return i?(n.push(a?i.value:i.primaryKey),++e===u?r({result:n}):void i.continue()):r({result:n})},t.onerror=Wt(i)}}))}(o),openCursor:function({trans:e,values:n,query:r,reverse:i,unique:o}){return new Promise(((a,u)=>{a=ze(a);const{index:l,range:c}=r,h=e.objectStore(t),d=l.isPrimaryKey?h:h.index(l.name),f=i?o?"prevunique":"prev":o?"nextunique":"next",p=n||!("openKeyCursor"in d)?d.openCursor(s(c),f):d.openKeyCursor(s(c),f);p.onerror=Wt(u),p.onsuccess=ze((t=>{const n=p.result;if(!n)return void a(null);n.___id=++nn,n.done=!1;const r=n.continue.bind(n);let s=n.continuePrimaryKey;s&&(s=s.bind(n));const i=n.advance.bind(n),o=()=>{throw new Error("Cursor not stopped")};n.trans=e,n.stop=n.continue=n.continuePrimaryKey=n.advance=()=>{throw new Error("Cursor not started")},n.fail=ze(u),n.next=function(){let e=1;return this.start((()=>e--?this.continue():this.stop())).then((()=>this))},n.start=e=>{const t=new Promise(((e,t)=>{e=ze(e),p.onerror=Wt(t),n.fail=t,n.stop=t=>{n.stop=n.continue=n.continuePrimaryKey=n.advance=o,e(t)}})),a=()=>{if(p.result)try{e()}catch(e){n.fail(e)}else n.done=!0,n.start=()=>{throw new Error("Cursor behind last entry")},n.stop()};return p.onsuccess=ze((e=>{p.onsuccess=a,a()})),n.continue=r,n.continuePrimaryKey=s,n.advance=i,a(),t},a(n)}),u)}))},count({query:e,trans:n}){const{index:r,range:i}=e;return new Promise(((e,o)=>{const a=n.objectStore(t),u=r.isPrimaryKey?a:a.index(r.name),l=s(i),c=l?u.count(l):u.count();c.onsuccess=ze((t=>e(t.target.result))),c.onerror=Wt(o)}))}}}(e))),u={};return a.forEach((e=>u[e.name]=e)),{stack:"dbcore",transaction:e.transaction.bind(e),table(e){if(!u[e])throw new Error(`Table '${e}' not found`);return u[e]},MIN_KEY:-1/0,MAX_KEY:Zt(t),schema:i}}function on(e,t){const n=t.db,r=function(e,t,{IDBKeyRange:n,indexedDB:r},s){const i=function(e,t){return t.reduce(((e,{create:t})=>({...e,...t(e)})),e)}(sn(t,n,s),e.dbcore);return{dbcore:i}}(e._middlewares,n,e._deps,t);e.core=r.dbcore,e.tables.forEach((t=>{const n=t.name;e.core.schema.tables.some((e=>e.name===n))&&(t.core=e.core.table(n),e[n]instanceof e.Table&&(e[n].core=t.core))}))}function an(e,t,n,r){n.forEach((n=>{const s=r[n];t.forEach((t=>{const r=d(t,n);(!r||"value"in r&&void 0===r.value)&&(t===e.Transaction.prototype||t instanceof e.Transaction?l(t,n,{get(){return this.table(n)},set(e){u(this,n,{value:e,writable:!0,configurable:!0,enumerable:!0})}}):t[n]=new e.Table(n,s))}))}))}function un(e,t){t.forEach((t=>{for(let n in t)t[n]instanceof e.Table&&delete t[n]}))}function ln(e,t){return e._cfg.version-t._cfg.version}function cn(e,n,r,s){const i=e._dbSchema,o=e._createTransaction("readwrite",e._storeNames,i);o.create(r),o._completion.catch(s);const a=o._reject.bind(o),u=Ee.transless||Ee;Je((()=>{Ee.trans=o,Ee.transless=u,0===n?(t(i).forEach((e=>{dn(r,e,i[e].primKey,i[e].indexes)})),on(e,r),Ce.follow((()=>e.on.populate.fire(o))).catch(a)):function(e,n,r,s){const i=[],o=e._versions;let a=e._dbSchema=pn(e,e.idbdb,s),u=!1;function l(){return i.length?Ce.resolve(i.shift()(r.idbtrans)).then(l):Ce.resolve()}return o.filter((e=>e._cfg.version>=n)).forEach((o=>{i.push((()=>{const i=a,l=o._cfg.dbschema;yn(e,i,s),yn(e,l,s),a=e._dbSchema=l;const c=hn(i,l);c.add.forEach((e=>{dn(s,e[0],e[1].primKey,e[1].indexes)})),c.change.forEach((e=>{if(e.recreate)throw new J.Upgrade("Not yet support for changing primary key");{const t=s.objectStore(e.name);e.add.forEach((e=>fn(t,e))),e.change.forEach((e=>{t.deleteIndex(e.name),fn(t,e)})),e.del.forEach((e=>t.deleteIndex(e)))}}));const h=o._cfg.contentUpgrade;if(h&&o._cfg.version>n){on(e,s),r._memoizedTables={},u=!0;let n=w(l);c.del.forEach((e=>{n[e]=i[e]})),un(e,[e.Transaction.prototype]),an(e,[e.Transaction.prototype],t(n),n),r.schema=n;const o=T(h);let a;o&&Ze();const d=Ce.follow((()=>{if(a=h(r),a&&o){var e=et.bind(null,null);a.then(e,e)}}));return a&&"function"==typeof a.then?Ce.resolve(a):d.then((()=>a))}})),i.push((t=>{if(!u||!yt){!function(e,t){[].slice.call(t.db.objectStoreNames).forEach((n=>null==e[n]&&t.db.deleteObjectStore(n)))}(o._cfg.dbschema,t)}un(e,[e.Transaction.prototype]),an(e,[e.Transaction.prototype],e._storeNames,e._dbSchema),r.schema=e._dbSchema}))})),l().then((()=>{var e,n;n=s,t(e=a).forEach((t=>{n.db.objectStoreNames.contains(t)||dn(n,t,e[t].primKey,e[t].indexes)}))}))}(e,n,o,r).catch(a)}))}function hn(e,t){const n={del:[],add:[],change:[]};let r;for(r in e)t[r]||n.del.push(r);for(r in t){const s=e[r],i=t[r];if(s){const e={name:r,def:i,recreate:!1,del:[],add:[],change:[]};if(""+(s.primKey.keyPath||"")!=""+(i.primKey.keyPath||"")||s.primKey.auto!==i.primKey.auto&&!pt)e.recreate=!0,n.change.push(e);else{const t=s.idxByName,r=i.idxByName;let o;for(o in t)r[o]||e.del.push(o);for(o in r){const n=t[o],s=r[o];n?n.src!==s.src&&e.change.push(s):e.add.push(s)}(e.del.length>0||e.add.length>0||e.change.length>0)&&n.change.push(e)}}else n.add.push([r,i])}return n}function dn(e,t,n,r){const s=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach((e=>fn(s,e))),s}function fn(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function pn(e,t,n){const r={};return p(t.objectStoreNames,0).forEach((e=>{const t=n.objectStore(e);let s=t.keyPath;const i=Qt(Xt(s),s||"",!1,!1,!!t.autoIncrement,s&&"string"!=typeof s,!0),o=[];for(let e=0;e{if(null!==e[t]){var s=e[t].split(",").map(((e,t)=>{const r=(e=e.trim()).replace(/([&*]|\+\+)/g,""),s=/^\[/.test(r)?r.match(/^\[(.*)\]$/)[1].split("+"):r;return Qt(r,s||null,/\&/.test(e),/\*/.test(e),/\+\+/.test(e),n(s),0===t)})),i=s.shift();if(i.multi)throw new J.Schema("Primary key cannot be multi-valued");s.forEach((e=>{if(e.auto)throw new J.Schema("Only primary key can be marked as autoIncrement (++)");if(!e.keyPath)throw new J.Schema("Index must have a name and cannot be an empty string")})),r[t]=Jt(t,i,s)}}))}stores(e){const n=this.db;this._cfg.storesSource=this._cfg.storesSource?r(this._cfg.storesSource,e):e;const s=n._versions,i={};let o={};return s.forEach((e=>{r(i,e._cfg.storesSource),o=e._cfg.dbschema={},e._parseStoresSpec(i,o)})),n._dbSchema=o,un(n,[n._allTables,n,n.Transaction.prototype]),an(n,[n._allTables,n,n.Transaction.prototype,this._cfg.tables],t(o),o),n._storeNames=t(o),this}upgrade(e){return this._cfg.contentUpgrade=le(this._cfg.contentUpgrade||te,e),this}}function bn(e,t){let n=e._dbNamesDB;return n||(n=e._dbNamesDB=new sr("__dbnames",{addons:[],indexedDB:e,IDBKeyRange:t}),n.version(1).stores({dbnames:"name"})),n.table("dbnames")}function gn(e){return e&&"function"==typeof e.databases}function vn(e){return Je((function(){return Ee.letThrough=!0,e()}))}function wn(){var e;return!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise((function(t){var n=function(){return indexedDB.databases().finally(t)};e=setInterval(n,100),n()})).finally((function(){return clearInterval(e)})):Promise.resolve()}function _n(e){return!("from"in e)}const xn=function(e,t){if(!this){const t=new xn;return e&&"d"in e&&r(t,e),t}r(this,arguments.length?{d:1,from:e,to:arguments.length>1?t:e}:{d:0})};function kn(e,t,n){const s=xt(t,n);if(isNaN(s))return;if(s>0)throw RangeError();if(_n(e))return r(e,{from:t,to:n,d:1});const i=e.l,o=e.r;if(xt(n,e.from)<0)return i?kn(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Kn(e);if(xt(t,e.to)>0)return o?kn(o,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Kn(e);xt(t,e.from)<0&&(e.from=t,e.l=null,e.d=o?o.d+1:1),xt(n,e.to)>0&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1);const a=!e.r;i&&!e.l&&On(e,i),o&&a&&On(e,o)}function On(e,t){_n(t)||function e(t,{from:n,to:r,l:s,r:i}){kn(t,n,r),s&&e(t,s),i&&e(t,i)}(e,t)}function Pn(e,t){const n=En(t);let r=n.next();if(r.done)return!1;let s=r.value;const i=En(e);let o=i.next(s.from),a=o.value;for(;!r.done&&!o.done;){if(xt(a.from,s.to)<=0&&xt(a.to,s.from)>=0)return!0;xt(s.from,a.from)<0?s=(r=n.next(a.from)).value:a=(o=i.next(s.from)).value}return!1}function En(e){let t=_n(e)?null:{s:0,n:e};return{next(e){const n=arguments.length>0;for(;t;)switch(t.s){case 0:if(t.s=1,n)for(;t.n.l&&xt(e,t.n.from)<0;)t={up:t,n:t.n.l,s:1};else for(;t.n.l;)t={up:t,n:t.n.l,s:1};case 1:if(t.s=2,!n||xt(e,t.n.to)<=0)return{value:t.n,done:!1};case 2:if(t.n.r){t.s=3,t={up:t,n:t.n.r,s:0};continue}case 3:t=t.up}return{done:!0}}}}function Kn(e){var t,n;const r=((null===(t=e.r)||void 0===t?void 0:t.d)||0)-((null===(n=e.l)||void 0===n?void 0:n.d)||0),s=r>1?"r":r<-1?"l":"";if(s){const t="r"===s?"l":"r",n={...e},r=e[s];e.from=r.from,e.to=r.to,e[s]=r[s],n[s]=r[t],e[t]=n,n.d=Sn(n)}e.d=Sn(e)}function Sn({r:e,l:t}){return(e?t?Math.max(e.d,t.d):e.d:t?t.d:0)+1}function An(e,n){return t(n).forEach((t=>{e[t]?On(e[t],n[t]):e[t]=P(n[t])})),e}function Cn(e,t){return Object.keys(e).some((n=>t[n]&&Pn(t[n],e[n])))}a(xn.prototype,{add(e){return On(this,e),this},addKey(e){return kn(this,e,e),this},addKeys(e){return e.forEach((e=>kn(this,e,e))),this},[j](){return En(this)}});const jn={};let qn={},Dn=!1;function In(e){An(qn,e),Dn||(Dn=!0,setTimeout((()=>{Dn=!1;const e=qn;qn={},Bn(e)}),0))}function Bn(e,t=!1){const n=new Set;for(const r in e){const s=/^idb\:\/\/(.*)\/(.*)\//.exec(r);if(s){const[,r,i]=s,o=jn[`idb://${r}/${i}`];o&&Tn(o,e,n,t)}}n.forEach((e=>e()))}function Tn(e,t,n,r){const s=r&&[];for(const[i,o]of Object.entries(e.queries.query)){const e=r&&[];for(const s of o)s.obsSet&&Cn(t,s.obsSet)?s.subscribers.forEach((e=>n.add(e))):r&&e.push(s);r&&s.push([i,e])}if(r)for(const[t,n]of s)e.queries.query[t]=n}function Rn(e){const n=e._state,{indexedDB:r}=e._deps;if(n.isBeingOpened||e.idbdb)return n.dbReadyPromise.then((()=>n.dbOpenError?lt(n.dbOpenError):e));R&&(n.openCanceller._stackHolder=$()),n.isBeingOpened=!0,n.dbOpenError=null,n.openComplete=!1;const s=n.openCanceller;function i(){if(n.openCanceller!==s)throw new J.DatabaseClosed("db.open() was cancelled")}let o=n.dbReadyResolve,a=null,u=!1;return Ce.race([s,("undefined"==typeof navigator?Ce.resolve():wn()).then((()=>new Ce(((s,o)=>{if(i(),!r)throw new J.MissingAPI;const l=e.name,c=n.autoSchema?r.open(l):r.open(l,Math.round(10*e.verno));if(!c)throw new J.MissingAPI;c.onerror=Wt(o),c.onblocked=ze(e._fireOnBlocked),c.onupgradeneeded=ze((t=>{if(a=c.transaction,n.autoSchema&&!e._options.allowEmptyDB){c.onerror=Yt,a.abort(),c.result.close();const e=r.deleteDatabase(l);e.onsuccess=e.onerror=ze((()=>{o(new J.NoSuchDatabase(`Database ${l} doesnt exist`))}))}else{a.onerror=Wt(o);var s=t.oldVersion>Math.pow(2,62)?0:t.oldVersion;u=s<1,e.idbdb=c.result,cn(e,s/10,a,o)}}),o),c.onsuccess=ze((()=>{a=null;const r=e.idbdb=c.result,i=p(r.objectStoreNames);if(i.length>0)try{const s=r.transaction(1===(o=i).length?o[0]:o,"readonly");n.autoSchema?function(e,n,r){e.verno=n.version/10;const s=e._dbSchema=pn(0,n,r);e._storeNames=p(n.objectStoreNames,0),an(e,[e._allTables],t(s),s)}(e,r,s):(yn(e,e._dbSchema,s),function(e,t){const n=hn(pn(0,e.idbdb,t),e._dbSchema);return!(n.add.length||n.change.some((e=>e.add.length||e.change.length)))}(e,s)||console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.")),on(e,s)}catch(e){}var o;ft.push(e),r.onversionchange=ze((t=>{n.vcFired=!0,e.on("versionchange").fire(t)})),r.onclose=ze((t=>{e.on("close").fire(t)})),u&&function({indexedDB:e,IDBKeyRange:t},n){!gn(e)&&"__dbnames"!==n&&bn(e,t).put({name:n}).catch(te)}(e._deps,l),s()}),o)}))))]).then((()=>(i(),n.onReadyBeingFired=[],Ce.resolve(vn((()=>e.on.ready.fire(e.vip)))).then((function t(){if(n.onReadyBeingFired.length>0){let r=n.onReadyBeingFired.reduce(le,te);return n.onReadyBeingFired=[],Ce.resolve(vn((()=>r(e.vip)))).then(t)}}))))).finally((()=>{n.openCanceller===s&&(n.onReadyBeingFired=null,n.isBeingOpened=!1)})).catch((t=>{n.dbOpenError=t;try{a&&a.abort()}catch(e){}return s===n.openCanceller&&e._close(),lt(t)})).finally((()=>{n.openComplete=!0,o()})).then((()=>{if(u){const t={};e.tables.forEach((n=>{n.schema.indexes.forEach((r=>{r.name&&(t[`idb://${e.name}/${n.name}/${r.name}`]=new xn(-1/0,[[[]]]))})),t[`idb://${e.name}/${n.name}/`]=t[`idb://${e.name}/${n.name}/:dels`]=new xn(-1/0,[[[]]])})),Gt("storagemutated").fire(t),Bn(t,!0)}return e}))}function Fn(e){var t=t=>e.next(t),r=i(t),s=i((t=>e.throw(t)));function i(e){return t=>{var i=e(t),o=i.value;return i.done?o:o&&"function"==typeof o.then?o.then(r,s):n(o)?Promise.all(o).then(r,s):r(o)}}return i(t)()}function Mn(e,t,n){var r=arguments.length;if(r<2)throw new J.InvalidArgument("Too few arguments");for(var s=new Array(r-1);--r;)s[r-1]=arguments[r];n=s.pop();var i=x(s);return[e,i,n]}function Nn(e,t,n,r,s){return Ce.resolve().then((()=>{const i=Ee.transless||Ee,o=e._createTransaction(t,n,e._dbSchema,r);o.explicit=!0;const a={trans:o,transless:i};if(r)o.idbtrans=r.idbtrans;else try{o.create(),e._state.PR1398_maxLoop=3}catch(r){return r.name===Q.InvalidState&&e.isOpen()&&--e._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),e._close(),e.open().then((()=>Nn(e,t,n,null,s)))):lt(r)}const u=T(s);let l;u&&Ze();const c=Ce.follow((()=>{if(l=s.call(o,o),l)if(u){var e=et.bind(null,null);l.then(e,e)}else"function"==typeof l.next&&"function"==typeof l.throw&&(l=Fn(l))}),a);return(l&&"function"==typeof l.then?Ce.resolve(l).then((e=>o.active?e:lt(new J.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")))):c.then((()=>l))).then((e=>(r&&o._resolve(),o._completion.then((()=>e))))).catch((e=>(o._reject(e),lt(e))))}))}function $n(e,t,r){const s=n(e)?e.slice():[e];for(let e=0;e0,c={...n,name:l?`${r}(virtual-from:${n.name})`:n.name,lowLevelIndex:n,isVirtual:l,keyTail:t,keyLength:u,extractKey:en(e),unique:!l&&n.unique};if(a.push(c),c.isPrimaryKey||i.push(c),u>1){o(2===u?e[0]:e.slice(0,u-1),t+1,n)}return a.sort(((e,t)=>e.keyTail-t.keyTail)),c}const a=o(r.primaryKey.keyPath,0,r.primaryKey);s[":id"]=[a];for(const e of r.indexes)o(e.keyPath,0,e);function u(t){const n=t.query.index;return n.isVirtual?{...t,query:{index:n.lowLevelIndex,range:(r=t.query.range,s=n.keyTail,{type:1===r.type?2:r.type,lower:$n(r.lower,r.lowerOpen?e.MAX_KEY:e.MIN_KEY,s),lowerOpen:!0,upper:$n(r.upper,r.upperOpen?e.MIN_KEY:e.MAX_KEY,s),upperOpen:!0})}}:t;var r,s}const l={...n,schema:{...r,primaryKey:a,indexes:i,getIndexByKeyPath:function(e){const t=s[rn(e)];return t&&t[0]}},count:e=>n.count(u(e)),query:e=>n.query(u(e)),openCursor(t){const{keyTail:r,isVirtual:s,keyLength:i}=t.query.index;if(!s)return n.openCursor(t);return n.openCursor(u(t)).then((n=>n&&function(n){const s=Object.create(n,{continue:{value:function(s){null!=s?n.continue($n(s,t.reverse?e.MAX_KEY:e.MIN_KEY,r)):t.unique?n.continue(n.key.slice(0,i).concat(t.reverse?e.MIN_KEY:e.MAX_KEY,r)):n.continue()}},continuePrimaryKey:{value(t,s){n.continuePrimaryKey($n(t,e.MAX_KEY,r),s)}},primaryKey:{get:()=>n.primaryKey},key:{get(){const e=n.key;return 1===i?e[0]:e.slice(0,i)}},value:{get:()=>n.value}});return s}(n)))}};return l}}}};function Un(e,n,r,s){return r=r||{},s=s||"",t(e).forEach((t=>{if(o(n,t)){var i=e[t],a=n[t];if("object"==typeof i&&"object"==typeof a&&i&&a){const e=C(i);e!==C(a)?r[s+t]=n[t]:"Object"===e?Un(i,a,r,s+t+"."):i!==a&&(r[s+t]=n[t])}else i!==a&&(r[s+t]=n[t])}else r[s+t]=void 0})),t(n).forEach((t=>{o(e,t)||(r[s+t]=n[t])})),r}function Vn(e,t){return"delete"===t.type?t.keys:t.keys||t.values.map(e.extractKey)}const zn={stack:"dbcore",name:"HooksMiddleware",level:2,create:e=>({...e,table(t){const n=e.table(t),{primaryKey:r}=n.schema,s={...n,mutate(e){const s=Ee.trans,{deleting:i,creating:a,updating:u}=s.table(t).hook;switch(e.type){case"add":if(a.fire===te)break;return s._promise("readwrite",(()=>l(e)),!0);case"put":if(a.fire===te&&u.fire===te)break;return s._promise("readwrite",(()=>l(e)),!0);case"delete":if(i.fire===te)break;return s._promise("readwrite",(()=>l(e)),!0);case"deleteRange":if(i.fire===te)break;return s._promise("readwrite",(()=>function(e){return c(e.trans,e.range,1e4)}(e)),!0)}return n.mutate(e);function l(e){const t=Ee.trans,s=e.keys||Vn(r,e);if(!s)throw new Error("Keys missing");return"delete"!==(e="add"===e.type||"put"===e.type?{...e,keys:s}:{...e}).type&&(e.values=[...e.values]),e.keys&&(e.keys=[...e.keys]),function(e,t,n){return"add"===t.type?Promise.resolve([]):e.getMany({trans:t.trans,keys:n,cache:"immutable"})}(n,e,s).then((l=>{const c=s.map(((n,s)=>{const c=l[s],h={onerror:null,onsuccess:null};if("delete"===e.type)i.fire.call(h,n,c,t);else if("add"===e.type||void 0===c){const i=a.fire.call(h,n,e.values[s],t);null==n&&null!=i&&(n=i,e.keys[s]=n,r.outbound||v(e.values[s],r.keyPath,n))}else{const r=Un(c,e.values[s]),i=u.fire.call(h,r,n,c,t);if(i){const t=e.values[s];Object.keys(i).forEach((e=>{o(t,e)?t[e]=i[e]:v(t,e,i[e])}))}}return h}));return n.mutate(e).then((({failures:t,results:n,numFailures:r,lastResult:i})=>{for(let r=0;r(c.forEach((t=>t.onerror&&t.onerror(e))),Promise.reject(e))))}))}function c(e,t,s){return n.query({trans:e,values:!1,query:{index:r,range:t},limit:s}).then((({result:n})=>l({type:"delete",keys:n,trans:e}).then((r=>r.numFailures>0?Promise.reject(r.failures[0]):n.length({table:t=>{const n=e.table(t);return{...n,getMany:e=>{if(!e.cache)return n.getMany(e);const t=Wn(e.keys,e.trans._cache,"clone"===e.cache);return t?Ce.resolve(t):n.getMany(e).then((t=>(e.trans._cache={keys:e.keys,values:"clone"===e.cache?K(t):t},t)))},mutate:e=>("add"!==e.type&&(e.trans._cache=null),n.mutate(e))}}})};function Gn(e,t){return"readonly"===e.trans.mode&&!!e.subscr&&!e.trans.explicit&&"disabled"!==e.trans.db._options.cache&&!t.schema.primaryKey.outbound}function Hn(e,t){switch(e){case"query":return t.values&&!t.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}const Qn={stack:"dbcore",level:0,name:"Observability",create:e=>{const r=e.schema.name,s=new xn(e.MIN_KEY,e.MAX_KEY);return{...e,transaction:(t,n,r)=>{if(Ee.subscr&&"readonly"!==n)throw new J.ReadOnly(`Readwrite transaction in liveQuery context. Querier source: ${Ee.querier}`);return e.transaction(t,n,r)},table:i=>{const o=e.table(i),{schema:a}=o,{primaryKey:u}=a,{extractKey:l,outbound:c}=u,h={...o,mutate:e=>{const t=e.trans,l=e.mutatedParts||(e.mutatedParts={}),c=e=>{const t=`idb://${r}/${i}/${e}`;return l[t]||(l[t]=new xn)},h=c(""),d=c(":dels"),{type:f}=e;let[p,y]="deleteRange"===e.type?[e.range]:"delete"===e.type?[e.keys]:e.values.length<50?[Vn(u,e).filter((e=>e)),e.values]:[];const m=e.trans._cache;if(n(p)){h.addKeys(p);const e="delete"===f||p.length===y.length?Wn(p,m):null;e||"add"===f||d.addKeys(p),(e||y)&&function(e,t,r,s){function i(t){const i=e(t.name||"");function o(e){return null!=e?t.extractKey(e):null}const a=e=>t.multiEntry&&n(e)?e.forEach((e=>i.addKey(e))):i.addKey(e);(r||s).forEach(((e,t)=>{const n=r&&o(r[t]),i=s&&o(s[t]);0!==xt(n,i)&&(null!=n&&a(n),null!=i&&a(i))}))}t.indexes.forEach(i)}(c,a,e,y)}else if(p){const e={from:p.lower,to:p.upper};d.add(e),h.add(e)}else h.add(s),d.add(s),a.indexes.forEach((e=>c(e.name).add(s)));return o.mutate(e).then((n=>(!p||"add"!==e.type&&"put"!==e.type||h.addKeys(n.results),t.mutatedParts=An(t.mutatedParts||{},l),n)))}},d=({query:{index:t,range:n}})=>{var r,s;return[t,new xn(null!==(r=n.lower)&&void 0!==r?r:e.MIN_KEY,null!==(s=n.upper)&&void 0!==s?s:e.MAX_KEY)]},f={get:e=>[u,new xn(e.key)],getMany:e=>[u,(new xn).addKeys(e.keys)],count:d,query:d,openCursor:d};return t(f).forEach((e=>{h[e]=function(t){const{subscr:n}=Ee,a=!!n;let u=Gn(Ee,o)&&Hn(e,t);const h=u?t.obsSet={}:n;if(a){const n=e=>{const t=`idb://${r}/${i}/${e}`;return h[t]||(h[t]=new xn)},a=n(""),u=n(":dels"),[d,p]=f[e](t);if(n(d.name||"").add(p),!d.isPrimaryKey){if("count"!==e){const n="query"===e&&c&&t.values&&o.query({...t,values:!1});return o[e].apply(this,arguments).then((r=>{if("query"===e){if(c&&t.values)return n.then((({result:e})=>(a.addKeys(e),r)));const e=t.values?r.result.map(l):r.result;t.values?a.addKeys(e):u.addKeys(e)}else if("openCursor"===e){const e=r,n=t.values;return e&&Object.create(e,{key:{get:()=>(u.addKey(e.primaryKey),e.key)},primaryKey:{get(){const t=e.primaryKey;return u.addKey(t),t}},value:{get:()=>(n&&a.addKey(e.primaryKey),e.value)}})}return r}))}u.add(s)}}return o[e].apply(this,arguments)}})),h}}}};function Xn(e,t){return function(e,t){return void 0===t.lower||(t.lowerOpen?xt(e,t.lower)>0:xt(e,t.lower)>=0)}(e,t)&&function(e,t){return void 0===t.upper||(t.upperOpen?xt(e,t.upper)<0:xt(e,t.upper)<=0)}(e,t)}function Jn(e,t,n,r,s,i){if(!n||0===n.length)return e;const o=t.query.index,a=r.schema.primaryKey.extractKey,u=o.extractKey,l=(o.lowLevelIndex||o).extractKey;let c=n.reduce(((e,n)=>{let r=e;const s="add"===n.type||"put"===n.type?n.values.filter((e=>Xn(u(e),t.query.range))).map((e=>(e=K(e),i&&Object.freeze(e),e))):[];switch(n.type){case"add":r=e.concat(t.values?s:s.map((e=>a(e))));break;case"put":const i=(new xn).addKeys(n.values.map((e=>a(e))));r=e.filter((e=>{const n=t.values?a(e):e;return!Pn(new xn(n),i)})).concat(t.values?s:s.map((e=>a(e))));break;case"delete":const o=(new xn).addKeys(n.keys);r=e.filter((e=>{const n=t.values?a(e):e;return!Pn(new xn(n),o)}));break;case"deleteRange":const u=n.range;r=e.filter((e=>!Xn(a(e),u)))}return r}),e);return c===e?e:(c.sort(((e,t)=>xt(l(e),l(t))||xt(a(e),a(t)))),t.limit&&t.limit<1/0&&(c.length>t.limit?c.length=t.limit:e.length===t.limit&&c.length=0}function tr(e,t,n,r){e.subscribers.add(n),r.addEventListener("abort",(()=>{e.subscribers.delete(n),0===e.subscribers.size&&function(e,t){setTimeout((()=>{0===e.subscribers.size&&D(t,e)}),3e3)}(e,t)}))}const nr={stack:"dbcore",level:0,name:"Cache",create:e=>{const t=e.schema.name,n={...e,transaction:(n,r,s)=>{const i=e.transaction(n,r,s);if("readwrite"===r){const s=new AbortController,{signal:o}=s,a=o=>()=>{if(s.abort(),"readwrite"===r){const r=new Set;for(const s of n){const n=jn[`idb://${t}/${s}`],a=e.table(s);if(n){const e=n.optimisticOps.filter((e=>e.trans===i));if(e.length>0){n.optimisticOps=n.optimisticOps.filter((e=>e.trans!==i));for(const t of Object.values(n.queries.query))for(const n of t.slice())if(null!=n.res&&i.mutatedParts)if(o&&!n.dirty){const s=Object.isFrozen(n.res),i=Jn(n.res,n.req,e,a,n,s);n.dirty?(D(t,n),n.subscribers.forEach((e=>r.add(e)))):i!==n.res&&(n.res=i,n.promise=Ce.resolve({result:i}))}else n.dirty&&D(t,n),n.subscribers.forEach((e=>r.add(e)))}}}r.forEach((e=>e()))}};i.addEventListener("abort",a(!1),{signal:o}),i.addEventListener("error",a(!1),{signal:o}),i.addEventListener("complete",a(!0),{signal:o})}return i},table(n){const r=e.table(n),s=r.schema.primaryKey,i={...r,mutate(e){if(s.outbound||"disabled"===Ee.trans.db._options.cache)return r.mutate(e);const i=jn[`idb://${t}/${n}`];if(!i)return r.mutate(e);const o=r.mutate(e);return"add"!==e.type&&"put"!==e.type||!(e.values.length>=50||Vn(s,e).some((e=>null==e)))?(i.optimisticOps.push(e),In(e.mutatedParts),o.catch((()=>{D(i.optimisticOps,e),In(e.mutatedParts)}))):o.then((t=>{const n={...e,values:e.values.map(((e,n)=>{const r=s.keyPath.includes(".")?K(e):{...e};return v(r,s.keyPath,t.results[n]),r}))};i.optimisticOps.push(n),queueMicrotask((()=>In(e.mutatedParts)))})),o},query(e){if(!Gn(Ee,r)||!Hn("query",e))return r.query(e);const s="immutable"===Ee.trans.db._options.cache,{requery:i,signal:o}=Ee;let[a,u,l,c]=function(e,t,n,r){const s=jn[`idb://${e}/${t}`];if(!s)return[];const i=s.queries[n];if(!i)return[null,!1,s,null];const o=i[(r.query?r.query.index.name:null)||""];if(!o)return[null,!1,s,null];switch(n){case"query":const e=o.find((e=>e.req.limit===r.limit&&e.req.values===r.values&&Zn(e.req.query.range,r.query.range)));return e?[e,!0,s,o]:[o.find((e=>("limit"in e.req?e.req.limit:1/0)>=r.limit&&(!r.values||e.req.values)&&er(e.req.query.range,r.query.range))),!1,s,o];case"count":const t=o.find((e=>Zn(e.req.query.range,r.query.range)));return[t,!!t,s,o]}}(t,n,"query",e);if(a&&u)a.obsSet=e.obsSet;else{const i=r.query(e).then((e=>{const t=e.result;if(a.res=t,s){for(let e=0,n=t.length;e(c&&a&&D(c,a),Promise.reject(e))));a={obsSet:e.obsSet,promise:i,subscribers:new Set,type:"query",req:e,dirty:!1},c?c.push(a):(c=[a],l||(l=jn[`idb://${t}/${n}`]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}}),l.queries.query[e.query.index.name||""]=c)}return tr(a,c,i,o),a.promise.then((t=>({result:Jn(t.result,e,null==l?void 0:l.optimisticOps,r,a,s)})))}};return i}};return n}};function rr(e,t){return new Proxy(e,{get:(e,n,r)=>"db"===n?t:Reflect.get(e,n,r)})}class sr{constructor(e,t){this._middlewares={},this.verno=0;const n=sr.dependencies;this._options=t={addons:sr.addons,autoOpen:!0,indexedDB:n.indexedDB,IDBKeyRange:n.IDBKeyRange,cache:"cloned",...t},this._deps={indexedDB:t.indexedDB,IDBKeyRange:t.IDBKeyRange};const{addons:r}=t;this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;const s={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:te,dbReadyPromise:null,cancelOpen:te,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3};var i;s.dbReadyPromise=new Ce((e=>{s.dbReadyResolve=e})),s.openCanceller=new Ce(((e,t)=>{s.cancelOpen=t})),this._state=s,this.name=e,this.on=Et(this,"populate","blocked","versionchange","close",{ready:[le,te]}),this.on.ready.subscribe=y(this.on.ready.subscribe,(e=>(t,n)=>{sr.vip((()=>{const r=this._state;if(r.openComplete)r.dbOpenError||Ce.resolve().then(t),n&&e(t);else if(r.onReadyBeingFired)r.onReadyBeingFired.push(t),n&&e(t);else{e(t);const r=this;n||e((function e(){r.on.ready.unsubscribe(t),r.on.ready.unsubscribe(e)}))}}))})),this.Collection=(i=this,Kt(Bt.prototype,(function(e,t){this.db=i;let n=vt,r=null;if(t)try{n=t()}catch(e){r=e}const s=e._ctx,o=s.table,a=o.hook.reading.fire;this._ctx={table:o,index:s.index,isPrimKey:!s.index||o.schema.primKey.keyPath&&s.index===o.schema.primKey.name,range:n,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:r,or:s.or,valueMapper:a!==ne?a:null}}))),this.Table=function(e){return Kt(Pt.prototype,(function(t,n,r){this.db=e,this._tx=r,this.name=t,this.schema=n,this.hook=e._allTables[t]?e._allTables[t].hook:Et(null,{creating:[ie,te],reading:[re,ne],updating:[ae,te],deleting:[oe,te]})}))}(this),this.Transaction=function(e){return Kt(Ht.prototype,(function(t,n,r,s,i){this.db=e,this.mode=t,this.storeNames=n,this.schema=r,this.chromeTransactionDurability=s,this.idbtrans=null,this.on=Et(this,"complete","error","abort"),this.parent=i||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Ce(((e,t)=>{this._resolve=e,this._reject=t})),this._completion.then((()=>{this.active=!1,this.on.complete.fire()}),(e=>{var t=this.active;return this.active=!1,this.on.error.fire(e),this.parent?this.parent._reject(e):t&&this.idbtrans&&this.idbtrans.abort(),lt(e)}))}))}(this),this.Version=function(e){return Kt(mn.prototype,(function(t){this.db=e,this._cfg={version:t,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}}))}(this),this.WhereClause=function(e){return Kt(zt.prototype,(function(t,n,r){if(this.db=e,this._ctx={table:t,index:":id"===n?null:n,or:r},this._cmp=this._ascending=xt,this._descending=(e,t)=>xt(t,e),this._max=(e,t)=>xt(e,t)>0?e:t,this._min=(e,t)=>xt(e,t)<0?e:t,this._IDBKeyRange=e._deps.IDBKeyRange,!this._IDBKeyRange)throw new J.MissingAPI}))}(this),this.on("versionchange",(e=>{e.newVersion>0?console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`):console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`),this.close({disableAutoOpen:!1}),this._state.openComplete=!1})),this.on("blocked",(e=>{!e.newVersion||e.newVersionnew this.Transaction(e,t,n,this._options.chromeTransactionDurability,r),this._fireOnBlocked=e=>{this.on("blocked").fire(e),ft.filter((e=>e.name===this.name&&e!==this&&!e._state.vcFired)).map((t=>t.on("versionchange").fire(e)))},this.use(Yn),this.use(nr),this.use(Qn),this.use(Ln),this.use(zn);const o=new Proxy(this,{get:(e,t,n)=>{if("_vip"===t)return!0;if("table"===t)return e=>rr(this.table(e),o);const r=Reflect.get(e,t,n);return r instanceof Pt?rr(r,o):"tables"===t?r.map((e=>rr(e,o))):"_createTransaction"===t?function(){const e=r.apply(this,arguments);return rr(e,o)}:r}});this.vip=o,r.forEach((e=>e(this)))}version(e){if(isNaN(e)||e<.1)throw new J.Type("Given version is not a positive number");if(e=Math.round(10*e)/10,this.idbdb||this._state.isBeingOpened)throw new J.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,e);const t=this._versions;var n=t.filter((t=>t._cfg.version===e))[0];return n||(n=new this.Version(e),t.push(n),t.sort(ln),n.stores({}),this._state.autoSchema=!1,n)}_whenReady(e){return this.idbdb&&(this._state.openComplete||Ee.letThrough||this._vip)?e():new Ce(((e,t)=>{if(this._state.openComplete)return t(new J.DatabaseClosed(this._state.dbOpenError));if(!this._state.isBeingOpened){if(!this._options.autoOpen)return void t(new J.DatabaseClosed);this.open().catch(te)}this._state.dbReadyPromise.then(e,t)})).then(e)}use({stack:e,create:t,level:n,name:r}){r&&this.unuse({stack:e,name:r});const s=this._middlewares[e]||(this._middlewares[e]=[]);return s.push({stack:e,create:t,level:null==n?10:n,name:r}),s.sort(((e,t)=>e.level-t.level)),this}unuse({stack:e,name:t,create:n}){return e&&this._middlewares[e]&&(this._middlewares[e]=this._middlewares[e].filter((e=>n?e.create!==n:!!t&&e.name!==t))),this}open(){return ot(Pe,(()=>Rn(this)))}_close(){const e=this._state,t=ft.indexOf(this);if(t>=0&&ft.splice(t,1),this.idbdb){try{this.idbdb.close()}catch(e){}this.idbdb=null}e.dbReadyPromise=new Ce((t=>{e.dbReadyResolve=t})),e.openCanceller=new Ce(((t,n)=>{e.cancelOpen=n}))}close({disableAutoOpen:e}={disableAutoOpen:!0}){this._close();const t=this._state;e&&(this._options.autoOpen=!1),t.dbOpenError=new J.DatabaseClosed,t.isBeingOpened&&t.cancelOpen(t.dbOpenError)}delete(){const e=arguments.length>0,t=this._state;return new Ce(((n,r)=>{const s=()=>{this.close({disableAutoOpen:!1});var e=this._deps.indexedDB.deleteDatabase(this.name);e.onsuccess=ze((()=>{!function({indexedDB:e,IDBKeyRange:t},n){!gn(e)&&"__dbnames"!==n&&bn(e,t).delete(n).catch(te)}(this._deps,this.name),n()})),e.onerror=Wt(r),e.onblocked=this._fireOnBlocked};if(e)throw new J.InvalidArgument("Arguments not allowed in db.delete()");t.isBeingOpened?t.dbReadyPromise.then(s):s()}))}backendDB(){return this.idbdb}isOpen(){return null!==this.idbdb}hasBeenClosed(){const e=this._state.dbOpenError;return e&&"DatabaseClosed"===e.name}hasFailed(){return null!==this._state.dbOpenError}dynamicallyOpened(){return this._state.autoSchema}get tables(){return t(this._allTables).map((e=>this._allTables[e]))}transaction(){const e=Mn.apply(this,arguments);return this._transaction.apply(this,e)}_transaction(e,t,n){let r=Ee.trans;r&&r.db===this&&-1===e.indexOf("!")||(r=null);const s=-1!==e.indexOf("?");let i,o;e=e.replace("!","").replace("?","");try{if(o=t.map((e=>{var t=e instanceof this.Table?e.name:e;if("string"!=typeof t)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return t})),"r"==e||"readonly"===e)i="readonly";else{if("rw"!=e&&"readwrite"!=e)throw new J.InvalidArgument("Invalid transaction mode: "+e);i="readwrite"}if(r){if("readonly"===r.mode&&"readwrite"===i){if(!s)throw new J.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");r=null}r&&o.forEach((e=>{if(r&&-1===r.storeNames.indexOf(e)){if(!s)throw new J.SubTransaction("Table "+e+" not included in parent transaction.");r=null}})),s&&r&&!r.active&&(r=null)}}catch(e){return r?r._promise(null,((t,n)=>{n(e)})):lt(e)}const a=Nn.bind(null,this,i,o,r,n);return r?r._promise(i,a,"lock"):Ee.trans?ot(Ee.transless,(()=>this._whenReady(a))):this._whenReady(a)}table(e){if(!o(this._allTables,e))throw new J.InvalidTable(`Table ${e} does not exist`);return this._allTables[e]}}const ir="undefined"!=typeof Symbol&&"observable"in Symbol?Symbol.observable:"@@observable";class or{constructor(e){this._subscribe=e}subscribe(e,t,n){return this._subscribe(e&&"function"!=typeof e?e:{next:e,error:t,complete:n})}[ir](){return this}}let ar;try{ar={indexedDB:e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB,IDBKeyRange:e.IDBKeyRange||e.webkitIDBKeyRange}}catch(e){ar={indexedDB:null,IDBKeyRange:null}}function ur(e){let t,n=!1;const r=new or((r=>{const s=T(e);let i,a=!1,u={},l={};const c={get closed(){return a},unsubscribe:()=>{a||(a=!0,i&&i.abort(),h&&Gt.storagemutated.unsubscribe(d))}};r.start&&r.start(c);let h=!1;const d=e=>{An(u,e),Cn(l,u)&&f()},f=()=>{if(a||!ar.indexedDB)return;u={};const c={};i&&i.abort(),i=new AbortController;const p={subscr:c,signal:i.signal,requery:f,querier:e,trans:null},y=function(t){const n=$e();try{s&&Ze();const r=Je(e,t);return s&&r.finally(et),r}finally{n&&Le()}}(p);Promise.resolve(y).then((e=>{n=!0,t=e,a||p.signal.aborted||(u={},l=c,function(e){for(const t in e)if(o(e,t))return!1;return!0}(l)||h||(Gt("storagemutated",d),h=!0),r.next&&r.next(e))}),(e=>{if(n=!1,!["DatabaseClosedError","AbortError"].includes(null==e?void 0:e.name)){if(a)return;r.error&&r.error(e)}}))};return f(),c}));return r.hasValue=()=>n,r.getValue=()=>t,r}const lr=sr;function cr(e){let t=hr;try{hr=!0,Gt.storagemutated.fire(e),Bn(e,!0)}finally{hr=t}}a(lr,{...ee,delete:e=>new lr(e,{addons:[]}).delete(),exists:e=>new lr(e,{addons:[]}).open().then((e=>(e.close(),!0))).catch("NoSuchDatabaseError",(()=>!1)),getDatabaseNames(e){try{return function({indexedDB:e,IDBKeyRange:t}){return gn(e)?Promise.resolve(e.databases()).then((e=>e.map((e=>e.name)).filter((e=>"__dbnames"!==e)))):bn(e,t).toCollection().primaryKeys()}(lr.dependencies).then(e)}catch(e){return lt(new J.MissingAPI)}},defineClass:()=>function(e){r(this,e)},ignoreTransaction:e=>Ee.trans?ot(Ee.transless,e):e(),vip:vn,async:function(e){return function(){try{var t=Fn(e.apply(this,arguments));return t&&"function"==typeof t.then?t:Ce.resolve(t)}catch(e){return lt(e)}}},spawn:function(e,t,n){try{var r=Fn(e.apply(n,t||[]));return r&&"function"==typeof r.then?r:Ce.resolve(r)}catch(e){return lt(e)}},currentTransaction:{get:()=>Ee.trans||null},waitFor:function(e,t){const n=Ce.resolve("function"==typeof e?lr.ignoreTransaction(e):e).timeout(t||6e4);return Ee.trans?Ee.trans.waitFor(n):n},Promise:Ce,debug:{get:()=>R,set:e=>{F(e,"dexie"===e?()=>!0:bt)}},derive:c,extend:r,props:a,override:y,Events:Et,on:Gt,liveQuery:ur,extendObservabilitySet:An,getByKeyPath:g,setByKeyPath:v,delByKeyPath:function(e,t){"string"==typeof t?v(e,t,void 0):"length"in t&&[].map.call(t,(function(t){v(e,t,void 0)}))},shallowClone:w,deepClone:K,getObjectDiff:Un,cmp:xt,asap:b,minKey:-(1/0),addons:[],connections:ft,errnames:Q,dependencies:ar,cache:jn,semVer:"4.0.1-beta.1",version:"4.0.1-beta.1".split(".").map((e=>parseInt(e))).reduce(((e,t,n)=>e+t/Math.pow(10,2*n)))}),lr.maxKey=Zt(lr.dependencies.IDBKeyRange),"undefined"!=typeof dispatchEvent&&"undefined"!=typeof addEventListener&&(Gt("storagemutated",(e=>{if(!hr){let t;pt?(t=document.createEvent("CustomEvent"),t.initCustomEvent("x-storagemutated-1",!0,!0,e)):t=new CustomEvent("x-storagemutated-1",{detail:e}),hr=!0,dispatchEvent(t),hr=!1}})),addEventListener("x-storagemutated-1",(({detail:e})=>{hr||cr(e)})));let hr=!1;if("undefined"!=typeof BroadcastChannel){const e=new BroadcastChannel("x-storagemutated-1");"function"==typeof e.unref&&e.unref(),Gt("storagemutated",(t=>{hr||e.postMessage(t)})),e.onmessage=e=>{e.data&&cr(e.data)}}else if("undefined"!=typeof self&&"undefined"!=typeof navigator){Gt("storagemutated",(e=>{try{hr||("undefined"!=typeof localStorage&&localStorage.setItem("x-storagemutated-1",JSON.stringify({trig:Math.random(),changedParts:e})),"object"==typeof self.clients&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:"x-storagemutated-1",changedParts:e}))))}catch(e){}})),"undefined"!=typeof addEventListener&&addEventListener("storage",(e=>{if("x-storagemutated-1"===e.key){const t=JSON.parse(e.newValue);t&&cr(t.changedParts)}}));const e=self.document&&navigator.serviceWorker;e&&e.addEventListener("message",(function({data:e}){e&&"x-storagemutated-1"===e.type&&cr(e.changedParts)}))}Ce.rejectionMapper=function(e,t){if(!e||e instanceof W||e instanceof TypeError||e instanceof SyntaxError||!e.name||!Z[e.name])return e;var n=new Z[e.name](t||e.message,e);return"stack"in e&&l(n,"stack",{get:function(){return this.inner.stack}}),n},F(R,bt);export{sr as Dexie,_t as Entity,xn as RangeSet,xt as cmp,sr as default,ur as liveQuery,On as mergeRanges,Pn as rangesOverlap}; +//# sourceMappingURL=dexie.min.mjs.map \ No newline at end of file diff --git a/dist/modern/dexie.min.mjs.map b/dist/modern/dexie.min.mjs.map new file mode 100644 index 000000000..82ce60244 --- /dev/null +++ b/dist/modern/dexie.min.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["dexie.mjs"],"names":["_global","globalThis","self","window","global","keys","Object","isArray","Array","extend","obj","extension","forEach","key","Promise","getProto","getPrototypeOf","_hasOwn","hasOwnProperty","hasOwn","prop","call","props","proto","Reflect","ownKeys","setProp","defineProperty","functionOrGetSet","options","get","set","configurable","value","writable","derive","Child","from","Parent","prototype","create","bind","getOwnPropertyDescriptor","getPropertyDescriptor","_slice","slice","args","start","end","override","origFunc","overridedFactory","assert","b","Error","asap$1","fn","setImmediate","setTimeout","getByKeyPath","keyPath","rv","i","l","length","val","push","period","indexOf","innerObj","substr","undefined","setByKeyPath","isFrozen","currentKeyPath","remainingKeyPath","isNaN","parseInt","splice","shallowClone","m","concat","flatten","a","apply","intrinsicTypeNames","split","map","num","t","filter","intrinsicTypes","Set","cloneSimpleObjectTree","o","k","v","has","constructor","circularRefs","deepClone","any","WeakMap","innerDeepClone","x","toString","toStringTag","iteratorSymbol","Symbol","iterator","getIteratorOf","delArrayItem","NO_CHAR_ARRAY","getArrayOf","arrayLike","it","arguments","this","next","done","isAsyncFunction","debug","location","test","href","setDebug","libraryFilter","NEEDS_THROW_FOR_STACK","stack","getErrorWithStack","e","prettyStack","exception","numIgnoredFrames","name","message","frame","join","idbDomErrorNames","errorList","defaultTexts","VersionChanged","DatabaseClosed","Abort","TransactionInactive","MissingAPI","DexieError","msg","_e","getMultiErrorMessage","failures","s","ModifyError","successCount","failedKeys","BulkError","pos","failuresByPos","_stack","errnames","reduce","BaseException","exceptions","fullName","msgOrInner","inner","Syntax","SyntaxError","Type","TypeError","Range","RangeError","exceptionMap","fullNameExceptions","nop","mirror","pureFunctionChain","f1","f2","callBoth","on1","on2","hookCreatingChain","res","onsuccess","onerror","res2","hookDeletingChain","hookUpdatingChain","modifications","reverseStoppableEventChain","promisableChain","then","thiz","INTERNAL","resolvedNativePromise","nativePromiseProto","resolvedGlobalPromise","globalP","resolve","crypto","subtle","nativeP","digest","Uint8Array","nativePromiseThen","NativePromise","patchGlobalPromise","stack_being_generated","asap","callback","microtickQueue","needsNewPhysicalTick","queueMicrotask","physicalTick","isOutsideMicroTick","unhandledErrors","rejectingErrors","currentFulfiller","rejectionMapper","globalPSD","id","ref","unhandleds","onunhandled","pgp","env","finalize","PSD","numScheduledCalls","tickFinalizers","DexiePromise","_listeners","_lib","psd","_PSD","_stackHolder","_prev","_numPrev","_state","_value","handleRejection","executePromiseTask","thenProp","microTaskId","totalEchoes","onFulfilled","onRejected","possibleAwait","cleanup","decrementExpectedAwaits","reject","propagateToListener","Listener","nativeAwaitCompatibleWrap","linkToPreviousPromise","zone","promise","shouldExecuteTick","beginMicroTickScope","_then","propagateAllListeners","endMicroTickScope","ex","reason","_promise","tryCatch","origProp","some","p","addPossiblyUnhandledError","listeners","len","finalizePhysicalTick","listener","cb","callListener","ret","markErrorAsHandled","getStack","stacks","limit","errorName","failure","prev","numPrev","usePSD","wasRootExec","callbacks","item","unhandledErrs","finalizers","PromiseReject","wrap","errorCatcher","outerScope","switchToZone","catch","type","handler","err","finally","onFinally","timeout","ms","Infinity","handle","Timeout","clearTimeout","snapShot","all","values","onPossibleParallellAsync","remaining","race","newPSD","newScope","scheduler","follow","zoneProps","finalizer","run_at_end_of_this_or_next_physical_tick","allSettled","possiblePromises","results","status","AggregateError","task","awaits","echoes","taskCounter","zoneStack","zoneEchoes","zone_id_counter","a1","a2","parent","globalEnv","PromiseProp","nthen","getPatchedPromiseThen","gthen","incrementExpectedAwaits","possiblePromise","rejection","zoneEnterEcho","targetZone","zoneLeaveEcho","pop","bEnteringZone","currentZone","GlobalPromise","targetEnv","a3","outerZone","origThen","onResolved","tempTransaction","db","mode","storeNames","idbdb","openComplete","letThrough","_vip","trans","_createTransaction","_dbSchema","PR1398_maxLoop","InvalidState","isOpen","console","warn","_close","open","result","idbtrans","commit","_a","_completion","dbOpenError","isBeingOpened","_options","autoOpen","dbReadyPromise","maxString","String","fromCharCode","INVALID_KEY_ARGUMENT","connections","isIEOrEdge","navigator","userAgent","hasIEDeleteObjectStoreBug","hangsOnDeleteLargeKeyRange","dexieStackFrameFilter","combine","filter1","filter2","AnyRange","lower","lowerOpen","upper","upperOpen","workaroundForUndefinedPrimKey","Entity","cmp","ta","tb","NaN","al","bl","compareUint8Arrays","getUint8Array","compareArrays","ArrayBuffer","isView","tsTag","buffer","byteOffset","byteLength","Table","_trans","writeLocked","_tx","tableName","checkTableInTransaction","schema","NotFound","_novip","transless","keyOrCrit","where","first","core","hook","reading","fire","indexOrCrit","WhereClause","keyPaths","equals","compoundIndex","indexes","primKey","ix","compound","every","sort","_maxKey","keyPathsInValidOrder","kp","JSON","stringify","idxByName","idb","_deps","indexedDB","idx","filterFunction","prevIndex","prevFilterFn","index","multi","toCollection","and","count","thenShortcut","offset","numRows","each","toArray","Collection","orderBy","reverse","mapToClass","mappedClass","table","inheritedProps","getOwnPropertyNames","propName","add","readHook","_","unsubscribe","defineClass","content","auto","objToAdd","mutate","numFailures","lastResult","update","keyOrObject","modify","InvalidArgument","put","delete","clear","range","bulkGet","getMany","bulkAdd","objects","keysOrOptions","wantResults","allKeys","numObjects","objectsToAdd","bulkPut","objectsToPut","bulkUpdate","keysAndChanges","coreTable","entry","changeSpecs","changes","offsetMap","cache","objs","resultKeys","resultObjs","Constraint","numEntries","updates","mappedOffset","Number","bulkDelete","numKeys","Events","ctx","evs","eventName","subscriber","subscribe","addEventType","chainFunction","defaultFunction","addConfiguredEvents","context","subscribers","cfg","makeClassConstructor","isPlainKeyRange","ignoreLimitFilter","algorithm","or","justLimit","replayFilter","addFilter","addReplayFilter","factory","isLimitFilter","curr","getIndexOrStore","coreSchema","isPrimKey","primaryKey","getIndexByKeyPath","Schema","openCursor","keysOnly","dir","unique","query","iter","coreTrans","union","cursor","advance","stop","fail","_iterate","iterate","valueMapper","cursorPromise","wrappedFn","c","continue","advancer","_read","_ctx","error","_write","_addAlgorithm","clone","raw","Math","min","sortBy","parts","lastPart","lastIndex","getval","order","sorter","aVal","bVal","offsetLeft","rowsLeft","until","bIncludeStopEntry","last","isMatch","indexName","_ondirectionchange","desc","eachKey","eachUniqueKey","eachPrimaryKey","primaryKeys","uniqueKeys","firstKey","lastKey","distinct","strKey","found","modifyer","anythingModified","outbound","extractKey","modifyChunkSize","totalFailures","applyMutateResult","expectedCount","nextChunk","addValues","putValues","putKeys","deleteKeys","origValue","criteria","deleteCallback","changeSpec","coreRange","simpleCompare","simpleCompareReverse","collectionOrWhereClause","T","collection","emptyCollection","whereClause","rangeEqual","nextCasing","lowerKey","upperNeedle","lowerNeedle","llp","lwrKeyChar","addIgnoreCaseAlgorithm","match","needles","suffix","compare","upperNeedles","lowerNeedles","direction","nextKeySuffix","needlesLen","initDirection","toUpperCase","toLowerCase","upperFactory","lowerFactory","needleBounds","needle","nb","createRange","firstPossibleNeedle","lowestPossibleCasing","casing","between","includeLower","includeUpper","_cmp","above","aboveOrEqual","below","belowOrEqual","startsWith","str","startsWithIgnoreCase","equalsIgnoreCase","anyOfIgnoreCase","startsWithAnyOfIgnoreCase","n","anyOf","_ascending","_descending","notEqual","inAnyRange","includeLowers","includeUppers","noneOf","ranges","ascending","descending","_min","max","_max","sortDirection","rangeSorter","newRange","rangePos","keyIsBeyondCurrentEntry","keyIsBeforeCurrentEntry","checkKey","keyWithinCurrentRange","startsWithAnyOf","eventRejectHandler","event","preventDefault","target","stopPropagation","globalEvents","Transaction","_lock","_reculock","lockOwnerFor","_unlock","_blockedFuncs","_locked","fnAndPSD","shift","OpenFailed","active","transaction","durability","chromeTransactionDurability","ev","_reject","onabort","on","oncomplete","_resolve","storagemutated","bWriteLock","ReadOnly","_root","waitFor","promiseLike","root","_waitingFor","_waitingQueue","store","objectStore","spin","_spinCount","currentWaitPromise","abort","memoizedTables","_memoizedTables","tableSchema","transactionBoundTable","createIndexSpec","src","nameFromKeyPath","createTableSchema","array","extractor","nameAndValue","getMaxKey","IdbKeyRange","only","getKeyExtractor","getSinglePathKeyExtractor","arrayify","_id_counter","getKeyPathAlias","createDBCore","tmpTrans","makeIDBKeyRange","upperBound","lowerBound","bound","hasGetAll","tables","objectStoreNames","autoIncrement","indexByKeyPath","isPrimaryKey","indexNames","multiEntry","extractSchema","isAddOrPut","req","reqs","errorHandler","args1","args2","keyCount","callbackCount","successHandler","_pos","request","nonInfinitLimit","source","idbKeyRange","getAll","getAllKeys","openKeyCursor","___id","_cursorContinue","_cursorContinuePrimaryKey","continuePrimaryKey","_cursorAdvance","doThrowCursorIsStopped","gotOne","iterationPromise","resolveIteration","rejectIteration","guardedCallback","createDbCoreTable","tableMap","MIN_KEY","MAX_KEY","generateMiddlewareStacks","middlewares","IDBKeyRange","dbcore","stackImpl","down","createMiddlewareStack","createMiddlewareStacks","_middlewares","tbl","setApiOnPlace","tableNames","dbschema","propDesc","enumerable","removeTablesApi","lowerVersionFirst","_cfg","version","runUpgraders","oldVersion","idbUpgradeTrans","globalSchema","_storeNames","rejectTransaction","createTable","populate","queue","versions","_versions","buildGlobalSchema","anyContentUpgraderHasRun","runQueue","oldSchema","newSchema","adjustToExistingIndexNames","diff","getSchemaDiff","tuple","change","recreate","Upgrade","addIndex","deleteIndex","del","idxName","contentUpgrade","upgradeSchema","contentUpgradeIsAsync","returnValue","promiseFollowed","decrementor","storeName","deleteObjectStore","deleteRemovedTables","contains","updateTablesAndIndexes","oldDef","newDef","def","oldIndexes","newIndexes","oldIdx","newIdx","createObjectStore","createIndex","j","idbindex","_hasGetAll","dexieName","indexSpec","WorkerGlobalScope","Version","_parseStoresSpec","stores","outSchema","indexNum","trim","replace","storesSource","storesSpec","_allTables","upgrade","upgradeFunction","getDbNamesTable","dbNamesDB","Dexie$1","addons","dbnames","hasDatabasesNative","databases","vip","idbReady","intervalId","userAgentData","tryIdb","setInterval","clearInterval","isEmptyRange","node","RangeSet","fromOrTree","to","d","addRange","left","right","r","rebalance","rightWasCutOff","mergeRanges","newSet","_addRangeSet","rangesOverlap","rangeSet1","rangeSet2","i1","getRangeSetIterator","nextResult1","i2","nextResult2","state","keyProvided","up","_b","rootClone","oldRootRight","computeDepth","extendObservabilitySet","part","obsSetsOverlap","os1","os2","rangeSet","addKey","addKeys","unsignaledParts","isTaskEnqueued","signalSubscribersLazily","signalSubscribersNow","updatedParts","deleteAffectedCacheEntries","queriesToSignal","exec","dbName","tblCache","signalTableSubscribersNow","requery","outQueriesToSignal","updatedEntryLists","entries","queries","filteredEntries","obsSet","dexieOpen","openCanceller","throwIfCancelled","resolveDbReady","dbReadyResolve","upgradeTransaction","wasCreated","autoSchema","round","verno","onblocked","_fireOnBlocked","onupgradeneeded","allowEmptyDB","close","delreq","deleteDatabase","NoSuchDatabase","oldVer","pow","readGlobalSchema","ch","verifyInstalledSchema","onversionchange","vcFired","onclose","_onDatabaseCreated","onReadyBeingFired","ready","fireRemainders","remainders","everything","awaitIterator","callNext","onSuccess","step","onError","throw","getNext","extractTransactionArgs","_tableArgs_","scopeFunc","enterTransactionScope","parentTransaction","explicit","scopeFuncIsAsync","PrematureCommit","pad","virtualIndexMiddleware","level","indexLookup","allVirtualIndexes","addVirtualIndexes","keyTail","lowLevelIndex","keyPathAlias","indexList","keyLength","isVirtual","virtualIndex","translateRequest","virtualCursor","createVirtualCursor","getObjectDiff","prfx","ap","bp","apTypeName","getEffectiveKeys","hooksMiddleware","downCore","downTable","tableMiddleware","dxTrans","deleting","creating","updating","addPutOrDelete","deleteNextChunk","deleteRange","effectiveKeys","getExistingValues","existingValues","contexts","existingValue","generatedPrimaryKey","objectDiff","additionalChanges","requestedValue","getFromTransactionCache","cacheExistingValuesMiddleware","cachedResult","isCachableContext","subscr","isCachableRequest","observabilityMiddleware","FULL_RANGE","querier","tableClone","mutatedParts","getRangeSet","pkRangeSet","delsRangeSet","newObjs","oldCache","oldObjs","addAffectedIndex","addKeyOrKeys","oldKey","newKey","trackAffectedIndexes","getRange","readSubscribers","method","isLiveQuery","cachable","queriedIndex","queriedRanges","keysPromise","resultingKeys","pKeys","wantValues","pkey","isWithinRange","isAboveLower","isBelowUpper","applyOptimisticOps","ops","cacheEntry","immutable","extractPrimKey","extractIndex","extractLowLevelIndex","finalResult","op","modifedResult","includedValues","freeze","keySet","keysToDelete","dirty","areRangesEqual","r1","r2","isSuperRange","lower1","lower2","lowerOpen1","lowerOpen2","compareLowers","upper1","upper2","upperOpen1","upperOpen2","compareUppers","subscribeToCacheEntry","container","signal","addEventListener","size","enqueForDeletion","cacheMiddleware","coreMW","ac","AbortController","endTransaction","wasCommitted","affectedSubscribers","optimisticOps","freezeResults","modRes","tableMW","reqWithResolvedKeys","valueWithKey","includes","exactMatch","equalEntry","find","countQuery","findCompatibleQuery","Map","vipify","vipDb","Proxy","receiver","deps","dependencies","cancelOpen","bSticky","keyRangeGenerator","keyRange","whereCtx","readingHook","createTableConstructor","complete","wasActive","createTransactionConstructor","versionNumber","createVersionConstructor","orCollection","_IDBKeyRange","createWhereClauseConstructor","newVersion","disableAutoOpen","use","vipDB","tx","addon","versionInstance","_whenReady","unuse","mw","hasArguments","doDelete","_onDatabaseDeleted","backendDB","hasBeenClosed","hasFailed","dynamicallyOpened","_transaction","onlyIfCompatible","idbMode","SubTransaction","enterTransaction","InvalidTable","symbolObservable","observable","Observable","_subscribe","domDeps","mozIndexedDB","webkitIndexedDB","msIndexedDB","webkitIDBKeyRange","liveQuery","currentValue","hasValue","observer","abortController","closed","accumMuts","currentObs","subscription","startedListening","mutationListener","doQuery","execute","aborted","objectIsEmpty","getValue","Dexie","propagateLocally","updateParts","wasMe","propagatingLocally","databaseName","exists","getDatabaseNames","infos","info","ignoreTransaction","async","generatorFn","spawn","currentTransaction","promiseOrFunction","optionalTimeout","delByKeyPath","minKey","semVer","maxKey","dispatchEvent","document","createEvent","initCustomEvent","CustomEvent","detail","BroadcastChannel","bc","unref","changedParts","postMessage","onmessage","data","localStorage","setItem","trig","random","matchAll","includeUncontrolled","client","parse","newValue","swContainer","serviceWorker","domError"],"mappings":"AAaA,MAAMA,EAAgC,oBAAfC,WAA6BA,WAChC,oBAATC,KAAuBA,KACR,oBAAXC,OAAyBA,OAC5BC,OAENC,EAAOC,OAAOD,KACdE,EAAUC,MAAMD,QAItB,SAASE,EAAOC,EAAKC,GACjB,MAAyB,iBAAdA,GAEXN,EAAKM,GAAWC,SAAQ,SAAUC,GAC9BH,EAAIG,GAAOF,EAAUE,MAFdH,EALQ,oBAAZI,SAA4Bd,EAAQc,UAC3Cd,EAAQc,QAAUA,SAUtB,MAAMC,EAAWT,OAAOU,eAClBC,EAAU,GAAGC,eACnB,SAASC,EAAOT,EAAKU,GACjB,OAAOH,EAAQI,KAAKX,EAAKU,GAE7B,SAASE,EAAMC,EAAOZ,GACO,mBAAdA,IACPA,EAAYA,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AAOjyB,KAAKyyB,MAAMphB,EAAGqhB,UACvBT,GACAhC,GAAiBgC,EAAKH,kBAItC,MAAMa,EAAc7uC,KAAKwtC,UAAYn1B,UAAUy2B,cAC3CD,GACAA,EAAYvI,iBAAiB,WAGrC,UAAiC6H,KAAEA,IAC3BA,GA39F+B,uBA29FvBA,EAAK37B,MACb25B,GAAiBgC,EAAKH,iBAI9B3/B,GAAaZ,gBA9mKb,SAAkBshC,EAAU1mC,GACxB,IAAK0mC,GAAYA,aAAoB/lC,GAAc+lC,aAAoBxkC,WAAawkC,aAAoB1kC,cAAgB0kC,EAAS3mC,OAASsC,EAAaqkC,EAAS3mC,MAC5J,OAAO2mC,EACX,IAAIprC,EAAK,IAAI+G,EAAaqkC,EAAS3mC,MAAMC,GAAW0mC,EAAS1mC,QAAS0mC,GAMtE,MALI,UAAWA,GACXvtC,EAAQmC,EAAI,QAAS,CAAE/B,IAAK,WACpB,OAAOuF,KAAKgD,MAAMrC,SAGvBnE,GAsmKXgE,EAASJ,EAAOkR,WAEP2f,YAAkBjf,aAAQ+f,eAAU9f,UAAKgf,cAAoB8S,gBAAWtR,kBAAaG"} \ No newline at end of file diff --git a/dist/modern/dexie.mjs b/dist/modern/dexie.mjs new file mode 100644 index 000000000..b2d43a44f --- /dev/null +++ b/dist/modern/dexie.mjs @@ -0,0 +1,5665 @@ +/* + * Dexie.js - a minimalistic wrapper for IndexedDB + * =============================================== + * + * By David Fahlander, david.fahlander@gmail.com + * + * Version 4.0.1-beta.1, Wed Oct 18 2023 + * + * https://dexie.org + * + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/ + */ + +const _global = typeof globalThis !== 'undefined' ? globalThis : + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + +const keys = Object.keys; +const isArray = Array.isArray; +if (typeof Promise !== 'undefined' && !_global.Promise) { + _global.Promise = Promise; +} +function extend(obj, extension) { + if (typeof extension !== 'object') + return obj; + keys(extension).forEach(function (key) { + obj[key] = extension[key]; + }); + return obj; +} +const getProto = Object.getPrototypeOf; +const _hasOwn = {}.hasOwnProperty; +function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); +} +function props(proto, extension) { + if (typeof extension === 'function') + extension = extension(getProto(proto)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(key => { + setProp(proto, key, extension[key]); + }); +} +const 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) + }; + } + }; +} +const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +function getPropertyDescriptor(obj, prop) { + const pd = getOwnPropertyDescriptor(obj, prop); + let proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); +} +const _slice = [].slice; +function slice(args, start, end) { + return _slice.call(args, start, end); +} +function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); +} +function assert(b) { + if (!b) + throw new Error("Assertion Failed"); +} +function asap$1(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); +} +function arrayToObject(array, extractor) { + return array.reduce((result, item, i) => { + var nameAndValue = extractor(item, i); + if (nameAndValue) + result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); +} +function tryCatch(fn, onerror, args) { + try { + fn.apply(null, args); + } + catch (ex) { + onerror && onerror(ex); + } +} +function getByKeyPath(obj, keyPath) { + if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) + return obj[keyPath]; + 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) { + if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) + obj.splice(currentKeyPath, 1); + else + delete obj[currentKeyPath]; + } + else + obj[currentKeyPath] = value; + else { + var innerObj = obj[currentKeyPath]; + if (!innerObj || !hasOwn(obj, currentKeyPath)) + innerObj = (obj[currentKeyPath] = {}); + setByKeyPath(innerObj, remainingKeyPath, value); + } + } + else { + if (value === undefined) { + if (isArray(obj) && !isNaN(parseInt(keyPath))) + obj.splice(keyPath, 1); + else + 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; +} +const concat = [].concat; +function flatten(a) { + return concat.apply([], a); +} +const intrinsicTypeNames = "Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" + .split(',').concat(flatten([8, 16, 32, 64].map(num => ["Int", "Uint", "Float"].map(t => t + num + "Array")))).filter(t => _global[t]); +const intrinsicTypes = new Set(intrinsicTypeNames.map(t => _global[t])); +function cloneSimpleObjectTree(o) { + const rv = {}; + for (const k in o) + if (hasOwn(o, k)) { + const v = o[k]; + rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); + } + return rv; +} +function objectIsEmpty(o) { + for (const k in o) + if (hasOwn(o, k)) + return false; + return true; +} +let circularRefs = null; +function deepClone(any) { + circularRefs = new WeakMap(); + const rv = innerDeepClone(any); + circularRefs = null; + return rv; +} +function innerDeepClone(x) { + if (!x || typeof x !== 'object') + return x; + let rv = circularRefs.get(x); + if (rv) + return rv; + if (isArray(x)) { + rv = []; + circularRefs.set(x, rv); + for (var i = 0, l = x.length; i < l; ++i) { + rv.push(innerDeepClone(x[i])); + } + } + else if (intrinsicTypes.has(x.constructor)) { + rv = x; + } + else { + const proto = getProto(x); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs.set(x, rv); + for (var prop in x) { + if (hasOwn(x, prop)) { + rv[prop] = innerDeepClone(x[prop]); + } + } + } + return rv; +} +const { toString } = {}; +function toStringTag(o) { + return toString.call(o).slice(8, -1); +} +const iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; +const getIteratorOf = typeof iteratorSymbol === "symbol" ? function (x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); +} : function () { return null; }; +function delArrayItem(a, x) { + const i = a.indexOf(x); + if (i >= 0) + a.splice(i, 1); + return i >= 0; +} +const NO_CHAR_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; +} +const isAsyncFunction = typeof Symbol !== 'undefined' + ? (fn) => fn[Symbol.toStringTag] === 'AsyncFunction' + : () => false; + +var debug = typeof location !== 'undefined' && + /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); +function setDebug(value, filter) { + debug = value; + libraryFilter = filter; +} +var libraryFilter = () => true; +const NEEDS_THROW_FOR_STACK = !new Error("").stack; +function getErrorWithStack() { + if (NEEDS_THROW_FOR_STACK) + try { + getErrorWithStack.arguments; + throw new Error(); + } + 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(frame => "\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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" +}; +function DexieError(name, msg) { + 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: " + Object.keys(failures) + .map(key => failures[key].toString()) + .filter((v, i, s) => s.indexOf(v) === i) + .join('\n'); +} +function ModifyError(msg, failures, successCount, failedKeys) { + this._e = getErrorWithStack(); + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + this.message = getMultiErrorMessage(msg, failures); +} +derive(ModifyError).from(DexieError); +function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = Object.keys(failures).map(pos => failures[pos]); + this.failuresByPos = failures; + this.message = getMultiErrorMessage(msg, this.failures); +} +derive(BulkError).from(DexieError); +var errnames = errorList.reduce((obj, name) => (obj[name] = name + "Error", obj), {}); +const BaseException = DexieError; +var exceptions = errorList.reduce((obj, name) => { + 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}${!inner ? '' : '\n ' + inner}`; + 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; +}, {}); +exceptions.Syntax = SyntaxError; +exceptions.Type = TypeError; +exceptions.Range = RangeError; +var exceptionMap = idbDomErrorNames.reduce((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) { + setProp(rv, "stack", { get: function () { + return this.inner.stack; + } }); + } + return rv; +} +var fullNameExceptions = errorList.reduce((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) { + 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) { + if (f1 === nop) + return f2; + return function () { + var res = f1.apply(this, arguments); + if (res !== undefined) + arguments[0] = res; + var onsuccess = this.onsuccess, + onerror = 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, + onerror = 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); + var onsuccess = this.onsuccess, + onerror = 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); + }; +} + +var INTERNAL = {}; +const LONG_STACKS_CLIP_LIMIT = 100, +MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ? + [] : + (() => { + let globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + const nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), nativePromiseThen = nativePromiseProto && nativePromiseProto.then; +const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; +const patchGlobalPromise = !!resolvedGlobalPromise; +var stack_being_generated = false; +function schedulePhysicalTick() { + queueMicrotask(physicalTick); +} +var asap = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } +}; +var isOutsideMicroTick = true, +needsNewPhysicalTick = true, +unhandledErrors = [], +rejectingErrors = [], +currentFulfiller = null, rejectionMapper = mirror; +var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: nop, + pgp: false, + env: {}, + finalize: nop +}; +var PSD = globalPSD; +var microtickQueue = []; +var numScheduledCalls = 0; +var tickFinalizers = []; +function DexiePromise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + this._lib = false; + var psd = (this._PSD = PSD); + if (debug) { + this._stackHolder = getErrorWithStack(); + this._prev = null; + this._numPrev = 0; + } + if (typeof fn !== 'function') { + if (fn !== INTERNAL) + throw new TypeError('Not a function'); + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); + return; + } + this._state = null; + this._value = null; + ++psd.ref; + executePromiseTask(this, fn); +} +const thenProp = { + get: function () { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + const cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise((resolve, reject) => { + propagateToListener(this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; + return then; + }, + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : + { + get: function () { + return value; + }, + set: thenProp.set + }); + } +}; +props(DexiePromise.prototype, { + then: thenProp, + _then: function (onFulfilled, onRejected) { + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function (onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + var type = arguments[0], handler = arguments[1]; + return typeof type === 'function' ? this.then(null, err => + err instanceof type ? handler(err) : PromiseReject(err)) + : this.then(null, err => + err && err.name === type ? handler(err) : PromiseReject(err)); + }, + finally: function (onFinally) { + return this.then(value => { + onFinally(); + return value; + }, 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; + return stack; + } + finally { + stack_being_generated = false; + } + } + }, + timeout: function (ms, msg) { + return ms < Infinity ? + new DexiePromise((resolve, reject) => { + var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms); + this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } +}); +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) + setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise'); +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; +} +props(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) + .map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach((a, i) => DexiePromise.resolve(a).then(x => { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject)); + }); + }, + resolve: value => { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise((resolve, reject) => { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise((resolve, reject) => { + values.map(value => DexiePromise.resolve(value).then(resolve, reject)); + }); + }, + PSD: { + get: () => PSD, + set: value => PSD = value + }, + totalEchoes: { get: () => totalEchoes }, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: () => asap, + set: value => { asap = value; } + }, + rejectionMapper: { + get: () => rejectionMapper, + set: value => { rejectionMapper = value; } + }, + follow: (fn, zoneProps) => { + return new DexiePromise((resolve, reject) => { + return newScope((resolve, reject) => { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject; + psd.finalize = callBoth(function () { + run_at_end_of_this_or_next_physical_tick(() => { + this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } +}); +if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function () { + const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(resolve => { + if (possiblePromises.length === 0) + resolve([]); + let remaining = possiblePromises.length; + const results = new Array(remaining); + possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => results[i] = { status: "fulfilled", value }, reason => results[i] = { status: "rejected", reason }) + .then(() => --remaining || resolve(results))); + }); + }); + if (NativePromise.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise((resolve, reject) => { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + let remaining = possiblePromises.length; + const failures = new Array(remaining); + possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(value => resolve(value), failure => { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + })); + }); + }); +} +function executePromiseTask(promise, fn) { + try { + fn(value => { + if (promise._state !== null) + return; + 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, (resolve, reject) => { + value instanceof DexiePromise ? + value._then(resolve, reject) : + value.then(resolve, reject); + }); + } + else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); + } + 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(() => { + var origProp = getPropertyDescriptor(reason, "stack"); + reason._promise = promise; + setProp(reason, "stack", { + get: () => stack_being_generated ? + origProp && (origProp.get ? + origProp.get.apply(reason) : + origProp.value) : + promise.stack + }); + }); + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); +} +function propagateAllListeners(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 (numScheduledCalls === 0) { + ++numScheduledCalls; + asap(() => { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } +} +function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap(callListener, [cb, promise, listener]); +} +function callListener(cb, promise, listener) { + try { + currentFulfiller = promise; + var ret, value = promise._value; + if (promise._state) { + ret = cb(value); + } + else { + if (rejectingErrors.length) + rejectingErrors = []; + ret = cb(value); + if (rejectingErrors.indexOf(value) === -1) + markErrorAsHandled(promise); + } + listener.resolve(ret); + } + catch (e) { + listener.reject(e); + } + finally { + 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; + 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) { + var numPrev = prev ? prev._numPrev + 1 : 0; + if (numPrev < LONG_STACKS_CLIP_LIMIT) { + promise._prev = prev; + promise._numPrev = numPrev; + } +} +function physicalTick() { + usePSD(globalPSD, () => { + beginMicroTickScope() && endMicroTickScope(); + }); +} +function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; +} +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(p => { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); + 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(() => { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); +} +function addPossiblyUnhandledError(promise) { + if (!unhandledErrors.some(p => p._value === promise._value)) + unhandledErrors.push(promise); +} +function markErrorAsHandled(promise) { + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + unhandledErrors.splice(i, 1); + return; + } +} +function PromiseReject(reason) { + return new DexiePromise(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(); + } + }; +} +const task = { awaits: 0, echoes: 0, id: 0 }; +var taskCounter = 0; +var zoneStack = []; +var zoneEchoes = 0; +var totalEchoes = 0; +var zone_id_counter = 0; +function newScope(fn, props, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + var globalEnv = globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) + } : {}; + if (props) + extend(psd, props); + ++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 incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; +} +function decrementExpectedAwaits() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; +} +if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; +} +function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(x => { + decrementExpectedAwaits(); + return x; + }, e => { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; +} +function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.id = 0; + } + 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)) { + queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + var GlobalPromise = globalPSD.env.Promise; + var targetEnv = targetZone.env; + nativePromiseProto.then = targetEnv.nthen; + GlobalPromise.prototype.then = targetEnv.gthen; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp); + GlobalPromise.all = targetEnv.all; + GlobalPromise.race = targetEnv.race; + GlobalPromise.resolve = targetEnv.resolve; + GlobalPromise.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise.any = targetEnv.any; + } + } +} +function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + 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 nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { + 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); + if (cleanup) + queueMicrotask(decrementExpectedAwaits); + } + }; +} +function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; +} +var rejection = DexiePromise.reject; + +function tempTransaction(db, mode, storeNames, fn) { + if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) { + if (db._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError)); + } + if (!db._state.isBeingOpened) { + if (!db._options.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db.open().catch(nop); + } + return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn)); + } + else { + var trans = db._createTransaction(mode, storeNames, db._dbSchema); + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(() => tempTransaction(db, mode, storeNames, fn)); + } + return rejection(ex); + } + return trans._promise(mode, (resolve, reject) => { + return newScope(() => { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(result => { + if (mode === 'readwrite') + try { + trans.idbtrans.commit(); + } + catch (_a) { } + return mode === 'readonly' ? result : trans._completion.then(() => result); + }); + } +} + +const DEXIE_VERSION = '4.0.1-beta.1'; +const maxString = String.fromCharCode(65535); +const minKey = -Infinity; +const INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; +const STRING_EXPECTED = "String expected."; +const connections = []; +const isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent); +const hasIEDeleteObjectStoreBug = isIEOrEdge; +const hangsOnDeleteLargeKeyRange = isIEOrEdge; +const dexieStackFrameFilter = frame => !/(dexie\.js|dexie\.min\.js)/.test(frame); +const DBNAMES_DB = '__dbnames'; +const READONLY = 'readonly'; +const READWRITE = 'readwrite'; + +function combine(filter1, filter2) { + return filter1 ? + filter2 ? + function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } : + filter1 : + filter2; +} + +const AnyRange = { + type: 3 , + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false +}; + +function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) + ? (obj) => { + if (obj[keyPath] === undefined && (keyPath in obj)) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } + : (obj) => obj; +} + +function Entity() { + throw exceptions.Type(); +} + +function cmp(a, b) { + try { + const ta = type(a); + const tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; +} +function compareArrays(a, b) { + const al = a.length; + const bl = b.length; + const l = al < bl ? al : bl; + for (let i = 0; i < l; ++i) { + const res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function compareUint8Arrays(a, b) { + const al = a.length; + const bl = b.length; + const l = al < bl ? al : bl; + for (let i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; +} +function type(x) { + const t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + const tsTag = toStringTag(x); + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; +} +function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); +} + +class Table { + _trans(mode, fn, writeLocked) { + const trans = this._tx || PSD.trans; + const tableName = this.name; + function checkTableInTransaction(resolve, reject, trans) { + if (!trans.schema[tableName]) + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + return fn(trans.idbtrans, trans); + } + const wasRootExec = beginMicroTickScope(); + try { + return trans && trans.db._novip === this.db._novip ? + trans === PSD.trans ? + trans._promise(mode, checkTableInTransaction, writeLocked) : + newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) : + tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + } + finally { + if (wasRootExec) + endMicroTickScope(); + } + } + get(keyOrCrit, cb) { + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + return this._trans('readonly', (trans) => { + return this.core.get({ trans, key: keyOrCrit }) + .then(res => this.hook.reading.fire(res)); + }).then(cb); + } + where(indexOrCrit) { + if (typeof indexOrCrit === 'string') + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`); + const keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this + .where(keyPaths[0]) + .equals(indexOrCrit[keyPaths[0]]); + const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => { + if (ix.compound && + keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) { + for (let i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort((a, b) => a.keyPath.length - b.keyPath.length)[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + const keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this + .where(keyPathsInValidOrder) + .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp])); + } + if (!compoundIndex && debug) + console.warn(`The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` + + `compound index [${keyPaths.join('+')}]`); + const { idxByName } = this.schema; + const idb = this.db._deps.indexedDB; + function equals(a, b) { + return idb.cmp(a, b) === 0; + } + const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => { + const index = idxByName[keyPath]; + const value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? + combine(prevFilterFn, index && index.multi ? + x => { + const prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(item => equals(value, item)); + } : x => equals(value, getByKeyPath(x, keyPath))) + : prevFilterFn + ]; + }, [null, null]); + return idx ? + this.where(idx.name).equals(indexOrCrit[idx.keyPath]) + .filter(filterFunction) : + compoundIndex ? + this.filter(filterFunction) : + this.where(keyPaths).equals(''); + } + filter(filterFunction) { + return this.toCollection().and(filterFunction); + } + count(thenShortcut) { + return this.toCollection().count(thenShortcut); + } + offset(offset) { + return this.toCollection().offset(offset); + } + limit(numRows) { + return this.toCollection().limit(numRows); + } + each(callback) { + return this.toCollection().each(callback); + } + toArray(thenShortcut) { + return this.toCollection().toArray(thenShortcut); + } + toCollection() { + return new this.db.Collection(new this.db.WhereClause(this)); + } + orderBy(index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? + `[${index.join('+')}]` : + index)); + } + reverse() { + return this.toCollection().reverse(); + } + mapToClass(constructor) { + const { db, name: tableName } = this; + this.schema.mappedClass = constructor; + if (constructor.prototype instanceof Entity) { + constructor = class extends constructor { + get db() { return db; } + table() { return tableName; } + }; + } + const inheritedProps = new Set(); + for (let proto = constructor.prototype; proto; proto = getProto(proto)) { + Object.getOwnPropertyNames(proto).forEach(propName => inheritedProps.add(propName)); + } + const readHook = (obj) => { + if (!obj) + return obj; + const res = Object.create(constructor.prototype); + for (let m in obj) + if (!inheritedProps.has(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 Class(content) { + extend(this, content); + } + return this.mapToClass(Class); + } + add(obj, key) { + const { auto, keyPath } = this.schema.primKey; + let objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', trans => { + return this.core.mutate({ trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd] }); + }).then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult) + .then(lastResult => { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + } + update(keyOrObject, modifications) { + if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) { + const 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 { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + } + put(obj, key) { + const { auto, keyPath } = this.schema.primKey; + let objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null })) + .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult) + .then(lastResult => { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } + catch (_) { } + } + return lastResult; + }); + } + delete(key) { + return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'delete', keys: [key] })) + .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined); + } + clear() { + return this._trans('readwrite', trans => this.core.mutate({ trans, type: 'deleteRange', range: AnyRange })) + .then(res => res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined); + } + bulkGet(keys) { + return this._trans('readonly', trans => { + return this.core.getMany({ + keys, + trans + }).then(result => result.map(res => this.hook.reading.fire(res))); + }); + } + bulkAdd(objects, keysOrOptions, options) { + const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + const wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', trans => { + const { auto, keyPath } = this.schema.primKey; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + const numObjects = objects.length; + let objectsToAdd = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return this.core.mutate({ trans, type: 'add', keys: keys, values: objectsToAdd, wantResults }) + .then(({ numFailures, results, lastResult, failures }) => { + const result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(`${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures); + }); + }); + } + bulkPut(objects, keysOrOptions, options) { + const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined; + options = options || (keys ? undefined : keysOrOptions); + const wantResults = options ? options.allKeys : undefined; + return this._trans('readwrite', trans => { + const { auto, keyPath } = this.schema.primKey; + if (keyPath && keys) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys && keys.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + const numObjects = objects.length; + let objectsToPut = keyPath && auto ? + objects.map(workaroundForUndefinedPrimKey(keyPath)) : + objects; + return this.core.mutate({ trans, type: 'put', keys: keys, values: objectsToPut, wantResults }) + .then(({ numFailures, results, lastResult, failures }) => { + const result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError(`${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures); + }); + }); + } + bulkUpdate(keysAndChanges) { + const coreTable = this.core; + const keys = keysAndChanges.map((entry) => entry.key); + const changeSpecs = keysAndChanges.map((entry) => entry.changes); + const offsetMap = []; + return this._trans('readwrite', (trans) => { + return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => { + const resultKeys = []; + const resultObjs = []; + keysAndChanges.forEach(({ key, changes }, idx) => { + const obj = objs[idx]; + if (obj) { + for (const keyPath of Object.keys(changes)) { + const value = changes[keyPath]; + if (keyPath === this.schema.primKey.keyPath) { + if (cmp(value, key) !== 0) { + throw new exceptions.Constraint(`Cannot update primary key in bulkUpdate()`); + } + } + else { + setByKeyPath(obj, keyPath, value); + } + } + offsetMap.push(idx); + resultKeys.push(key); + resultObjs.push(obj); + } + }); + const numEntries = resultKeys.length; + return coreTable + .mutate({ + trans, + type: 'put', + keys: resultKeys, + values: resultObjs, + updates: { + keys, + changeSpecs + } + }) + .then(({ numFailures, failures }) => { + if (numFailures === 0) + return numEntries; + for (const offset of Object.keys(failures)) { + const mappedOffset = offsetMap[Number(offset)]; + if (mappedOffset != null) { + const failure = failures[offset]; + delete failures[offset]; + failures[mappedOffset] = failure; + } + } + throw new BulkError(`${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`, failures); + }); + }); + }); + } + bulkDelete(keys) { + const numKeys = keys.length; + return this._trans('readwrite', trans => { + return this.core.mutate({ trans, type: 'delete', keys: keys }); + }).then(({ numFailures, lastResult, failures }) => { + if (numFailures === 0) + return lastResult; + throw new BulkError(`${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures); + }); + } +} + +function Events(ctx) { + var evs = {}; + var rv = function (eventName, subscriber) { + if (subscriber) { + 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 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) { + keys(cfg).forEach(function (eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add(eventName, cfg[eventName][0], cfg[eventName][1]); + } + else if (args === 'asap') { + var context = add(eventName, mirror, function fire() { + var i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + context.subscribers.forEach(function (fn) { + asap$1(function fireEvent() { + fn.apply(null, args); + }); + }); + }); + } + else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } +} + +function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype }); + return constructor; +} + +function createTableConstructor(db) { + return makeClassConstructor(Table.prototype, function Table(name, tableSchema, trans) { + this.db = db; + this._tx = trans; + this.name = name; + this.schema = tableSchema; + this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, { + "creating": [hookCreatingChain, nop], + "reading": [pureFunctionChain, mirror], + "updating": [hookUpdatingChain, nop], + "deleting": [hookDeletingChain, nop] + }); + }); +} + +function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && + (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); +} +function addFilter(ctx, fn) { + ctx.filter = combine(ctx.filter, fn); +} +function addReplayFilter(ctx, factory, isLimitFilter) { + var curr = ctx.replayFilter; + ctx.replayFilter = curr ? () => combine(curr(), factory()) : factory; + ctx.justLimit = isLimitFilter && !curr; +} +function addMatchFilter(ctx, fn) { + ctx.isMatch = combine(ctx.isMatch, fn); +} +function getIndexOrStore(ctx, coreSchema) { + if (ctx.isPrimKey) + return coreSchema.primaryKey; + const index = coreSchema.getIndexByKeyPath(ctx.index); + if (!index) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); + return index; +} +function openCursor(ctx, coreTable, trans) { + const index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans, + values: !ctx.keysOnly, + reverse: ctx.dir === 'prev', + unique: !!ctx.unique, + query: { + index, + range: ctx.range + } + }); +} +function iter(ctx, fn, coreTrans, coreTable) { + const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); + } + else { + const set = {}; + const union = (item, cursor, advance) => { + if (!filter || filter(cursor, advance, result => cursor.stop(result), err => cursor.fail(err))) { + 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); + } + } + }; + return Promise.all([ + ctx.or._iterate(union, coreTrans), + iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) + ]); + } +} +function iterate(cursorPromise, filter, fn, valueMapper) { + var mappedFn = valueMapper ? (x, c, a) => fn(valueMapper(x), c, a) : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(cursor => { + if (cursor) { + return cursor.start(() => { + var c = () => cursor.continue(); + if (!filter || filter(cursor, advancer => c = advancer, val => { cursor.stop(val); c = nop; }, e => { cursor.fail(e); c = nop; })) + wrappedFn(cursor.value, cursor, advancer => c = advancer); + c(); + }); + } + }); +} + +class Collection { + _read(fn, cb) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readonly', fn).then(cb); + } + _write(fn) { + var ctx = this._ctx; + return ctx.error ? + ctx.table._trans(null, rejection.bind(null, ctx.error)) : + ctx.table._trans('readwrite', fn, "locked"); + } + _addAlgorithm(fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + } + _iterate(fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + } + clone(props) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props) + extend(ctx, props); + rv._ctx = ctx; + return rv; + } + raw() { + this._ctx.valueMapper = null; + return this; + } + each(fn) { + var ctx = this._ctx; + return this._read(trans => iter(ctx, fn, trans, ctx.table.core)); + } + count(cb) { + return this._read(trans => { + const ctx = this._ctx; + const coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(count => Math.min(count, ctx.limit)); + } + else { + var count = 0; + return iter(ctx, () => { ++count; return false; }, trans, coreTable) + .then(() => count); + } + }).then(cb); + } + sortBy(keyPath, cb) { + const 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(cb) { + return this._read(trans => { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + const { valueMapper } = ctx; + const index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans, + limit: ctx.limit, + values: true, + query: { + index, + range: ctx.range + } + }).then(({ result }) => valueMapper ? result.map(valueMapper) : result); + } + else { + const a = []; + return iter(ctx, item => a.push(item), trans, ctx.table.core).then(() => a); + } + }, cb); + } + offset(offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, () => { + var offsetLeft = offset; + return (cursor, advance) => { + if (offsetLeft === 0) + return true; + if (offsetLeft === 1) { + --offsetLeft; + return false; + } + advance(() => { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } + else { + addReplayFilter(ctx, () => { + var offsetLeft = offset; + return () => (--offsetLeft < 0); + }); + } + return this; + } + limit(numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, () => { + var rowsLeft = numRows; + return function (cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + } + until(filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function (cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } + else { + return true; + } + }); + return this; + } + first(cb) { + return this.limit(1).toArray(function (a) { return a[0]; }).then(cb); + } + last(cb) { + return this.reverse().first(cb); + } + filter(filterFunction) { + addFilter(this._ctx, function (cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + } + and(filter) { + return this.filter(filter); + } + or(indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + } + reverse() { + this._ctx.dir = (this._ctx.dir === "prev" ? "next" : "prev"); + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + } + desc() { + return this.reverse(); + } + eachKey(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.key, cursor); }); + } + eachUniqueKey(cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + } + eachPrimaryKey(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); }); + } + keys(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(cb) { + var ctx = this._ctx; + if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(trans => { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans, + values: false, + limit: ctx.limit, + query: { + index, + range: ctx.range + } + }); + }).then(({ result }) => result).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(cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + } + firstKey(cb) { + return this.limit(1).keys(function (a) { return a[0]; }).then(cb); + } + lastKey(cb) { + return this.reverse().firstKey(cb); + } + distinct() { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; + var set = {}; + addFilter(this._ctx, function (cursor) { + var strKey = cursor.primaryKey.toString(); + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + } + modify(changes) { + var ctx = this._ctx; + return this._write(trans => { + var modifyer; + if (typeof changes === 'function') { + modifyer = changes; + } + else { + 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); + anythingModified = true; + } + } + return anythingModified; + }; + } + const coreTable = ctx.table.core; + const { outbound, extractKey } = coreTable.schema.primaryKey; + const limit = this.db._options.modifyChunkSize || 200; + const totalFailures = []; + let successCount = 0; + const failedKeys = []; + const applyMutateResult = (expectedCount, res) => { + const { failures, numFailures } = res; + successCount += expectedCount - numFailures; + for (let pos of keys(failures)) { + totalFailures.push(failures[pos]); + } + }; + return this.clone().primaryKeys().then(keys => { + const nextChunk = (offset) => { + const count = Math.min(limit, keys.length - offset); + return coreTable.getMany({ + trans, + keys: keys.slice(offset, offset + count), + cache: "immutable" + }).then(values => { + const addValues = []; + const putValues = []; + const putKeys = outbound ? [] : null; + const deleteKeys = []; + for (let i = 0; i < count; ++i) { + const origValue = values[i]; + const ctx = { + value: deepClone(origValue), + primKey: keys[offset + i] + }; + if (modifyer.call(ctx, ctx.value, ctx) !== false) { + if (ctx.value == null) { + deleteKeys.push(keys[offset + i]); + } + else if (!outbound && cmp(extractKey(origValue), extractKey(ctx.value)) !== 0) { + deleteKeys.push(keys[offset + i]); + addValues.push(ctx.value); + } + else { + putValues.push(ctx.value); + if (outbound) + putKeys.push(keys[offset + i]); + } + } + } + const criteria = isPlainKeyRange(ctx) && + ctx.limit === Infinity && + (typeof changes !== 'function' || changes === deleteCallback) && { + index: ctx.index, + range: ctx.range + }; + return Promise.resolve(addValues.length > 0 && + coreTable.mutate({ trans, type: 'add', values: addValues }) + .then(res => { + for (let pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(() => (putValues.length > 0 || (criteria && typeof changes === 'object')) && + coreTable.mutate({ + trans, + type: 'put', + keys: putKeys, + values: putValues, + criteria, + changeSpec: typeof changes !== 'function' + && changes + }).then(res => applyMutateResult(putValues.length, res))).then(() => (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) && + coreTable.mutate({ + trans, + type: 'delete', + keys: deleteKeys, + criteria + }).then(res => applyMutateResult(deleteKeys.length, res))).then(() => { + return keys.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(() => { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys.length; + }); + }); + }); + } + delete() { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && + ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === 3 )) + { + return this._write(trans => { + const { primaryKey } = ctx.table.core.schema; + const coreRange = range; + return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(count => { + return ctx.table.core.mutate({ trans, type: 'deleteRange', range: coreRange }) + .then(({ failures, lastResult, results, numFailures }) => { + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(pos => failures[pos]), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(deleteCallback); + } +} +const deleteCallback = (value, ctx) => ctx.value = null; + +function createCollectionConstructor(db) { + return makeClassConstructor(Collection.prototype, function Collection(whereClause, keyRangeGenerator) { + this.db = db; + let keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } + catch (ex) { + error = ex; + } + const whereCtx = whereClause._ctx; + const table = whereCtx.table; + const readingHook = table.hook.reading.fire; + 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: readingHook !== mirror ? readingHook : null + }; + }); +} + +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 fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? + new collectionOrWhereClause.Collection(collectionOrWhereClause) : + collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; +} +function emptyCollection(whereClause) { + return new whereClause.Collection(whereClause, () => rangeEqual("")).limit(0); +} +function upperFactory(dir) { + return dir === "next" ? + (s) => s.toUpperCase() : + (s) => s.toLowerCase(); +} +function lowerFactory(dir) { + return dir === "next" ? + (s) => s.toLowerCase() : + (s) => 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(s => 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 whereClause.Collection(whereClause, () => createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix)); + c._ondirectionchange = function (direction) { + 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; +} +function createRange(lower, upper, lowerOpen, upperOpen) { + return { + type: 2 , + lower, + upper, + lowerOpen, + upperOpen + }; +} +function rangeEqual(value) { + return { + type: 1 , + lower: value, + upper: value + }; +} + +class WhereClause { + get Collection() { + return this._ctx.table.db.Collection; + } + between(lower, upper, includeLower, includeUpper) { + includeLower = includeLower !== false; + includeUpper = includeUpper === true; + try { + if ((this._cmp(lower, upper) > 0) || + (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper))) + return emptyCollection(this); + return new this.Collection(this, () => createRange(lower, upper, !includeLower, !includeUpper)); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + } + equals(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => rangeEqual(value)); + } + above(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(value, undefined, true)); + } + aboveOrEqual(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(value, undefined, false)); + } + below(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(undefined, value, false, true)); + } + belowOrEqual(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, () => createRange(undefined, value)); + } + startsWith(str) { + if (typeof str !== 'string') + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + } + startsWithIgnoreCase(str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString); + } + equalsIgnoreCase(str) { + return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], ""); + } + anyOfIgnoreCase() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, ""); + } + startsWithAnyOfIgnoreCase() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString); + } + anyOf() { + const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + let compare = this._cmp; + try { + set.sort(compare); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1])); + c._ondirectionchange = direction => { + compare = (direction === "next" ? + this._ascending : + this._descending); + set.sort(compare); + }; + let i = 0; + c._addAlgorithm((cursor, advance, resolve) => { + const key = cursor.key; + while (compare(key, set[i]) > 0) { + ++i; + if (i === set.length) { + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + return true; + } + else { + advance(() => { cursor.continue(set[i]); }); + return false; + } + }); + return c; + } + notEqual(value) { + return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false }); + } + noneOf() { + const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new this.Collection(this); + try { + set.sort(this._ascending); + } + catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + const ranges = set.reduce((res, val) => res ? + res.concat([[res[res.length - 1][1], val]]) : + [[minKey, val]], null); + ranges.push([set[set.length - 1], this.db._maxKey]); + return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false }); + } + inAnyRange(ranges, options) { + const cmp = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; + if (ranges.length === 0) + return emptyCollection(this); + if (!ranges.every(range => 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); + } + const includeLowers = !options || options.includeLowers !== false; + const includeUppers = options && options.includeUppers === true; + function addRange(ranges, newRange) { + let i = 0, l = ranges.length; + for (; i < l; ++i) { + const 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; + } + let sortDirection = ascending; + function rangeSorter(a, b) { return sortDirection(a[0], b[0]); } + let set; + try { + set = ranges.reduce(addRange, []); + set.sort(rangeSorter); + } + catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + let rangePos = 0; + const keyIsBeyondCurrentEntry = includeUppers ? + key => ascending(key, set[rangePos][1]) > 0 : + key => ascending(key, set[rangePos][1]) >= 0; + const keyIsBeforeCurrentEntry = includeLowers ? + key => descending(key, set[rangePos][0]) > 0 : + key => descending(key, set[rangePos][0]) >= 0; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + let checkKey = keyIsBeyondCurrentEntry; + const c = new this.Collection(this, () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers)); + c._ondirectionchange = direction => { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } + else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + c._addAlgorithm((cursor, advance, resolve) => { + var key = cursor.key; + while (checkKey(key)) { + ++rangePos; + if (rangePos === set.length) { + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + return true; + } + else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) { + return false; + } + else { + advance(() => { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + } + startsWithAnyOf() { + const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (!set.every(s => typeof s === 'string')) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) + return emptyCollection(this); + return this.inAnyRange(set.map((str) => [str, str + maxString])); + } +} + +function createWhereClauseConstructor(db) { + return makeClassConstructor(WhereClause.prototype, function WhereClause(table, index, orCollection) { + this.db = db; + this._ctx = { + table: table, + index: index === ":id" ? null : index, + or: orCollection + }; + this._cmp = this._ascending = cmp; + this._descending = (a, b) => cmp(b, a); + this._max = (a, b) => cmp(a, b) > 0 ? a : b; + this._min = (a, b) => cmp(a, b) < 0 ? a : b; + this._IDBKeyRange = db._deps.IDBKeyRange; + if (!this._IDBKeyRange) + throw new exceptions.MissingAPI(); + }); +} + +function eventRejectHandler(reject) { + return wrap(function (event) { + preventDefault(event); + reject(event.target.error); + return false; + }); +} +function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); +} + +const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated'; +const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1'; +const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + +class Transaction { + _lock() { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + } + _unlock() { + assert(!PSD.global); + 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() { + return this._reculock && PSD.lockOwnerFor !== this; + } + create(idbtrans) { + if (!this.mode) + return this; + const idbdb = this.db.idbdb; + const dbOpenError = this.db._state.dbOpenError; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) + throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + idbtrans = this.idbtrans = idbtrans || + (this.db.core + ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) + : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })); + idbtrans.onerror = wrap(ev => { + preventDefault(ev); + this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(ev => { + preventDefault(ev); + this.active && this._reject(new exceptions.Abort(idbtrans.error)); + this.active = false; + this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(() => { + this.active = false; + this._resolve(); + if ('mutatedParts' in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + return this; + } + _promise(mode, fn, bWriteLock) { + 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 DexiePromise((resolve, reject) => { + this._blockedFuncs.push([() => { + this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, PSD]); + }); + } + else if (bWriteLock) { + return newScope(() => { + var p = new DexiePromise((resolve, reject) => { + this._lock(); + const rv = fn(resolve, reject, this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p.finally(() => this._unlock()); + p._lib = true; + return p; + }); + } + else { + var p = new DexiePromise((resolve, reject) => { + var rv = fn(resolve, reject, this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + } + _root() { + return this.parent ? this.parent._root() : this; + } + waitFor(promiseLike) { + var root = this._root(); + const promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(() => promise); + } + else { + root._waitingFor = promise; + root._waitingQueue = []; + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; + while (root._waitingQueue.length) + (root._waitingQueue.shift())(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + }()); + } + var currentWaitPromise = root._waitingFor; + return new DexiePromise((resolve, reject) => { + promise.then(res => root._waitingQueue.push(wrap(resolve.bind(null, res))), err => root._waitingQueue.push(wrap(reject.bind(null, err)))).finally(() => { + if (root._waitingFor === currentWaitPromise) { + root._waitingFor = null; + } + }); + }); + } + abort() { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + } + table(tableName) { + const memoizedTables = (this._memoizedTables || (this._memoizedTables = {})); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + const tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + const transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + } +} + +function createTransactionConstructor(db) { + return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + this.db = db; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + 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; + this._completion = new DexiePromise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + this._completion.then(() => { + this.active = false; + this.on.complete.fire(); + }, 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); + }); + }); +} + +function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) { + return { + name, + keyPath, + unique, + multi, + auto, + compound, + src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath) + }; +} +function nameFromKeyPath(keyPath) { + return typeof keyPath === 'string' ? + keyPath : + keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : ""; +} + +function createTableSchema(name, primKey, indexes) { + return { + name, + primKey, + indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, index => [index.name, index]) + }; +} + +function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; +} +let getMaxKey = (IdbKeyRange) => { + try { + IdbKeyRange.only([[]]); + getMaxKey = () => [[]]; + return [[]]; + } + catch (e) { + getMaxKey = () => maxString; + return maxString; + } +}; + +function getKeyExtractor(keyPath) { + if (keyPath == null) { + return () => undefined; + } + else if (typeof keyPath === 'string') { + return getSinglePathKeyExtractor(keyPath); + } + else { + return obj => getByKeyPath(obj, keyPath); + } +} +function getSinglePathKeyExtractor(keyPath) { + const split = keyPath.split('.'); + if (split.length === 1) { + return obj => obj[keyPath]; + } + else { + return obj => getByKeyPath(obj, keyPath); + } +} + +function arrayify(arrayLike) { + return [].slice.call(arrayLike); +} +let _id_counter = 0; +function getKeyPathAlias(keyPath) { + return keyPath == null ? + ":id" : + typeof keyPath === 'string' ? + keyPath : + `[${keyPath.join('+')}]`; +} +function createDBCore(db, IdbKeyRange, tmpTrans) { + function extractSchema(db, trans) { + const tables = arrayify(db.objectStoreNames); + return { + schema: { + name: db.name, + tables: tables.map(table => trans.objectStore(table)).map(store => { + const { keyPath, autoIncrement } = store; + const compound = isArray(keyPath); + const outbound = keyPath == null; + const indexByKeyPath = {}; + const result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound, + compound, + keyPath, + autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(indexName => store.index(indexName)) + .map(index => { + const { name, unique, multiEntry, keyPath } = index; + const compound = isArray(keyPath); + const result = { + name, + compound, + keyPath, + unique, + multiEntry, + extractKey: getKeyExtractor(keyPath) + }; + indexByKeyPath[getKeyPathAlias(keyPath)] = result; + return result; + }), + getIndexByKeyPath: (keyPath) => indexByKeyPath[getKeyPathAlias(keyPath)] + }; + indexByKeyPath[":id"] = result.primaryKey; + if (keyPath != null) { + indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; + } + return result; + }) + }, + hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) && + !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) + }; + } + function makeIDBKeyRange(range) { + if (range.type === 3 ) + return null; + if (range.type === 4 ) + throw new Error("Cannot convert never type to IDBKeyRange"); + const { lower, upper, lowerOpen, upperOpen } = range; + const idbRange = lower === undefined ? + upper === undefined ? + null : + IdbKeyRange.upperBound(upper, !!upperOpen) : + upper === undefined ? + IdbKeyRange.lowerBound(lower, !!lowerOpen) : + IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); + return idbRange; + } + function createDbCoreTable(tableSchema) { + const tableName = tableSchema.name; + function mutate({ trans, type, keys, values, range }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const store = trans.objectStore(tableName); + const outbound = store.keyPath == null; + const isAddOrPut = type === "put" || type === "add"; + if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange') + throw new Error("Invalid operation type: " + type); + const { length } = keys || values || { length: 1 }; + if (keys && values && keys.length !== values.length) { + throw new Error("Given keys array must have same length as given values array."); + } + if (length === 0) + return resolve({ numFailures: 0, failures: {}, results: [], lastResult: undefined }); + let req; + const reqs = []; + const failures = []; + let numFailures = 0; + const errorHandler = event => { + ++numFailures; + preventDefault(event); + }; + if (type === 'deleteRange') { + if (range.type === 4 ) + return resolve({ numFailures, failures, results: [], lastResult: undefined }); + if (range.type === 3 ) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } + else { + const [args1, args2] = isAddOrPut ? + outbound ? + [values, keys] : + [values, null] : + [keys, null]; + if (isAddOrPut) { + for (let i = 0; i < length; ++i) { + reqs.push(req = (args2 && args2[i] !== undefined ? + store[type](args1[i], args2[i]) : + store[type](args1[i]))); + req.onerror = errorHandler; + } + } + else { + for (let i = 0; i < length; ++i) { + reqs.push(req = store[type](args1[i])); + req.onerror = errorHandler; + } + } + } + const done = event => { + const lastResult = event.target.result; + reqs.forEach((req, i) => req.error != null && (failures[i] = req.error)); + resolve({ + numFailures, + failures, + results: type === "delete" ? keys : reqs.map(req => req.result), + lastResult + }); + }; + req.onerror = event => { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor({ trans, values, query, reverse, unique }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const { index, range } = query; + const store = trans.objectStore(tableName); + const source = index.isPrimaryKey ? + store : + store.index(index.name); + const direction = reverse ? + unique ? + "prevunique" : + "prev" : + unique ? + "nextunique" : + "next"; + const req = values || !('openKeyCursor' in source) ? + source.openCursor(makeIDBKeyRange(range), direction) : + source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(ev => { + const cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + const _cursorContinue = cursor.continue.bind(cursor); + let _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + const _cursorAdvance = cursor.advance.bind(cursor); + const doThrowCursorIsNotStarted = () => { throw new Error("Cursor not started"); }; + const doThrowCursorIsStopped = () => { throw new Error("Cursor not stopped"); }; + cursor.trans = trans; + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; + cursor.fail = wrap(reject); + cursor.next = function () { + let gotOne = 1; + return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this); + }; + cursor.start = (callback) => { + const iterationPromise = new Promise((resolveIteration, rejectIteration) => { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = value => { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + const guardedCallback = () => { + if (req.result) { + try { + callback(); + } + catch (err) { + cursor.fail(err); + } + } + else { + cursor.done = true; + cursor.start = () => { throw new Error("Cursor behind last entry"); }; + cursor.stop(); + } + }; + req.onsuccess = wrap(ev => { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll) { + return (request) => { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const { trans, values, limit, query } = request; + const nonInfinitLimit = limit === Infinity ? undefined : limit; + const { index, range } = query; + const store = trans.objectStore(tableName); + const source = index.isPrimaryKey ? store : store.index(index.name); + const idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasGetAll) { + const req = values ? + source.getAll(idbKeyRange, nonInfinitLimit) : + source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = event => resolve({ result: event.target.result }); + req.onerror = eventRejectHandler(reject); + } + else { + let count = 0; + const req = values || !('openKeyCursor' in source) ? + source.openCursor(idbKeyRange) : + source.openKeyCursor(idbKeyRange); + const result = []; + req.onsuccess = event => { + const cursor = req.result; + if (!cursor) + return resolve({ result }); + result.push(values ? cursor.value : cursor.primaryKey); + if (++count === limit) + return resolve({ result }); + cursor.continue(); + }; + req.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate, + getMany({ trans, keys }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const store = trans.objectStore(tableName); + const length = keys.length; + const result = new Array(length); + let keyCount = 0; + let callbackCount = 0; + let req; + const successHandler = event => { + const req = event.target; + if ((result[req._pos] = req.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + const errorHandler = eventRejectHandler(reject); + for (let i = 0; i < length; ++i) { + const key = keys[i]; + if (key != null) { + req = store.get(keys[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get({ trans, key }) { + return new Promise((resolve, reject) => { + resolve = wrap(resolve); + const store = trans.objectStore(tableName); + const req = store.get(key); + req.onsuccess = event => resolve(event.target.result); + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll), + openCursor, + count({ query, trans }) { + const { index, range } = query; + return new Promise((resolve, reject) => { + const store = trans.objectStore(tableName); + const source = index.isPrimaryKey ? store : store.index(index.name); + const idbKeyRange = makeIDBKeyRange(range); + const req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(ev => resolve(ev.target.result)); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + const { schema, hasGetAll } = extractSchema(db, tmpTrans); + const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema)); + const tableMap = {}; + tables.forEach(table => tableMap[table.name] = table); + return { + stack: "dbcore", + transaction: db.transaction.bind(db), + table(name) { + const result = tableMap[name]; + if (!result) + throw new Error(`Table '${name}' not found`); + return tableMap[name]; + }, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema + }; +} + +function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce((down, { create }) => ({ ...down, ...create(down) }), stackImpl); +} +function createMiddlewareStacks(middlewares, idbdb, { IDBKeyRange, indexedDB }, tmpTrans) { + const dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore + }; +} +function generateMiddlewareStacks(db, tmpTrans) { + const idbdb = tmpTrans.db; + const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans); + db.core = stacks.dbcore; + db.tables.forEach(table => { + const tableName = table.name; + if (db.core.schema.tables.some(tbl => tbl.name === tableName)) { + table.core = db.core.table(tableName); + if (db[tableName] instanceof db.Table) { + db[tableName].core = table.core; + } + } + }); +} + +function setApiOnPlace(db, objs, tableNames, dbschema) { + tableNames.forEach(tableName => { + const schema = dbschema[tableName]; + objs.forEach(obj => { + const propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || ("value" in propDesc && propDesc.value === undefined)) { + if (obj === db.Transaction.prototype || obj instanceof db.Transaction) { + setProp(obj, tableName, { + get() { return this.table(tableName); }, + set(value) { + defineProperty(this, tableName, { value, writable: true, configurable: true, enumerable: true }); + } + }); + } + else { + obj[tableName] = new db.Table(tableName, schema); + } + } + }); + }); +} +function removeTablesApi(db, objs) { + objs.forEach(obj => { + for (let key in obj) { + if (obj[key] instanceof db.Table) + delete obj[key]; + } + }); +} +function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; +} +function runUpgraders(db, oldVersion, idbUpgradeTrans, reject) { + const globalSchema = db._dbSchema; + const trans = db._createTransaction('readwrite', db._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + const rejectTransaction = trans._reject.bind(trans); + const transless = PSD.transless || PSD; + newScope(() => { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(tableName => { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db, idbUpgradeTrans); + DexiePromise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction); + } + else + updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction); + }); +} +function updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans) { + const queue = []; + const versions = db._versions; + let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans); + let anyContentUpgraderHasRun = false; + const versToRun = versions.filter(v => v._cfg.version >= oldVersion); + versToRun.forEach(version => { + queue.push(() => { + const oldSchema = globalSchema; + const newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans); + globalSchema = db._dbSchema = newSchema; + const diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(tuple => { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(change => { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } + else { + const store = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(idx => addIndex(store, idx)); + change.change.forEach(idx => { + store.deleteIndex(idx.name); + addIndex(store, idx); + }); + change.del.forEach(idxName => store.deleteIndex(idxName)); + } + }); + const contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db, idbUpgradeTrans); + trans._memoizedTables = {}; + anyContentUpgraderHasRun = true; + let upgradeSchema = shallowClone(newSchema); + diff.del.forEach(table => { + upgradeSchema[table] = oldSchema[table]; + }); + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema); + trans.schema = upgradeSchema; + const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync) { + incrementExpectedAwaits(); + } + let returnValue; + const promiseFollowed = DexiePromise.follow(() => { + returnValue = contentUpgrade(trans); + if (returnValue) { + if (contentUpgradeIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + } + }); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue) : promiseFollowed.then(() => returnValue)); + } + }); + queue.push(idbtrans => { + if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { + const newSchema = version._cfg.dbschema; + deleteRemovedTables(newSchema, idbtrans); + } + removeTablesApi(db, [db.Transaction.prototype]); + setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema); + trans.schema = db._dbSchema; + }); + }); + function runQueue() { + return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : + DexiePromise.resolve(); + } + return runQueue().then(() => { + createMissingTables(globalSchema, idbUpgradeTrans); + }); +} +function getSchemaDiff(oldSchema, newSchema) { + const diff = { + del: [], + add: [], + change: [] + }; + let table; + for (table in oldSchema) { + if (!newSchema[table]) + diff.del.push(table); + } + for (table in newSchema) { + const oldDef = oldSchema[table], newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } + else { + const change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if (( + '' + (oldDef.primKey.keyPath || '')) !== ('' + (newDef.primKey.keyPath || '')) || + (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) + { + change.recreate = true; + diff.change.push(change); + } + else { + const oldIndexes = oldDef.idxByName; + const newIndexes = newDef.idxByName; + let idxName; + for (idxName in oldIndexes) { + if (!newIndexes[idxName]) + change.del.push(idxName); + } + for (idxName in newIndexes) { + const 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) { + const store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? + { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : + { autoIncrement: primKey.auto }); + indexes.forEach(idx => addIndex(store, idx)); + return store; +} +function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(tableName => { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); +} +function deleteRemovedTables(newSchema, idbtrans) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName => newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName)); +} +function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi }); +} +function buildGlobalSchema(db, idbdb, tmpTrans) { + const globalSchema = {}; + const dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(storeName => { + const store = tmpTrans.objectStore(storeName); + let keyPath = store.keyPath; + const primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + const indexes = []; + for (let j = 0; j < store.indexNames.length; ++j) { + const idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); + indexes.push(index); + } + globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); + }); + return globalSchema; +} +function readGlobalSchema(db, idbdb, tmpTrans) { + db.verno = idbdb.version / 10; + const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans); + db._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema); +} +function verifyInstalledSchema(db, tmpTrans) { + const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans); + const diff = getSchemaDiff(installedSchema, db._dbSchema); + return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length)); +} +function adjustToExistingIndexNames(db, schema, idbtrans) { + const storeNames = idbtrans.db.objectStoreNames; + for (let i = 0; i < storeNames.length; ++i) { + const storeName = storeNames[i]; + const store = idbtrans.objectStore(storeName); + db._hasGetAll = 'getAll' in store; + for (let j = 0; j < store.indexNames.length; ++j) { + const indexName = store.indexNames[j]; + const keyPath = store.index(indexName).keyPath; + const dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]"; + if (schema[storeName]) { + const indexSpec = schema[storeName].idxByName[dexieName]; + if (indexSpec) { + indexSpec.name = indexName; + delete schema[storeName].idxByName[dexieName]; + schema[storeName].idxByName[indexName] = indexSpec; + } + } + } + } + if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) && + !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && + _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && + [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + db._hasGetAll = false; + } +} +function parseIndexSyntax(primKeyAndIndexes) { + return primKeyAndIndexes.split(',').map((index, indexNum) => { + index = index.trim(); + const name = index.replace(/([&*]|\+\+)/g, ""); + const keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0); + }); +} + +class Version { + _parseStoresSpec(stores, outSchema) { + keys(stores).forEach(tableName => { + if (stores[tableName] !== null) { + var indexes = parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multi-valued"); + indexes.forEach(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"); + }); + outSchema[tableName] = createTableSchema(tableName, primKey, indexes); + } + }); + } + stores(stores) { + const db = this.db; + this._cfg.storesSource = this._cfg.storesSource ? + extend(this._cfg.storesSource, stores) : + stores; + const versions = db._versions; + const storesSpec = {}; + let dbschema = {}; + versions.forEach(version => { + extend(storesSpec, version._cfg.storesSource); + dbschema = (version._cfg.dbschema = {}); + version._parseStoresSpec(storesSpec, dbschema); + }); + db._dbSchema = dbschema; + removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]); + setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + db._storeNames = keys(dbschema); + return this; + } + upgrade(upgradeFunction) { + this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + } +} + +function createVersionConstructor(db) { + return makeClassConstructor(Version.prototype, function Version(versionNumber) { + this.db = db; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); +} + +function getDbNamesTable(indexedDB, IDBKeyRange) { + let dbNamesDB = indexedDB["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB, + IDBKeyRange, + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); +} +function hasDatabasesNative(indexedDB) { + return indexedDB && typeof indexedDB.databases === "function"; +} +function getDatabaseNames({ indexedDB, IDBKeyRange, }) { + return hasDatabasesNative(indexedDB) + ? Promise.resolve(indexedDB.databases()).then((infos) => infos + .map((info) => info.name) + .filter((name) => name !== DBNAMES_DB)) + : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys(); +} +function _onDatabaseCreated({ indexedDB, IDBKeyRange }, name) { + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).put({ name }).catch(nop); +} +function _onDatabaseDeleted({ indexedDB, IDBKeyRange }, name) { + !hasDatabasesNative(indexedDB) && + name !== DBNAMES_DB && + getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop); +} + +function vip(fn) { + return newScope(function () { + PSD.letThrough = true; + return fn(); + }); +} + +function idbReady() { + var isSafari = !navigator.userAgentData && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function (resolve) { + var tryIdb = function () { return indexedDB.databases().finally(resolve); }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function () { return clearInterval(intervalId); }); +} + +function isEmptyRange(node) { + return !("from" in node); +} +const RangeSet = function (fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + const rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } +}; +props(RangeSet.prototype, { + add(rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey(key) { + addRange(this, key, key); + return this; + }, + addKeys(keys) { + keys.forEach(key => addRange(this, key, key)); + return this; + }, + [iteratorSymbol]() { + return getRangeSetIterator(this); + } +}); +function addRange(target, from, to) { + const diff = cmp(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from, to, d: 1 }); + const left = target.l; + const right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from, to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from, to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + const rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges(target, left); + } + if (right && rightWasCutOff) { + mergeRanges(target, right); + } +} +function mergeRanges(target, newSet) { + function _addRangeSet(target, { from, to, l, r }) { + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); +} +function rangesOverlap(rangeSet1, rangeSet2) { + const i1 = getRangeSetIterator(rangeSet2); + let nextResult1 = i1.next(); + if (nextResult1.done) + return false; + let a = nextResult1.value; + const i2 = getRangeSetIterator(rangeSet1); + let nextResult2 = i2.next(a.from); + let b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) + : (b = (nextResult2 = i2.next(a.from)).value); + } + return false; +} +function getRangeSetIterator(node) { + let state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next(key) { + const keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; +} +function rebalance(target) { + var _a, _b; + const diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + const r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + const l = r === "r" ? "l" : "r"; + const rootClone = { ...target }; + const oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); +} +function computeDepth({ r, l }) { + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; +} + +function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(part => { + if (target[part]) + mergeRanges(target[part], newSet[part]); + else + target[part] = cloneSimpleObjectTree(newSet[part]); + }); + return target; +} + +function obsSetsOverlap(os1, os2) { + return Object.keys(os1).some((key) => os2[key] && rangesOverlap(os2[key], os1[key])); +} + +const cache = {}; + +let unsignaledParts = {}; +let isTaskEnqueued = false; +function signalSubscribersLazily(part) { + extendObservabilitySet(unsignaledParts, part); + if (!isTaskEnqueued) { + isTaskEnqueued = true; + setTimeout(() => { + isTaskEnqueued = false; + const parts = unsignaledParts; + unsignaledParts = {}; + signalSubscribersNow(parts); + }, 0); + } +} +function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries = false) { + const queriesToSignal = new Set(); + for (const key in updatedParts) { + const parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); + if (parts) { + const [, dbName, tableName] = parts; + const tblCache = cache[`idb://${dbName}/${tableName}`]; + if (tblCache) + signalTableSubscribersNow(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); + } + } + queriesToSignal.forEach((requery) => requery()); +} +function signalTableSubscribersNow(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { + const updatedEntryLists = deleteAffectedCacheEntries && []; + for (const [indexName, entries] of Object.entries(tblCache.queries.query)) { + const filteredEntries = deleteAffectedCacheEntries && []; + for (const entry of entries) { + if (entry.obsSet && obsSetsOverlap(updatedParts, entry.obsSet)) { + entry.subscribers.forEach((requery) => outQueriesToSignal.add(requery)); + } + else if (deleteAffectedCacheEntries) { + filteredEntries.push(entry); + } + } + if (deleteAffectedCacheEntries) + updatedEntryLists.push([indexName, filteredEntries]); + } + if (deleteAffectedCacheEntries) { + for (const [indexName, filteredEntries] of updatedEntryLists) { + tblCache.queries.query[indexName] = filteredEntries; + } + } +} + +function dexieOpen(db) { + const state = db._state; + const { indexedDB } = db._deps; + if (state.isBeingOpened || db.idbdb) + return state.dbReadyPromise.then(() => state.dbOpenError ? + rejection(state.dbOpenError) : + db); + debug && (state.openCanceller._stackHolder = getErrorWithStack()); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + const openCanceller = state.openCanceller; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed('db.open() was cancelled'); + } + let resolveDbReady = state.dbReadyResolve, + upgradeTransaction = null, wasCreated = false; + return DexiePromise.race([openCanceller, (typeof navigator === 'undefined' ? DexiePromise.resolve() : idbReady()).then(() => new DexiePromise((resolve, reject) => { + throwIfCancelled(); + if (!indexedDB) + throw new exceptions.MissingAPI(); + const dbName = db.name; + const req = state.autoSchema ? + indexedDB.open(dbName) : + indexedDB.open(dbName, Math.round(db.verno * 10)); + if (!req) + throw new exceptions.MissingAPI(); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db._fireOnBlocked); + req.onupgradeneeded = wrap(e => { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + const delreq = indexedDB.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(() => { + reject(new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`)); + }); + } + else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + wasCreated = oldVer < 1; + db.idbdb = req.result; + runUpgraders(db, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(() => { + upgradeTransaction = null; + const idbdb = db.idbdb = req.result; + const objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly'); + if (state.autoSchema) + readGlobalSchema(db, idbdb, tmpTrans); + else { + adjustToExistingIndexNames(db, db._dbSchema, tmpTrans); + if (!verifyInstalledSchema(db, tmpTrans)) { + console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`); + } + } + generateMiddlewareStacks(db, tmpTrans); + } + catch (e) { + } + connections.push(db); + idbdb.onversionchange = wrap(ev => { + state.vcFired = true; + db.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(ev => { + db.on("close").fire(ev); + }); + if (wasCreated) + _onDatabaseCreated(db._deps, dbName); + resolve(); + }, reject); + }))]).then(() => { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(() => db.on.ready.fire(db.vip))).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + let remainders = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(() => remainders(db.vip))).then(fireRemainders); + } + }); + }).finally(() => { + if (state.openCanceller === openCanceller) { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + } + }).catch(err => { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } + catch (_a) { } + if (openCanceller === state.openCanceller) { + db._close(); + } + return rejection(err); + }).finally(() => { + state.openComplete = true; + resolveDbReady(); + }).then(() => { + if (wasCreated) { + const everything = {}; + db.tables.forEach(table => { + table.schema.indexes.forEach(idx => { + if (idx.name) + everything[`idb://${db.name}/${table.name}/${idx.name}`] = new RangeSet(-Infinity, [[[]]]); + }); + everything[`idb://${db.name}/${table.name}/`] = everything[`idb://${db.name}/${table.name}/:dels`] = new RangeSet(-Infinity, [[[]]]); + }); + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything); + signalSubscribersNow(everything, true); + } + return db; + }); +} + +function awaitIterator(iterator) { + var callNext = result => iterator.next(result), doThrow = error => iterator.throw(error), onSuccess = step(callNext), onError = step(doThrow); + function step(getNext) { + return (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)(); +} + +function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + scopeFunc = args.pop(); + var tables = flatten(args); + return [mode, tables, scopeFunc]; +} +function enterTransactionScope(db, mode, storeNames, parentTransaction, scopeFunc) { + return DexiePromise.resolve().then(() => { + const transless = PSD.transless || PSD; + const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction); + trans.explicit = true; + const zoneProps = { + trans: trans, + transless: transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } + else { + try { + trans.create(); + db._state.PR1398_maxLoop = 3; + } + catch (ex) { + if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) { + console.warn('Dexie: Need to reopen db'); + db._close(); + return db.open().then(() => enterTransactionScope(db, mode, storeNames, null, scopeFunc)); + } + return rejection(ex); + } + } + const scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + let returnValue; + const promiseFollowed = DexiePromise.follow(() => { + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (scopeFuncIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } + else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') { + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === 'function' ? + DexiePromise.resolve(returnValue).then(x => trans.active ? + x + : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))) + : promiseFollowed.then(() => returnValue)).then(x => { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(() => x); + }).catch(e => { + trans._reject(e); + return rejection(e); + }); + }); +} + +function pad(a, value, count) { + const result = isArray(a) ? a.slice() : [a]; + for (let i = 0; i < count; ++i) + result.push(value); + return result; +} +function createVirtualIndexMiddleware(down) { + return { + ...down, + table(tableName) { + const table = down.table(tableName); + const { schema } = table; + const indexLookup = {}; + const allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + const keyPathAlias = getKeyPathAlias(keyPath); + const indexList = (indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []); + const keyLength = keyPath == null ? 0 : typeof keyPath === 'string' ? 1 : keyPath.length; + const isVirtual = keyTail > 0; + const virtualIndex = { + ...lowLevelIndex, + name: isVirtual + ? `${keyPathAlias}(virtual-from:${lowLevelIndex.name})` + : lowLevelIndex.name, + lowLevelIndex, + isVirtual, + keyTail, + keyLength, + extractKey: getKeyExtractor(keyPath), + unique: !isVirtual && lowLevelIndex.unique + }; + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + const virtualKeyPath = keyLength === 2 ? + keyPath[0] : + keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort((a, b) => a.keyTail - b.keyTail); + return virtualIndex; + } + const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (const index of schema.indexes) { + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + const result = indexLookup[getKeyPathAlias(keyPath)]; + return result && result[0]; + } + function translateRange(range, keyTail) { + return { + type: range.type === 1 ? + 2 : + range.type, + lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), + lowerOpen: true, + upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), + upperOpen: true + }; + } + function translateRequest(req) { + const index = req.query.index; + return index.isVirtual ? { + ...req, + query: { + index: index.lowLevelIndex, + range: translateRange(req.query.range, index.keyTail) + } + } : req; + } + const result = { + ...table, + schema: { + ...schema, + primaryKey, + indexes: allVirtualIndexes, + getIndexByKeyPath: findBestIndex + }, + count(req) { + return table.count(translateRequest(req)); + }, + query(req) { + return table.query(translateRequest(req)); + }, + openCursor(req) { + const { keyTail, isVirtual, keyLength } = req.query.index; + if (!isVirtual) + return table.openCursor(req); + function createVirtualCursor(cursor) { + function _continue(key) { + key != null ? + cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : + req.unique ? + cursor.continue(cursor.key.slice(0, keyLength) + .concat(req.reverse + ? down.MIN_KEY + : down.MAX_KEY, keyTail)) : + cursor.continue(); + } + const virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value(key, primaryKey) { + cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey); + } + }, + primaryKey: { + get() { + return cursor.primaryKey; + } + }, + key: { + get() { + const key = cursor.key; + return keyLength === 1 ? + key[0] : + key.slice(0, keyLength); + } + }, + value: { + get() { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)) + .then(cursor => cursor && createVirtualCursor(cursor)); + } + }; + return result; + } + }; +} +const virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware +}; + +function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ''; + keys(a).forEach((prop) => { + if (!hasOwn(b, prop)) { + rv[prfx + prop] = undefined; + } + else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) { + const apTypeName = toStringTag(ap); + const bpTypeName = toStringTag(bp); + if (apTypeName !== bpTypeName) { + rv[prfx + prop] = b[prop]; + } + else if (apTypeName === 'Object') { + getObjectDiff(ap, bp, rv, prfx + prop + '.'); + } + else if (ap !== bp) { + rv[prfx + prop] = b[prop]; + } + } + else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach((prop) => { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; +} + +function getEffectiveKeys(primaryKey, req) { + if (req.type === 'delete') + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); +} + +const hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: (downCore) => ({ + ...downCore, + table(tableName) { + const downTable = downCore.table(tableName); + const { primaryKey } = downTable.schema; + const tableMiddleware = { + ...downTable, + mutate(req) { + const dxTrans = PSD.trans; + const { deleting, creating, updating } = dxTrans.table(tableName).hook; + switch (req.type) { + case 'add': + if (creating.fire === nop) + break; + return dxTrans._promise('readwrite', () => addPutOrDelete(req), true); + case 'put': + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise('readwrite', () => addPutOrDelete(req), true); + case 'delete': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', () => addPutOrDelete(req), true); + case 'deleteRange': + if (deleting.fire === nop) + break; + return dxTrans._promise('readwrite', () => deleteRange(req), true); + } + return downTable.mutate(req); + function addPutOrDelete(req) { + const dxTrans = PSD.trans; + const keys = req.keys || getEffectiveKeys(primaryKey, req); + if (!keys) + throw new Error("Keys missing"); + req = req.type === 'add' || req.type === 'put' ? + { ...req, keys } : + { ...req }; + if (req.type !== 'delete') + req.values = [...req.values]; + if (req.keys) + req.keys = [...req.keys]; + return getExistingValues(downTable, req, keys).then(existingValues => { + const contexts = keys.map((key, i) => { + const existingValue = existingValues[i]; + const ctx = { onerror: null, onsuccess: null }; + if (req.type === 'delete') { + deleting.fire.call(ctx, key, existingValue, dxTrans); + } + else if (req.type === 'add' || existingValue === undefined) { + const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans); + if (key == null && generatedPrimaryKey != null) { + key = generatedPrimaryKey; + req.keys[i] = key; + if (!primaryKey.outbound) { + setByKeyPath(req.values[i], primaryKey.keyPath, key); + } + } + } + else { + const objectDiff = getObjectDiff(existingValue, req.values[i]); + const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans); + if (additionalChanges) { + const requestedValue = req.values[i]; + Object.keys(additionalChanges).forEach(keyPath => { + if (hasOwn(requestedValue, keyPath)) { + requestedValue[keyPath] = additionalChanges[keyPath]; + } + else { + setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]); + } + }); + } + } + return ctx; + }); + return downTable.mutate(req).then(({ failures, results, numFailures, lastResult }) => { + for (let i = 0; i < keys.length; ++i) { + const primKey = results ? results[i] : keys[i]; + const ctx = contexts[i]; + if (primKey == null) { + ctx.onerror && ctx.onerror(failures[i]); + } + else { + ctx.onsuccess && ctx.onsuccess(req.type === 'put' && existingValues[i] ? + req.values[i] : + primKey + ); + } + } + return { failures, results, numFailures, lastResult }; + }).catch(error => { + contexts.forEach(ctx => ctx.onerror && ctx.onerror(error)); + return Promise.reject(error); + }); + }); + } + function deleteRange(req) { + return deleteNextChunk(req.trans, req.range, 10000); + } + function deleteNextChunk(trans, range, limit) { + return downTable.query({ trans, values: false, query: { index: primaryKey, range }, limit }) + .then(({ result }) => { + return addPutOrDelete({ type: 'delete', keys: result, trans }).then(res => { + if (res.numFailures > 0) + return Promise.reject(res.failures[0]); + if (result.length < limit) { + return { failures: [], numFailures: 0, lastResult: undefined }; + } + else { + return deleteNextChunk(trans, { ...range, lower: result[result.length - 1], lowerOpen: true }, limit); + } + }); + }); + } + } + }; + return tableMiddleware; + }, + }) +}; +function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" + ? Promise.resolve([]) + : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: "immutable" }); +} + +function getFromTransactionCache(keys, cache, clone) { + try { + if (!cache) + return null; + if (cache.keys.length < keys.length) + return null; + const result = []; + for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) { + if (cmp(cache.keys[i], keys[j]) !== 0) + continue; + result.push(clone ? deepClone(cache.values[i]) : cache.values[i]); + ++j; + } + return result.length === keys.length ? result : null; + } + catch (_a) { + return null; + } +} +const cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: (core) => { + return { + table: (tableName) => { + const table = core.table(tableName); + return { + ...table, + getMany: (req) => { + if (!req.cache) { + return table.getMany(req); + } + const cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then((res) => { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res, + }; + return res; + }); + }, + mutate: (req) => { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + }, + }; + }, + }; + }, +}; + +function isCachableContext(ctx, table) { + return (ctx.trans.mode === 'readonly' && + !!ctx.subscr && + !ctx.trans.explicit && + ctx.trans.db._options.cache !== 'disabled' && + !table.schema.primaryKey.outbound); +} + +function isCachableRequest(type, req) { + switch (type) { + case 'query': + return req.values && !req.unique; + case 'get': + return false; + case 'getMany': + return false; + case 'count': + return false; + case 'openCursor': + return false; + } +} + +const observabilityMiddleware = { + stack: "dbcore", + level: 0, + name: "Observability", + create: (core) => { + const dbName = core.schema.name; + const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY); + return { + ...core, + transaction: (stores, mode, options) => { + if (PSD.subscr && mode !== 'readonly') { + throw new exceptions.ReadOnly(`Readwrite transaction in liveQuery context. Querier source: ${PSD.querier}`); + } + return core.transaction(stores, mode, options); + }, + table: (tableName) => { + const table = core.table(tableName); + const { schema } = table; + const { primaryKey } = schema; + const { extractKey, outbound } = primaryKey; + const tableClone = { + ...table, + mutate: (req) => { + const trans = req.trans; + const mutatedParts = req.mutatedParts || (req.mutatedParts = {}); + const getRangeSet = (indexName) => { + const part = `idb://${dbName}/${tableName}/${indexName}`; + return (mutatedParts[part] || + (mutatedParts[part] = new RangeSet())); + }; + const pkRangeSet = getRangeSet(""); + const delsRangeSet = getRangeSet(":dels"); + const { type } = req; + let [keys, newObjs] = req.type === "deleteRange" + ? [req.range] + : req.type === "delete" + ? [req.keys] + : req.values.length < 50 + ? [getEffectiveKeys(primaryKey, req).filter(id => id), req.values] + : []; + const oldCache = req.trans["_cache"]; + if (isArray(keys)) { + pkRangeSet.addKeys(keys); + const oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null; + if (!oldObjs && type !== "add") { + delsRangeSet.addKeys(keys); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } + else if (keys) { + const range = { from: keys.lower, to: keys.upper }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } + else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE)); + } + return table.mutate(req).then((res) => { + if (keys && (req.type === 'add' || req.type === 'put')) { + pkRangeSet.addKeys(res.results); + } + trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); + return res; + }); + }, + }; + const getRange = ({ query: { index, range }, }) => { + var _a, _b; + return [ + index, + new RangeSet((_a = range.lower) !== null && _a !== void 0 ? _a : core.MIN_KEY, (_b = range.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY), + ]; + }; + const readSubscribers = { + get: (req) => [primaryKey, new RangeSet(req.key)], + getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)], + count: getRange, + query: getRange, + openCursor: getRange, + }; + keys(readSubscribers).forEach(method => { + tableClone[method] = function (req) { + const { subscr } = PSD; + const isLiveQuery = !!subscr; + let cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); + const obsSet = cachable + ? req.obsSet = {} + : subscr; + if (isLiveQuery) { + const getRangeSet = (indexName) => { + const part = `idb://${dbName}/${tableName}/${indexName}`; + return (obsSet[part] || + (obsSet[part] = new RangeSet())); + }; + const pkRangeSet = getRangeSet(""); + const delsRangeSet = getRangeSet(":dels"); + const [queriedIndex, queriedRanges] = readSubscribers[method](req); + getRangeSet(queriedIndex.name || "").add(queriedRanges); + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet.add(FULL_RANGE); + } + else { + const keysPromise = method === "query" && + outbound && + req.values && + table.query({ + ...req, + values: false, + }); + return table[method].apply(this, arguments).then((res) => { + if (method === "query") { + if (outbound && req.values) { + return keysPromise.then(({ result: resultingKeys }) => { + pkRangeSet.addKeys(resultingKeys); + return res; + }); + } + const pKeys = req.values + ? res.result.map(extractKey) + : res.result; + if (req.values) { + pkRangeSet.addKeys(pKeys); + } + else { + delsRangeSet.addKeys(pKeys); + } + } + else if (method === "openCursor") { + const cursor = res; + const wantValues = req.values; + return (cursor && + Object.create(cursor, { + key: { + get() { + delsRangeSet.addKey(cursor.primaryKey); + return cursor.key; + }, + }, + primaryKey: { + get() { + const pkey = cursor.primaryKey; + delsRangeSet.addKey(pkey); + return pkey; + }, + }, + value: { + get() { + wantValues && pkRangeSet.addKey(cursor.primaryKey); + return cursor.value; + }, + }, + })); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + }, + }; + }, +}; +function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + const rangeSet = getRangeSet(ix.name || ""); + function extractKey(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + const addKeyOrKeys = (key) => ix.multiEntry && isArray(key) + ? key.forEach(key => rangeSet.addKey(key)) + : rangeSet.addKey(key); + (oldObjs || newObjs).forEach((_, i) => { + const oldKey = oldObjs && extractKey(oldObjs[i]); + const newKey = newObjs && extractKey(newObjs[i]); + if (cmp(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); +} + +function isAboveLower(key, range) { + return range.lower === undefined + ? true + : range.lowerOpen + ? cmp(key, range.lower) > 0 + : cmp(key, range.lower) >= 0; +} +function isBelowUpper(key, range) { + return range.upper === undefined + ? true + : range.upperOpen + ? cmp(key, range.upper) < 0 + : cmp(key, range.upper) <= 0; +} +function isWithinRange(key, range) { + return isAboveLower(key, range) && isBelowUpper(key, range); +} + +function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { + if (!ops || ops.length === 0) + return result; + const index = req.query.index; + const primaryKey = table.schema.primaryKey; + const extractPrimKey = primaryKey.extractKey; + const extractIndex = index.extractKey; + const extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; + let finalResult = ops.reduce((result, op) => { + let modifedResult = result; + const includedValues = op.type === 'add' || op.type === 'put' + ? op.values.filter((v) => isWithinRange(extractIndex(v), req.query.range)).map(v => { + v = deepClone(v); + if (immutable) + Object.freeze(v); + return v; + }) + : []; + switch (op.type) { + case 'add': + modifedResult = result.concat(req.values + ? includedValues + : includedValues.map((v) => extractPrimKey(v))); + break; + case 'put': + const keySet = new RangeSet().addKeys(op.values.map((v) => extractPrimKey(v))); + modifedResult = result + .filter((item) => { + const key = req.values ? extractPrimKey(item) : item; + return !rangesOverlap(new RangeSet(key), keySet); + }) + .concat(req.values + ? includedValues + : includedValues.map((v) => extractPrimKey(v))); + break; + case 'delete': + const keysToDelete = new RangeSet().addKeys(op.keys); + modifedResult = result.filter((item) => { + const key = req.values ? extractPrimKey(item) : item; + return !rangesOverlap(new RangeSet(key), keysToDelete); + }); + break; + case 'deleteRange': + const range = op.range; + modifedResult = result.filter((item) => !isWithinRange(extractPrimKey(item), range)); + break; + } + return modifedResult; + }, result); + if (finalResult === result) + return result; + finalResult.sort((a, b) => cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) || + cmp(extractPrimKey(a), extractPrimKey(b))); + if (req.limit && req.limit < Infinity) { + if (finalResult.length > req.limit) { + finalResult.length = req.limit; + } + else if (result.length === req.limit && finalResult.length < req.limit) { + cacheEntry.dirty = true; + } + } + return immutable ? Object.freeze(finalResult) : finalResult; +} + +function areRangesEqual(r1, r2) { + return (cmp(r1.lower, r2.lower) === 0 && + cmp(r1.upper, r2.upper) === 0 && + !!r1.lowerOpen === !!r2.lowerOpen && + !!r1.upperOpen === !!r2.upperOpen); +} + +function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { + if (lower1 === undefined) + return lower2 !== undefined ? -1 : 0; + if (lower2 === undefined) + return 1; + const c = cmp(lower1, lower2); + if (c === 0) { + if (lowerOpen1 && lowerOpen2) + return 0; + if (lowerOpen1) + return 1; + if (lowerOpen2) + return -1; + } + return c; +} +function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { + if (upper1 === undefined) + return upper2 !== undefined ? 1 : 0; + if (upper2 === undefined) + return -1; + const c = cmp(upper1, upper2); + if (c === 0) { + if (upperOpen1 && upperOpen2) + return 0; + if (upperOpen1) + return -1; + if (upperOpen2) + return 1; + } + return c; +} +function isSuperRange(r1, r2) { + return (compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && + compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0); +} + +function findCompatibleQuery(dbName, tableName, type, req) { + const tblCache = cache[`idb://${dbName}/${tableName}`]; + if (!tblCache) + return []; + const queries = tblCache.queries[type]; + if (!queries) + return [null, false, tblCache, null]; + const indexName = req.query ? req.query.index.name : null; + const entries = queries[indexName || '']; + if (!entries) + return [null, false, tblCache, null]; + switch (type) { + case 'query': + const equalEntry = entries.find((entry) => entry.req.limit === req.limit && + entry.req.values === req.values && + areRangesEqual(entry.req.query.range, req.query.range)); + if (equalEntry) + return [ + equalEntry, + true, + tblCache, + entries, + ]; + const superEntry = entries.find((entry) => { + const limit = 'limit' in entry.req ? entry.req.limit : Infinity; + return (limit >= req.limit && + (req.values ? entry.req.values : true) && + isSuperRange(entry.req.query.range, req.query.range)); + }); + return [superEntry, false, tblCache, entries]; + case 'count': + const countQuery = entries.find((entry) => areRangesEqual(entry.req.query.range, req.query.range)); + return [countQuery, !!countQuery, tblCache, entries]; + } +} + +function subscribeToCacheEntry(cacheEntry, container, requery, signal) { + cacheEntry.subscribers.add(requery); + signal.addEventListener("abort", () => { + cacheEntry.subscribers.delete(requery); + if (cacheEntry.subscribers.size === 0) { + enqueForDeletion(cacheEntry, container); + } + }); +} +function enqueForDeletion(cacheEntry, container) { + setTimeout(() => { + if (cacheEntry.subscribers.size === 0) { + delArrayItem(container, cacheEntry); + } + }, 3000); +} + +const cacheMiddleware = { + stack: 'dbcore', + level: 0, + name: 'Cache', + create: (core) => { + const dbName = core.schema.name; + const coreMW = { + ...core, + transaction: (stores, mode, options) => { + const idbtrans = core.transaction(stores, mode, options); + if (mode === 'readwrite') { + const ac = new AbortController(); + const { signal } = ac; + const endTransaction = (wasCommitted) => () => { + ac.abort(); + if (mode === 'readwrite') { + const affectedSubscribers = new Set(); + for (const storeName of stores) { + const tblCache = cache[`idb://${dbName}/${storeName}`]; + const table = core.table(storeName); + if (tblCache) { + const ops = tblCache.optimisticOps.filter((op) => op.trans === idbtrans); + if (ops.length > 0) { + tblCache.optimisticOps = tblCache.optimisticOps.filter((op) => op.trans !== idbtrans); + for (const entries of Object.values(tblCache.queries.query)) { + for (const entry of entries.slice()) { + if (entry.res != null && + idbtrans.mutatedParts +) { + if (wasCommitted && !entry.dirty) { + const freezeResults = Object.isFrozen(entry.res); + const modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); + if (entry.dirty) { + delArrayItem(entries, entry); + entry.subscribers.forEach((requery) => affectedSubscribers.add(requery)); + } + else if (modRes !== entry.res) { + entry.res = modRes; + entry.promise = DexiePromise.resolve({ result: modRes }); + } + } + else { + if (entry.dirty) { + delArrayItem(entries, entry); + } + entry.subscribers.forEach((requery) => affectedSubscribers.add(requery)); + } + } + } + } + } + } + } + affectedSubscribers.forEach((requery) => requery()); + } + }; + idbtrans.addEventListener('abort', endTransaction(false), { + signal, + }); + idbtrans.addEventListener('error', endTransaction(false), { + signal, + }); + idbtrans.addEventListener('complete', endTransaction(true), { + signal, + }); + } + return idbtrans; + }, + table(tableName) { + const downTable = core.table(tableName); + const primKey = downTable.schema.primaryKey; + const tableMW = { + ...downTable, + mutate(req) { + if (primKey.outbound || + PSD.trans.db._options.cache === 'disabled' + ) { + return downTable.mutate(req); + } + const tblCache = cache[`idb://${dbName}/${tableName}`]; + if (!tblCache) + return downTable.mutate(req); + const promise = downTable.mutate(req); + if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(key => key == null))) { + promise.then((res) => { + const reqWithResolvedKeys = { + ...req, + values: req.values.map((value, i) => { + const valueWithKey = primKey.keyPath.includes('.') + ? deepClone(value) + : { + ...value, + }; + setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); + return valueWithKey; + }) + }; + tblCache.optimisticOps.push(reqWithResolvedKeys); + queueMicrotask(() => signalSubscribersLazily(req.mutatedParts)); + }); + } + else { + tblCache.optimisticOps.push(req); + signalSubscribersLazily(req.mutatedParts); + promise.catch(() => { + delArrayItem(tblCache.optimisticOps, req); + signalSubscribersLazily(req.mutatedParts); + }); + } + return promise; + }, + query(req) { + if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) + return downTable.query(req); + const freezeResults = PSD.trans.db._options.cache === 'immutable'; + const { requery, signal } = PSD; + let [cacheEntry, exactMatch, tblCache, container] = findCompatibleQuery(dbName, tableName, 'query', req); + if (cacheEntry && exactMatch) { + cacheEntry.obsSet = req.obsSet; + } + else { + const promise = downTable.query(req).then((res) => { + const result = res.result; + cacheEntry.res = result; + if (freezeResults) { + for (let i = 0, l = result.length; i < l; ++i) { + Object.freeze(result[i]); + } + Object.freeze(result); + } + else { + res.result = deepClone(result); + } + return res; + }).catch(error => { + if (container && cacheEntry) + delArrayItem(container, cacheEntry); + return Promise.reject(error); + }); + cacheEntry = { + obsSet: req.obsSet, + promise, + subscribers: new Set(), + type: 'query', + req, + dirty: false, + }; + if (container) { + container.push(cacheEntry); + } + else { + container = [cacheEntry]; + if (!tblCache) { + tblCache = cache[`idb://${dbName}/${tableName}`] = { + queries: { + query: {}, + count: {}, + }, + objs: new Map(), + optimisticOps: [], + unsignaledParts: {} + }; + } + tblCache.queries.query[req.query.index.name || ''] = container; + } + } + subscribeToCacheEntry(cacheEntry, container, requery, signal); + return cacheEntry.promise.then((res) => { + return { + result: applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults), + }; + }); + }, + }; + return tableMW; + }, + }; + return coreMW; + }, +}; + +function vipify(target, vipDb) { + return new Proxy(target, { + get(target, prop, receiver) { + if (prop === 'db') + return vipDb; + return Reflect.get(target, prop, receiver); + } + }); +} + +class Dexie$1 { + constructor(name, options) { + this._middlewares = {}; + this.verno = 0; + const deps = Dexie$1.dependencies; + this._options = options = { + addons: Dexie$1.addons, + autoOpen: true, + indexedDB: deps.indexedDB, + IDBKeyRange: deps.IDBKeyRange, + cache: 'cloned', + ...options + }; + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + const { addons, } = options; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + this._novip = this; + const state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3 + }; + state.dbReadyPromise = new DexiePromise(resolve => { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise((_, reject) => { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] }); + this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => { + return (subscriber, bSticky) => { + Dexie$1.vip(() => { + const state = this._state; + if (state.openComplete) { + if (!state.dbOpenError) + DexiePromise.resolve().then(subscriber); + if (bSticky) + subscribe(subscriber); + } + else if (state.onReadyBeingFired) { + state.onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } + else { + subscribe(subscriber); + const db = this; + if (!bSticky) + subscribe(function unsubscribe() { + db.on.ready.unsubscribe(subscriber); + db.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.Collection = createCollectionConstructor(this); + this.Table = createTableConstructor(this); + this.Transaction = createTransactionConstructor(this); + this.Version = createVersionConstructor(this); + this.WhereClause = createWhereClauseConstructor(this); + this.on("versionchange", ev => { + if (ev.newVersion > 0) + console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`); + else + console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`); + this.close({ disableAutoOpen: false }); + this._state.openComplete = false; + }); + this.on("blocked", ev => { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn(`Dexie.delete('${this.name}') was blocked`); + else + console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`); + }); + this._maxKey = getMaxKey(options.IDBKeyRange); + this._createTransaction = (mode, storeNames, dbschema, parentTransaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction); + this._fireOnBlocked = ev => { + this.on("blocked").fire(ev); + connections + .filter(c => c.name === this.name && c !== this && !c._state.vcFired) + .map(c => c.on("versionchange").fire(ev)); + }; + this.use(cacheExistingValuesMiddleware); + this.use(cacheMiddleware); + this.use(observabilityMiddleware); + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + const vipDB = new Proxy(this, { + get: (_, prop, receiver) => { + if (prop === '_vip') + return true; + if (prop === 'table') + return (tableName) => vipify(this.table(tableName), vipDB); + const rv = Reflect.get(_, prop, receiver); + if (rv instanceof Table) + return vipify(rv, vipDB); + if (prop === 'tables') + return rv.map(t => vipify(t, vipDB)); + if (prop === '_createTransaction') + return function () { + const tx = rv.apply(this, arguments); + return vipify(tx, vipDB); + }; + return rv; + } + }); + this.vip = vipDB; + addons.forEach(addon => addon(this)); + } + version(versionNumber) { + if (isNaN(versionNumber) || versionNumber < 0.1) + throw new exceptions.Type(`Given version is not a positive number`); + versionNumber = Math.round(versionNumber * 10) / 10; + if (this.idbdb || this._state.isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + const versions = this._versions; + var versionInstance = versions.filter(v => v._cfg.version === versionNumber)[0]; + if (versionInstance) + return versionInstance; + versionInstance = new this.Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + versionInstance.stores({}); + this._state.autoSchema = false; + return versionInstance; + } + _whenReady(fn) { + return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new DexiePromise((resolve, reject) => { + if (this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(this._state.dbOpenError)); + } + if (!this._state.isBeingOpened) { + if (!this._options.autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + this.open().catch(nop); + } + this._state.dbReadyPromise.then(resolve, reject); + }).then(fn); + } + use({ stack, create, level, name }) { + if (name) + this.unuse({ stack, name }); + const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ stack, create, level: level == null ? 10 : level, name }); + middlewares.sort((a, b) => a.level - b.level); + return this; + } + unuse({ stack, name, create }) { + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(mw => create ? mw.create !== create : + name ? mw.name !== name : + false); + } + return this; + } + open() { + return usePSD(globalPSD, + () => dexieOpen(this)); + } + _close() { + const state = this._state; + const idx = connections.indexOf(this); + if (idx >= 0) + connections.splice(idx, 1); + if (this.idbdb) { + try { + this.idbdb.close(); + } + catch (e) { } + this.idbdb = null; + } + state.dbReadyPromise = new DexiePromise(resolve => { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise((_, reject) => { + state.cancelOpen = reject; + }); + } + close({ disableAutoOpen } = { disableAutoOpen: true }) { + this._close(); + const state = this._state; + if (disableAutoOpen) + this._options.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + if (state.isBeingOpened) + state.cancelOpen(state.dbOpenError); + } + delete() { + const hasArguments = arguments.length > 0; + const state = this._state; + return new DexiePromise((resolve, reject) => { + const doDelete = () => { + this.close({ disableAutoOpen: false }); + var req = this._deps.indexedDB.deleteDatabase(this.name); + req.onsuccess = wrap(() => { + _onDatabaseDeleted(this._deps, this.name); + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = this._fireOnBlocked; + }; + if (hasArguments) + throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()"); + if (state.isBeingOpened) { + state.dbReadyPromise.then(doDelete); + } + else { + doDelete(); + } + }); + } + backendDB() { + return this.idbdb; + } + isOpen() { + return this.idbdb !== null; + } + hasBeenClosed() { + const dbOpenError = this._state.dbOpenError; + return dbOpenError && (dbOpenError.name === 'DatabaseClosed'); + } + hasFailed() { + return this._state.dbOpenError !== null; + } + dynamicallyOpened() { + return this._state.autoSchema; + } + get tables() { + return keys(this._allTables).map(name => this._allTables[name]); + } + transaction() { + const args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + } + _transaction(mode, tables, scopeFunc) { + let parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) + parentTransaction = null; + const onlyIfCompatible = mode.indexOf('?') !== -1; + mode = mode.replace('!', '').replace('?', ''); + let idbMode, storeNames; + try { + storeNames = tables.map(table => { + var storeName = table instanceof this.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; + }); + if (mode == "r" || mode === READONLY) + idbMode = READONLY; + else if (mode == "rw" || mode == READWRITE) + idbMode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + if (parentTransaction.mode === READONLY && idbMode === READWRITE) { + if (onlyIfCompatible) { + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); + } + if (parentTransaction) { + storeNames.forEach(storeName => { + if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { + if (onlyIfCompatible) { + parentTransaction = null; + } + else + throw new exceptions.SubTransaction("Table " + storeName + + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + parentTransaction = null; + } + } + } + catch (e) { + return parentTransaction ? + parentTransaction._promise(null, (_, reject) => { reject(e); }) : + rejection(e); + } + const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return (parentTransaction ? + parentTransaction._promise(idbMode, enterTransaction, "lock") : + PSD.trans ? + usePSD(PSD.transless, () => this._whenReady(enterTransaction)) : + this._whenReady(enterTransaction)); + } + table(tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); + } + return this._allTables[tableName]; + } +} + +const symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol + ? Symbol.observable + : "@@observable"; +class Observable { + constructor(subscribe) { + this._subscribe = subscribe; + } + subscribe(x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error, complete } : x); + } + [symbolObservable]() { + return this; + } +} + +let domDeps; +try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; +} +catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; +} + +function liveQuery(querier) { + let hasValue = false; + let currentValue; + const observable = new Observable((observer) => { + const scopeFuncIsAsync = isAsyncFunction(querier); + function execute(ctx) { + const wasRootExec = beginMicroTickScope(); + try { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + const rv = newScope(querier, ctx); + if (scopeFuncIsAsync) { + rv.finally(decrementExpectedAwaits); + } + return rv; + } + finally { + wasRootExec && endMicroTickScope(); + } + } + let closed = false; + let abortController; + let accumMuts = {}; + let currentObs = {}; + const subscription = { + get closed() { + return closed; + }, + unsubscribe: () => { + if (closed) + return; + closed = true; + if (abortController) + abortController.abort(); + if (startedListening) + globalEvents.storagemutated.unsubscribe(mutationListener); + }, + }; + observer.start && observer.start(subscription); + let startedListening = false; + function shouldNotify() { + return obsSetsOverlap(currentObs, accumMuts); + } + const mutationListener = (parts) => { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + const doQuery = () => { + if (closed || + !domDeps.indexedDB) + { + return; + } + accumMuts = {}; + const subscr = {}; + if (abortController) + abortController.abort(); + abortController = new AbortController(); + const ctx = { + subscr, + signal: abortController.signal, + requery: doQuery, + querier, + trans: null + }; + const ret = execute(ctx); + Promise.resolve(ret).then((result) => { + hasValue = true; + currentValue = result; + if (closed || ctx.signal.aborted) { + return; + } + accumMuts = {}; + currentObs = subscr; + if (!objectIsEmpty(currentObs) && !startedListening) { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener); + startedListening = true; + } + observer.next && observer.next(result); + }, (err) => { + hasValue = false; + if (!['DatabaseClosedError', 'AbortError'].includes(err === null || err === void 0 ? void 0 : err.name)) { + if (closed) + return; + observer.error && observer.error(err); + } + }); + }; + doQuery(); + return subscription; + }); + observable.hasValue = () => hasValue; + observable.getValue = () => currentValue; + return observable; +} + +const Dexie = Dexie$1; +props(Dexie, { + ...fullNameExceptions, + delete(databaseName) { + const db = new Dexie(databaseName, { addons: [] }); + return db.delete(); + }, + exists(name) { + return new Dexie(name, { addons: [] }).open().then(db => { + db.close(); + return true; + }).catch('NoSuchDatabaseError', () => false); + }, + getDatabaseNames(cb) { + try { + return getDatabaseNames(Dexie.dependencies).then(cb); + } + catch (_a) { + return rejection(new exceptions.MissingAPI()); + } + }, + defineClass() { + function Class(content) { + extend(this, content); + } + return Class; + }, + ignoreTransaction(scopeFunc) { + return PSD.trans ? + usePSD(PSD.transless, scopeFunc) : + scopeFunc(); + }, + vip, + async: function (generatorFn) { + return function () { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== 'function') + return DexiePromise.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 DexiePromise.resolve(rv); + return rv; + } + catch (e) { + return rejection(e); + } + }, + currentTransaction: { + get: () => PSD.trans || null + }, + waitFor: function (promiseOrFunction, optionalTimeout) { + const promise = DexiePromise.resolve(typeof promiseOrFunction === 'function' ? + Dexie.ignoreTransaction(promiseOrFunction) : + promiseOrFunction) + .timeout(optionalTimeout || 60000); + return PSD.trans ? + PSD.trans.waitFor(promise) : + promise; + }, + Promise: DexiePromise, + debug: { + get: () => debug, + set: value => { + setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter); + } + }, + derive: derive, + extend: extend, + props: props, + override: override, + Events: Events, + on: globalEvents, + liveQuery, + extendObservabilitySet, + getByKeyPath: getByKeyPath, + setByKeyPath: setByKeyPath, + delByKeyPath: delByKeyPath, + shallowClone: shallowClone, + deepClone: deepClone, + getObjectDiff: getObjectDiff, + cmp, + asap: asap$1, + minKey: minKey, + addons: [], + connections: connections, + errnames: errnames, + dependencies: domDeps, + cache, + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split('.') + .map(n => parseInt(n)) + .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))), +}); +Dexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange); + +if (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => { + if (!propagatingLocally) { + let event; + if (isIEOrEdge) { + event = document.createEvent('CustomEvent'); + event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts); + } + else { + event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + } + propagatingLocally = true; + dispatchEvent(event); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({ detail }) => { + if (!propagatingLocally) { + propagateLocally(detail); + } + }); +} +function propagateLocally(updateParts) { + let wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + signalSubscribersNow(updateParts, true); + } + finally { + propagatingLocally = wasMe; + } +} +let propagatingLocally = false; + +if (typeof BroadcastChannel !== 'undefined') { + const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + if (typeof bc.unref === 'function') { + bc.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => { + if (!propagatingLocally) { + bc.postMessage(changedParts); + } + }); + bc.onmessage = (ev) => { + if (ev.data) + propagateLocally(ev.data); + }; +} +else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => { + try { + if (!propagatingLocally) { + if (typeof localStorage !== 'undefined') { + localStorage.setItem(STORAGE_MUTATED_DOM_EVENT_NAME, JSON.stringify({ + trig: Math.random(), + changedParts, + })); + } + if (typeof self['clients'] === 'object') { + [...self['clients'].matchAll({ includeUncontrolled: true })].forEach((client) => client.postMessage({ + type: STORAGE_MUTATED_DOM_EVENT_NAME, + changedParts, + })); + } + } + } + catch (_a) { } + }); + if (typeof addEventListener !== 'undefined') { + addEventListener('storage', (ev) => { + if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) { + const data = JSON.parse(ev.newValue); + if (data) + propagateLocally(data.changedParts); + } + }); + } + const swContainer = self.document && navigator.serviceWorker; + if (swContainer) { + swContainer.addEventListener('message', propagateMessageLocally); + } +} +function propagateMessageLocally({ data }) { + if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) { + propagateLocally(data.changedParts); + } +} + +DexiePromise.rejectionMapper = mapError; +setDebug(debug, dexieStackFrameFilter); + +export { Dexie$1 as Dexie, Entity, RangeSet, cmp, Dexie$1 as default, liveQuery, mergeRanges, rangesOverlap }; +//# sourceMappingURL=dexie.mjs.map diff --git a/dist/modern/dexie.mjs.map b/dist/modern/dexie.mjs.map new file mode 100644 index 000000000..73b8d0ebe --- /dev/null +++ b/dist/modern/dexie.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"dexie.mjs","sources":["../../src/globals/global.ts","../../src/functions/utils.ts","../../src/helpers/debug.ts","../../src/errors/errors.js","../../src/functions/chaining-functions.js","../../src/helpers/promise.js","../../src/functions/temp-transaction.ts","../../src/globals/constants.ts","../../src/functions/combine.ts","../../src/dbcore/keyrange.ts","../../src/functions/workaround-undefined-primkey.ts","../../src/classes/entity/Entity.ts","../../src/functions/cmp.ts","../../src/classes/table/table.ts","../../src/helpers/Events.js","../../src/functions/make-class-constructor.ts","../../src/classes/table/table-constructor.ts","../../src/classes/collection/collection-helpers.ts","../../src/classes/collection/collection.ts","../../src/classes/collection/collection-constructor.ts","../../src/functions/compare-functions.ts","../../src/classes/where-clause/where-clause-helpers.ts","../../src/classes/where-clause/where-clause.ts","../../src/classes/where-clause/where-clause-constructor.ts","../../src/functions/event-wrappers.ts","../../src/globals/global-events.ts","../../src/classes/transaction/transaction.ts","../../src/classes/transaction/transaction-constructor.ts","../../src/helpers/index-spec.ts","../../src/helpers/table-schema.ts","../../src/functions/quirks.ts","../../src/dbcore/get-key-extractor.ts","../../src/dbcore/dbcore-indexeddb.ts","../../src/classes/dexie/generate-middleware-stacks.ts","../../src/classes/version/schema-helpers.ts","../../src/classes/version/version.ts","../../src/classes/version/version-constructor.ts","../../src/helpers/database-enumerator.ts","../../src/classes/dexie/vip.ts","../../node_modules/.pnpm/safari-14-idb-fix@3.0.0/node_modules/safari-14-idb-fix/dist/index.js","../../src/helpers/rangeset.ts","../../src/live-query/extend-observability-set.ts","../../src/live-query/obs-sets-overlap.ts","../../src/live-query/cache/cache.ts","../../src/live-query/cache/signalSubscribers.ts","../../src/classes/dexie/dexie-open.ts","../../src/helpers/yield-support.ts","../../src/classes/dexie/transaction-helpers.ts","../../src/dbcore/virtual-index-middleware.ts","../../src/functions/get-object-diff.ts","../../src/dbcore/get-effective-keys.ts","../../src/hooks/hooks-middleware.ts","../../src/dbcore/cache-existing-values-middleware.ts","../../src/live-query/cache/is-cachable-context.ts","../../src/live-query/cache/is-cachable-request.ts","../../src/live-query/observability-middleware.ts","../../src/live-query/cache/is-within-range.ts","../../src/live-query/cache/apply-optimistic-ops.ts","../../src/live-query/cache/are-ranges-equal.ts","../../src/live-query/cache/is-super-range.ts","../../src/live-query/cache/find-compatible-query.ts","../../src/live-query/cache/subscribe-cachentry.ts","../../src/live-query/cache/cache-middleware.ts","../../src/helpers/vipify.ts","../../src/classes/dexie/dexie.ts","../../src/classes/observable/observable.ts","../../src/classes/dexie/dexie-dom-dependencies.ts","../../src/live-query/live-query.ts","../../src/classes/dexie/dexie-static-props.ts","../../src/live-query/propagate-locally.ts","../../src/live-query/enable-broadcast.ts","../../src/index.ts"],"sourcesContent":["declare var global;\nexport const _global: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof self !== 'undefined' ? self :\n typeof window !== 'undefined' ? window :\n global;\n","import { _global } from \"../globals/global\";\nexport const keys = Object.keys;\nexport const isArray = Array.isArray;\nif (typeof Promise !== 'undefined' && !_global.Promise){\n // In jsdom, this it can be the case that Promise is not put on the global object.\n // If so, we need to patch the global object for the rest of the code to work as expected.\n // Other dexie code expects Promise to be on the global object (like normal browser environments)\n _global.Promise = Promise;\n}\nexport { _global }\n\nexport function extend(obj: T, extension: X): T & X {\n if (typeof extension !== 'object') return obj as T & X;\n keys(extension).forEach(function (key) {\n obj[key] = extension[key];\n });\n return obj as T & X;\n}\n\nexport const getProto = Object.getPrototypeOf;\nexport const _hasOwn = {}.hasOwnProperty;\nexport function hasOwn(obj, prop) {\n return _hasOwn.call(obj, prop);\n}\n\nexport function props (proto, extension) {\n if (typeof extension === 'function') extension = extension(getProto(proto));\n (typeof Reflect === \"undefined\" ? keys : Reflect.ownKeys)(extension).forEach(key => {\n setProp(proto, key, extension[key]);\n });\n}\n\nexport const defineProperty = Object.defineProperty;\n\nexport function setProp(obj, prop, functionOrGetSet, options?) {\n defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, \"get\") && typeof functionOrGetSet.get === 'function' ?\n {get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :\n {value: functionOrGetSet, configurable: true, writable: true}, options));\n}\n\nexport function derive(Child) {\n return {\n from: function (Parent) {\n Child.prototype = Object.create(Parent.prototype);\n setProp(Child.prototype, \"constructor\", Child);\n return {\n extend: props.bind(null, Child.prototype)\n };\n }\n };\n}\n\nexport const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\nexport function getPropertyDescriptor(obj, prop) {\n const pd = getOwnPropertyDescriptor(obj, prop);\n let proto;\n return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);\n}\n\nconst _slice = [].slice;\nexport function slice(args, start?, end?) {\n return _slice.call(args, start, end);\n}\n\nexport function override(origFunc, overridedFactory) {\n return overridedFactory(origFunc);\n}\n\nexport function assert (b) {\n if (!b) throw new Error(\"Assertion Failed\");\n}\n\nexport function asap(fn) {\n // @ts-ignore\n if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);\n}\n\nexport function getUniqueArray(a) {\n return a.filter((value, index, self) => self.indexOf(value) === index);\n}\n\n/** Generate an object (hash map) based on given array.\n * @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to\n * instert on the resulting object for each item in the array. If this function returns a falsy value, the\n * current item wont affect the resulting object.\n */\nexport function arrayToObject (array: T[], extractor: (x:T, idx: number)=>[string, R]): {[name: string]: R} {\n return array.reduce((result, item, i) => {\n var nameAndValue = extractor(item, i);\n if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];\n return result;\n }, {});\n}\n\nexport function trycatcher(fn, reject) {\n return function () {\n try {\n fn.apply(this, arguments);\n } catch (e) {\n reject(e);\n }\n };\n}\n\nexport function tryCatch(fn: (...args: any[])=>void, onerror, args?) : void {\n try {\n fn.apply(null, args);\n } catch (ex) {\n onerror && onerror(ex);\n }\n}\n\nexport function getByKeyPath(obj, keyPath) {\n // http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path\n if (typeof keyPath === 'string' && hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.\n if (!keyPath) return obj;\n if (typeof keyPath !== 'string') {\n var rv = [];\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n var val = getByKeyPath(obj, keyPath[i]);\n rv.push(val);\n }\n return rv;\n }\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var innerObj = obj[keyPath.substr(0, period)];\n return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));\n }\n return undefined;\n}\n\nexport function setByKeyPath(obj, keyPath, value) {\n if (!obj || keyPath === undefined) return;\n if ('isFrozen' in Object && Object.isFrozen(obj)) return;\n if (typeof keyPath !== 'string' && 'length' in keyPath) {\n assert(typeof value !== 'string' && 'length' in value);\n for (var i = 0, l = keyPath.length; i < l; ++i) {\n setByKeyPath(obj, keyPath[i], value[i]);\n }\n } else {\n var period = keyPath.indexOf('.');\n if (period !== -1) {\n var currentKeyPath = keyPath.substr(0, period);\n var remainingKeyPath = keyPath.substr(period + 1);\n if (remainingKeyPath === \"\")\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) obj.splice(currentKeyPath, 1);\n else delete obj[currentKeyPath];\n } else obj[currentKeyPath] = value;\n else {\n var innerObj = obj[currentKeyPath];\n if (!innerObj || !hasOwn(obj, currentKeyPath)) innerObj = (obj[currentKeyPath] = {});\n setByKeyPath(innerObj, remainingKeyPath, value);\n }\n } else {\n if (value === undefined) {\n if (isArray(obj) && !isNaN(parseInt(keyPath))) obj.splice(keyPath, 1);\n else delete obj[keyPath];\n } else obj[keyPath] = value;\n }\n }\n}\n\nexport function delByKeyPath(obj, keyPath) {\n if (typeof keyPath === 'string')\n setByKeyPath(obj, keyPath, undefined);\n else if ('length' in keyPath)\n [].map.call(keyPath, function(kp) {\n setByKeyPath(obj, kp, undefined);\n });\n}\n\nexport function shallowClone(obj) {\n var rv = {};\n for (var m in obj) {\n if (hasOwn(obj, m)) rv[m] = obj[m];\n }\n return rv;\n}\n\nconst concat = [].concat;\nexport function flatten (a: (T | T[])[]) : T[] {\n return concat.apply([], a);\n}\n\n//https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\nconst intrinsicTypeNames =\n \"Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey\"\n .split(',').concat(\n flatten([8,16,32,64].map(num=>[\"Int\",\"Uint\",\"Float\"].map(t=>t+num+\"Array\")))\n ).filter(t=>_global[t]);\nconst intrinsicTypes = new Set(intrinsicTypeNames.map(t=>_global[t]));\n\n/** Deep clone a simple object tree.\n * \n * Copies object tree deeply, but does not deep-copy arrays,\n * typed arrays, Dates or other intrinsic types.\n * \n * Does not check for cyclic references.\n * \n * This function is 6 times faster than structuredClone() on chromium 111.\n * \n * This function can safely be used for cloning ObservabilitySets and RangeSets.\n * \n * @param o Object to clone\n * @returns Cloned object\n */\nexport function cloneSimpleObjectTree(o: T): T {\n const rv = {} as T;\n for (const k in o) if (hasOwn(o, k)) {\n const v = o[k];\n rv[k] = !v || typeof v !== 'object' || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v);\n }\n return rv;\n}\n\nexport function objectIsEmpty(o: object) {\n for (const k in o) if (hasOwn(o, k)) return false;\n return true;\n}\n\nlet circularRefs: null | WeakMap = null;\n\n/** Deep clone an object or array.\n * \n * \n * @param any \n * @returns \n */\nexport function deepClone(any: T): T {\n circularRefs = new WeakMap();\n const rv = innerDeepClone(any);\n circularRefs = null;\n return rv;\n}\n\nfunction innerDeepClone(x: T): T {\n if (!x || typeof x !== 'object') return x;\n let rv = circularRefs.get(x); // Resolve circular references\n if (rv) return rv;\n if (isArray(x)) {\n rv = [];\n circularRefs.set(x, rv);\n for (var i = 0, l = x.length; i < l; ++i) {\n rv.push(innerDeepClone(x[i]));\n }\n } else if (intrinsicTypes.has(x.constructor)) {\n // For performance, we're less strict than structuredClone - we're only\n // cloning arrays and custom objects.\n // Typed arrays, Dates etc are not cloned.\n rv = x;\n } else {\n // We're nicer to custom classes than what structuredClone() is -\n // we preserve the proto of each object.\n const proto = getProto(x);\n rv = proto === Object.prototype ? {} : Object.create(proto);\n circularRefs.set(x, rv);\n for (var prop in x) {\n if (hasOwn(x, prop)) {\n rv[prop] = innerDeepClone(x[prop]);\n }\n }\n }\n return rv;\n}\n\nconst {toString} = {};\nexport function toStringTag(o: Object) {\n return toString.call(o).slice(8, -1);\n}\n\n// If first argument is iterable or array-like, return it as an array\nexport const iteratorSymbol = typeof Symbol !== 'undefined' ?\n Symbol.iterator :\n '@@iterator';\nexport const getIteratorOf = typeof iteratorSymbol === \"symbol\" ? function(x) {\n var i;\n return x != null && (i = x[iteratorSymbol]) && i.apply(x);\n} : function () { return null; };\nexport const asyncIteratorSymbol = typeof Symbol !== 'undefined'\n ? Symbol.asyncIterator || Symbol.for(\"Symbol.asyncIterator\")\n : '@asyncIterator';\n\nexport function delArrayItem(a: any[], x: any) {\n const i = a.indexOf(x);\n if (i >= 0) a.splice(i, 1);\n return i >= 0;\n}\n\nexport const NO_CHAR_ARRAY = {};\n// Takes one or several arguments and returns an array based on the following criteras:\n// * If several arguments provided, return arguments converted to an array in a way that\n// still allows javascript engine to optimize the code.\n// * If single argument is an array, return a clone of it.\n// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special\n// case to the two bullets below.\n// * If single argument is an iterable, convert it to an array and return the resulting array.\n// * If single argument is array-like (has length of type number), convert it to an array.\nexport function getArrayOf (arrayLike) {\n var i, a, x, it;\n if (arguments.length === 1) {\n if (isArray(arrayLike)) return arrayLike.slice();\n if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];\n if ((it = getIteratorOf(arrayLike))) {\n a = [];\n while ((x = it.next()), !x.done) a.push(x.value);\n return a;\n }\n if (arrayLike == null) return [arrayLike];\n i = arrayLike.length;\n if (typeof i === 'number') {\n a = new Array(i);\n while (i--) a[i] = arrayLike[i];\n return a;\n }\n return [arrayLike];\n }\n i = arguments.length;\n a = new Array(i);\n while (i--) a[i] = arguments[i];\n return a;\n}\nexport const isAsyncFunction = typeof Symbol !== 'undefined'\n ? (fn: Function) => fn[Symbol.toStringTag] === 'AsyncFunction'\n : ()=>false;\n","// By default, debug will be true only if platform is a web platform and its page is served from localhost.\n// When debug = true, error's stacks will contain asyncronic long stacks.\nexport var debug = typeof location !== 'undefined' &&\n // By default, use debug mode if served from localhost.\n /^(http|https):\\/\\/(localhost|127\\.0\\.0\\.1)/.test(location.href);\n\nexport function setDebug(value, filter) {\n debug = value;\n libraryFilter = filter;\n}\n\nexport var libraryFilter = () => true;\n\nexport const NEEDS_THROW_FOR_STACK = !new Error(\"\").stack;\n\nexport function getErrorWithStack() {\n \"use strict\";\n if (NEEDS_THROW_FOR_STACK) try {\n // Doing something naughty in strict mode here to trigger a specific error\n // that can be explicitely ignored in debugger's exception settings.\n // If we'd just throw new Error() here, IE's debugger's exception settings\n // will just consider it as \"exception thrown by javascript code\" which is\n // something you wouldn't want it to ignore.\n getErrorWithStack.arguments;\n throw new Error(); // Fallback if above line don't throw.\n } catch(e) {\n return e;\n }\n return new Error();\n}\n\nexport function prettyStack(exception, numIgnoredFrames) {\n var stack = exception.stack;\n if (!stack) return \"\";\n numIgnoredFrames = (numIgnoredFrames || 0);\n if (stack.indexOf(exception.name) === 0)\n numIgnoredFrames += (exception.name + exception.message).split('\\n').length;\n return stack.split('\\n')\n .slice(numIgnoredFrames)\n .filter(libraryFilter)\n .map(frame => \"\\n\" + frame)\n .join('');\n}\n\n// TODO: Replace this in favor of a decorator instead.\nexport function deprecated (what: string, fn: (...args)=>T) {\n return function () {\n console.warn(`${what} is deprecated. See https://dexie.org/docs/Deprecations. ${prettyStack(getErrorWithStack(), 1)}`);\n return fn.apply(this, arguments);\n } as (...args)=>T\n}\n","import { derive, setProp } from '../functions/utils';\nimport { getErrorWithStack, prettyStack } from '../helpers/debug';\n\nvar dexieErrorNames = [\n 'Modify',\n 'Bulk',\n 'OpenFailed',\n 'VersionChange',\n 'Schema',\n 'Upgrade',\n 'InvalidTable',\n 'MissingAPI',\n 'NoSuchDatabase',\n 'InvalidArgument',\n 'SubTransaction',\n 'Unsupported',\n 'Internal',\n 'DatabaseClosed',\n 'PrematureCommit',\n 'ForeignAwait'\n];\n\nvar idbDomErrorNames = [\n 'Unknown',\n 'Constraint',\n 'Data',\n 'TransactionInactive',\n 'ReadOnly',\n 'Version',\n 'NotFound',\n 'InvalidState',\n 'InvalidAccess',\n 'Abort',\n 'Timeout',\n 'QuotaExceeded',\n 'Syntax',\n 'DataClone'\n];\n\nvar errorList = dexieErrorNames.concat(idbDomErrorNames);\n\nvar defaultTexts = {\n VersionChanged: \"Database version changed by other database connection\",\n DatabaseClosed: \"Database has been closed\",\n Abort: \"Transaction aborted\",\n TransactionInactive: \"Transaction has already completed or failed\",\n MissingAPI: \"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb\"\n};\n\n//\n// DexieError - base class of all out exceptions.\n//\nexport function DexieError (name, msg) {\n // Reason we don't use ES6 classes is because:\n // 1. It bloats transpiled code and increases size of minified code.\n // 2. It doesn't give us much in this case.\n // 3. It would require sub classes to call super(), which\n // is not needed when deriving from Error.\n this._e = getErrorWithStack();\n this.name = name;\n this.message = msg;\n}\n\nderive(DexieError).from(Error).extend({\n stack: {\n get: function() {\n return this._stack ||\n (this._stack = this.name + \": \" + this.message + prettyStack(this._e, 2));\n }\n },\n toString: function(){ return this.name + \": \" + this.message; }\n});\n\nfunction getMultiErrorMessage (msg, failures) {\n return msg + \". Errors: \" + Object.keys(failures)\n .map(key=>failures[key].toString())\n .filter((v,i,s)=>s.indexOf(v) === i) // Only unique error strings\n .join('\\n');\n}\n\n//\n// ModifyError - thrown in Collection.modify()\n// Specific constructor because it contains members failures and failedKeys.\n//\nexport function ModifyError (msg, failures, successCount, failedKeys) {\n this._e = getErrorWithStack();\n this.failures = failures;\n this.failedKeys = failedKeys;\n this.successCount = successCount;\n this.message = getMultiErrorMessage(msg, failures);\n}\nderive(ModifyError).from(DexieError);\n\nexport function BulkError (msg, failures) {\n this._e = getErrorWithStack();\n this.name = \"BulkError\";\n this.failures = Object.keys(failures).map(pos => failures[pos]);\n this.failuresByPos = failures;\n this.message = getMultiErrorMessage(msg, this.failures);\n}\nderive(BulkError).from(DexieError);\n\n//\n//\n// Dynamically generate error names and exception classes based\n// on the names in errorList.\n//\n//\n\n// Map of {ErrorName -> ErrorName + \"Error\"}\nexport var errnames = errorList.reduce((obj,name)=>(obj[name]=name+\"Error\",obj),{});\n\n// Need an alias for DexieError because we're gonna create subclasses with the same name.\nconst BaseException = DexieError;\n// Map of {ErrorName -> exception constructor}\nexport var exceptions = errorList.reduce((obj,name)=>{\n // Let the name be \"DexieError\" because this name may\n // be shown in call stack and when debugging. DexieError is\n // the most true name because it derives from DexieError,\n // and we cannot change Function.name programatically without\n // dynamically create a Function object, which would be considered\n // 'eval-evil'.\n var fullName = name + \"Error\";\n function DexieError (msgOrInner, inner){\n this._e = getErrorWithStack();\n this.name = fullName;\n if (!msgOrInner) {\n this.message = defaultTexts[name] || fullName;\n this.inner = null;\n } else if (typeof msgOrInner === 'string') {\n this.message = `${msgOrInner}${!inner ? '' : '\\n ' + inner}`;\n this.inner = inner || null;\n } else if (typeof msgOrInner === 'object') {\n this.message = `${msgOrInner.name} ${msgOrInner.message}`;\n this.inner = msgOrInner;\n }\n }\n derive(DexieError).from(BaseException);\n obj[name]=DexieError;\n return obj;\n},{});\n\n// Use ECMASCRIPT standard exceptions where applicable:\nexceptions.Syntax = SyntaxError;\nexceptions.Type = TypeError;\nexceptions.Range = RangeError;\n\nexport var exceptionMap = idbDomErrorNames.reduce((obj, name)=>{\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nexport function mapError (domError, message) {\n if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name])\n return domError;\n var rv = new exceptionMap[domError.name](message || domError.message, domError);\n if (\"stack\" in domError) {\n // Derive stack from inner exception if it has a stack\n setProp(rv, \"stack\", {get: function(){\n return this.inner.stack;\n }});\n }\n return rv;\n}\n\nexport var fullNameExceptions = errorList.reduce((obj, name)=>{\n if ([\"Syntax\",\"Type\",\"Range\"].indexOf(name) === -1)\n obj[name + \"Error\"] = exceptions[name];\n return obj;\n}, {});\n\nfullNameExceptions.ModifyError = ModifyError;\nfullNameExceptions.DexieError = DexieError;\nfullNameExceptions.BulkError = BulkError;\n","import {extend} from './utils';\n\nexport function nop() { }\nexport function mirror(val) { return val; }\nexport function pureFunctionChain(f1, f2) {\n // Enables chained events that takes ONE argument and returns it to the next function in chain.\n // This pattern is used in the hook(\"reading\") event.\n if (f1 == null || f1 === mirror) return f2;\n return function (val) {\n return f2(f1(val));\n };\n}\n\nexport function callBoth(on1, on2) {\n return function () {\n on1.apply(this, arguments);\n on2.apply(this, arguments);\n };\n}\n\nexport function hookCreatingChain(f1, f2) {\n // Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.\n // This pattern is used in the hook(\"creating\") event.\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res !== undefined) arguments[0] = res;\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res2 !== undefined ? res2 : res;\n };\n}\n\nexport function hookDeletingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = this.onerror = null;\n f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n };\n}\n\nexport function hookUpdatingChain(f1, f2) {\n if (f1 === nop) return f2;\n return function (modifications) {\n var res = f1.apply(this, arguments);\n extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.\n var onsuccess = this.onsuccess, // In case event listener has set this.onsuccess\n onerror = this.onerror; // In case event listener has set this.onerror\n this.onsuccess = null;\n this.onerror = null;\n var res2 = f2.apply(this, arguments);\n if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;\n if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;\n return res === undefined ?\n (res2 === undefined ? undefined : res2) :\n (extend(res, res2));\n };\n}\n\nexport function reverseStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n if (f2.apply(this, arguments) === false) return false;\n return f1.apply(this, arguments);\n };\n}\n\nexport function nonStoppableEventChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n f1.apply(this, arguments);\n f2.apply(this, arguments);\n };\n}\n\nexport function promisableChain(f1, f2) {\n if (f1 === nop) return f2;\n return function () {\n var res = f1.apply(this, arguments);\n if (res && typeof res.then === 'function') {\n var thiz = this,\n i = arguments.length,\n args = new Array(i);\n while (i--) args[i] = arguments[i];\n return res.then(function () {\n return f2.apply(thiz, args);\n });\n }\n return f2.apply(this, arguments);\n };\n}\n","/*\n * Copyright (c) 2014-2017 David Fahlander\n * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0\n */\nimport { _global } from '../globals/global';\nimport {tryCatch, props, setProp,\n getPropertyDescriptor, getArrayOf, extend, getProto} from '../functions/utils';\nimport {nop, callBoth, mirror} from '../functions/chaining-functions';\nimport {debug, prettyStack, getErrorWithStack} from './debug';\nimport {exceptions} from '../errors';\n\n//\n// Promise and Zone (PSD) for Dexie library\n//\n// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by\n// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.\n//\n// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another\n// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use\n// another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task\n// engine that is indexedDB compliant across all browsers.\n// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.\n// Also with inspiration from bluebird, asyncronic stacks in debug mode.\n//\n// Specific non-standard features of this Promise class:\n// * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as\n// native async / await.\n// * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame\n// and below + all promises that those promises creates or awaits.\n// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). \n//\n// David Fahlander, https://github.com/dfahlander\n//\n\n// Just a pointer that only this module knows about.\n// Used in Promise constructor to emulate a private constructor.\nvar INTERNAL = {};\n\n// Async stacks (long stacks) must not grow infinitely.\nconst\n LONG_STACKS_CLIP_LIMIT = 100,\n // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. \n MAX_LONG_STACKS = 20,\n ZONE_ECHO_LIMIT = 100,\n [resolvedNativePromise, nativePromiseProto, resolvedGlobalPromise] = typeof Promise === 'undefined' ?\n [] :\n (()=>{\n let globalP = Promise.resolve();\n if (typeof crypto === 'undefined' || !crypto.subtle)\n return [globalP, getProto(globalP), globalP];\n // Generate a native promise (as window.Promise may have been patched)\n const nativeP = crypto.subtle.digest(\"SHA-512\", new Uint8Array([0]));\n return [\n nativeP,\n getProto(nativeP),\n globalP\n ];\n })(),\n nativePromiseThen = nativePromiseProto && nativePromiseProto.then;\n\nexport const NativePromise = resolvedNativePromise && resolvedNativePromise.constructor;\nconst patchGlobalPromise = !!resolvedGlobalPromise;\n\nvar stack_being_generated = false;\n\n/* The default function used only for the very first promise in a promise chain.\n As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks\n emulated in this module. For indexedDB compatibility, this means that every method needs to \n execute at least one promise before doing an indexedDB operation. Dexie will always call \n db.ready().then() for every operation to make sure the indexedDB event is started in an\n indexedDB-compatible emulated micro task loop.\n*/\nfunction schedulePhysicalTick() {\n queueMicrotask(physicalTick);\n}\n\n// Configurable through Promise.scheduler.\n// Don't export because it would be unsafe to let unknown\n// code call it unless they do try..catch within their callback.\n// This function can be retrieved through getter of Promise.scheduler though,\n// but users must not do Promise.scheduler = myFuncThatThrowsException\nvar asap = function (callback, args) {\n microtickQueue.push([callback, args]);\n if (needsNewPhysicalTick) {\n schedulePhysicalTick();\n needsNewPhysicalTick = false;\n }\n};\n\nvar isOutsideMicroTick = true, // True when NOT in a virtual microTick.\n needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick()\n unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'.\n rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback.\n currentFulfiller = null,\n rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions\n \nexport var globalPSD = {\n id: 'global',\n global: true,\n ref: 0,\n unhandleds: [],\n onunhandled: nop,\n pgp: false,\n env: {},\n finalize: nop\n};\n\nexport var PSD = globalPSD;\n\nexport var microtickQueue = []; // Callbacks to call in this or next physical tick.\nexport var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.\nexport var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.\n\nexport default function DexiePromise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); \n this._listeners = [];\n \n // A library may set `promise._lib = true;` after promise is created to make resolve() or reject()\n // execute the microtask engine implicitely within the call to resolve() or reject().\n // To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack\n // only contains library code when calling resolve() or reject().\n // RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from\n // global scope (event handler, timer etc)!\n this._lib = false;\n // Current async scope\n var psd = (this._PSD = PSD);\n\n if (debug) {\n this._stackHolder = getErrorWithStack();\n this._prev = null;\n this._numPrev = 0; // Number of previous promises (for long stacks)\n }\n \n if (typeof fn !== 'function') {\n if (fn !== INTERNAL) throw new TypeError('Not a function');\n // Private constructor (INTERNAL, state, value).\n // Used internally by Promise.resolve() and Promise.reject().\n this._state = arguments[1];\n this._value = arguments[2];\n if (this._state === false)\n handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().\n return;\n }\n \n this._state = null; // null (=pending), false (=rejected) or true (=resolved)\n this._value = null; // error or result\n ++psd.ref; // Refcounting current scope\n executePromiseTask(this, fn);\n}\n\n// Prepare a property descriptor to put onto Promise.prototype.then\nconst thenProp = {\n get: function() {\n var psd = PSD, microTaskId = totalEchoes;\n\n function then (onFulfilled, onRejected) {\n var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes);\n const cleanup = possibleAwait && !decrementExpectedAwaits();\n var rv = new DexiePromise((resolve, reject) => {\n propagateToListener(this, new Listener(\n nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup),\n nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup),\n resolve,\n reject,\n psd));\n });\n debug && linkToPreviousPromise(rv, this);\n return rv;\n }\n\n then.prototype = INTERNAL; // For idempotense, see setter below.\n\n return then;\n },\n // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then\n // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor.\n set: function (value) {\n setProp (this, 'then', value && value.prototype === INTERNAL ?\n thenProp : // Restore to original property descriptor.\n {\n get: function(){\n return value; // Getter returning provided value (behaves like value is just changed)\n },\n set: thenProp.set // Keep a setter that is prepared to restore original.\n }\n );\n }\n};\n\nprops(DexiePromise.prototype, {\n then: thenProp, // Defined above.\n _then: function (onFulfilled, onRejected) {\n // A little tinier version of then() that don't have to create a resulting promise.\n propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); \n },\n\n catch: function (onRejected) {\n if (arguments.length === 1) return this.then(null, onRejected);\n // First argument is the Error type to catch\n var type = arguments[0],\n handler = arguments[1];\n return typeof type === 'function' ? this.then(null, err =>\n // Catching errors by its constructor type (similar to java / c++ / c#)\n // Sample: promise.catch(TypeError, function (e) { ... });\n err instanceof type ? handler(err) : PromiseReject(err))\n : this.then(null, err =>\n // Catching errors by the error.name property. Makes sense for indexedDB where error type\n // is always DOMError but where e.name tells the actual error type.\n // Sample: promise.catch('ConstraintError', function (e) { ... });\n err && err.name === type ? handler(err) : PromiseReject(err));\n },\n\n finally: function (onFinally) {\n return this.then(value => {\n onFinally();\n return value;\n }, err => {\n onFinally();\n return PromiseReject(err);\n });\n },\n \n stack: {\n get: function() {\n if (this._stack) return this._stack;\n try {\n stack_being_generated = true;\n var stacks = getStack (this, [], MAX_LONG_STACKS);\n var stack = stacks.join(\"\\nFrom previous: \");\n if (this._state !== null) this._stack = stack; // Stack may be updated on reject.\n return stack;\n } finally {\n stack_being_generated = false;\n }\n }\n },\n\n timeout: function (ms, msg) {\n return ms < Infinity ?\n new DexiePromise((resolve, reject) => {\n var handle = setTimeout(() => reject(new exceptions.Timeout(msg)), ms);\n this.then(resolve, reject).finally(clearTimeout.bind(null, handle));\n }) : this;\n }\n});\n\nif (typeof Symbol !== 'undefined' && Symbol.toStringTag)\n setProp(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.Promise');\n\n// Now that Promise.prototype is defined, we have all it takes to set globalPSD.env.\n// Environment globals snapshotted on leaving global zone\nglobalPSD.env = snapShot();\n\nfunction Listener(onFulfilled, onRejected, resolve, reject, zone) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.resolve = resolve;\n this.reject = reject;\n this.psd = zone;\n}\n\n// Promise Static Properties\nprops (DexiePromise, {\n all: function () {\n var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like.\n .map(onPossibleParallellAsync); // Handle parallell async/awaits \n return new DexiePromise(function (resolve, reject) {\n if (values.length === 0) resolve([]);\n var remaining = values.length;\n values.forEach((a,i) => DexiePromise.resolve(a).then(x => {\n values[i] = x;\n if (!--remaining) resolve(values);\n }, reject));\n });\n },\n \n resolve: value => {\n if (value instanceof DexiePromise) return value;\n if (value && typeof value.then === 'function') return new DexiePromise((resolve, reject)=>{\n value.then(resolve, reject);\n });\n var rv = new DexiePromise(INTERNAL, true, value);\n linkToPreviousPromise(rv, currentFulfiller);\n return rv;\n },\n \n reject: PromiseReject,\n \n race: function () {\n var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n values.map(value => DexiePromise.resolve(value).then(resolve, reject));\n });\n },\n\n PSD: {\n get: ()=>PSD,\n set: value => PSD = value\n },\n\n totalEchoes: {get: ()=>totalEchoes},\n\n //task: {get: ()=>task},\n \n newPSD: newScope,\n \n usePSD: usePSD,\n \n scheduler: {\n get: () => asap,\n set: value => {asap = value}\n },\n \n rejectionMapper: {\n get: () => rejectionMapper,\n set: value => {rejectionMapper = value;} // Map reject failures\n },\n \n follow: (fn, zoneProps) => {\n return new DexiePromise((resolve, reject) => {\n return newScope((resolve, reject) => {\n var psd = PSD;\n psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()\n psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.\n psd.finalize = callBoth(function () {\n // Unhandled standard or 3rd part promises are put in PSD.unhandleds and\n // examined upon scope completion while unhandled rejections in this Promise\n // will trigger directly through psd.onunhandled\n run_at_end_of_this_or_next_physical_tick(()=>{\n this.unhandleds.length === 0 ? resolve() : reject(this.unhandleds[0]);\n });\n }, psd.finalize);\n fn();\n }, zoneProps, resolve, reject);\n });\n }\n});\n\nif (NativePromise) {\n if (NativePromise.allSettled) setProp (DexiePromise, \"allSettled\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise(resolve => {\n if (possiblePromises.length === 0) resolve([]);\n let remaining = possiblePromises.length;\n const results = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => results[i] = {status: \"fulfilled\", value},\n reason => results[i] = {status: \"rejected\", reason})\n .then(()=>--remaining || resolve(results)));\n });\n });\n if (NativePromise.any && typeof AggregateError !== 'undefined') setProp(DexiePromise, \"any\", function() {\n const possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync);\n return new DexiePromise((resolve, reject) => {\n if (possiblePromises.length === 0) reject(new AggregateError([]));\n let remaining = possiblePromises.length;\n const failures = new Array(remaining);\n possiblePromises.forEach((p, i) => DexiePromise.resolve(p).then(\n value => resolve(value),\n failure => {\n failures[i] = failure;\n if (!--remaining) reject(new AggregateError(failures));\n }));\n });\n });\n}\n\n/**\n* Take a potentially misbehaving resolver function and make sure\n* onFulfilled and onRejected are only called once.\n*\n* Makes no guarantees about asynchrony.\n*/\nfunction executePromiseTask (promise, fn) {\n // Promise Resolution Procedure:\n // https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n try {\n fn(value => {\n if (promise._state !== null) return; // Already settled\n if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n if (value && typeof value.then === 'function') {\n executePromiseTask(promise, (resolve, reject) => {\n value instanceof DexiePromise ?\n value._then(resolve, reject) :\n value.then(resolve, reject);\n });\n } else {\n promise._state = true;\n promise._value = value;\n propagateAllListeners(promise);\n }\n if (shouldExecuteTick) endMicroTickScope();\n }, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below\n } catch (ex) {\n handleRejection(promise, ex);\n }\n}\n\nfunction handleRejection (promise, reason) {\n rejectingErrors.push(reason);\n if (promise._state !== null) return;\n var shouldExecuteTick = promise._lib && beginMicroTickScope();\n reason = rejectionMapper(reason);\n promise._state = false;\n promise._value = reason;\n debug && reason !== null && typeof reason === 'object' && !reason._promise && tryCatch(()=>{\n var origProp = getPropertyDescriptor(reason, \"stack\"); \n reason._promise = promise; \n setProp(reason, \"stack\", {\n get: () =>\n stack_being_generated ?\n origProp && (origProp.get ?\n origProp.get.apply(reason) :\n origProp.value) :\n promise.stack\n });\n });\n // Add the failure to a list of possibly uncaught errors\n addPossiblyUnhandledError(promise);\n propagateAllListeners(promise);\n if (shouldExecuteTick) endMicroTickScope();\n}\n\nfunction propagateAllListeners (promise) {\n //debug && linkToPreviousPromise(promise);\n var listeners = promise._listeners;\n promise._listeners = [];\n for (var i = 0, len = listeners.length; i < len; ++i) {\n propagateToListener(promise, listeners[i]);\n }\n var psd = promise._PSD;\n --psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();\n if (numScheduledCalls === 0) {\n // If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,\n // and that no deferreds where listening to this rejection or success.\n // Since there is a risk that our stack can contain application code that may\n // do stuff after this code is finished that may generate new calls, we cannot\n // call finalizers here.\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors\n }, []);\n }\n}\n\nfunction propagateToListener(promise, listener) {\n if (promise._state === null) {\n promise._listeners.push(listener);\n return;\n }\n\n var cb = promise._state ? listener.onFulfilled : listener.onRejected;\n if (cb === null) {\n // This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()\n return (promise._state ? listener.resolve : listener.reject) (promise._value);\n }\n ++listener.psd.ref;\n ++numScheduledCalls;\n asap (callListener, [cb, promise, listener]);\n}\n\nfunction callListener (cb, promise, listener) {\n try {\n // Set static variable currentFulfiller to the promise that is being fullfilled,\n // so that we connect the chain of promises (for long stacks support)\n currentFulfiller = promise;\n \n // Call callback and resolve our listener with it's return value.\n var ret, value = promise._value;\n \n if (promise._state) {\n // cb is onResolved\n ret = cb (value);\n } else {\n // cb is onRejected\n if (rejectingErrors.length) rejectingErrors = [];\n ret = cb(value);\n if (rejectingErrors.indexOf(value) === -1)\n markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.\n }\n listener.resolve(ret);\n } catch (e) {\n // Exception thrown in callback. Reject our listener.\n listener.reject(e);\n } finally {\n // Restore env and currentFulfiller.\n currentFulfiller = null;\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n --listener.psd.ref || listener.psd.finalize();\n }\n}\n\nfunction getStack (promise, stacks, limit) {\n if (stacks.length === limit) return stacks;\n var stack = \"\";\n if (promise._state === false) {\n var failure = promise._value,\n errorName,\n message;\n \n if (failure != null) {\n errorName = failure.name || \"Error\";\n message = failure.message || failure;\n stack = prettyStack(failure, 0);\n } else {\n errorName = failure; // If error is undefined or null, show that.\n message = \"\";\n }\n stacks.push(errorName + (message ? \": \" + message : \"\") + stack);\n }\n if (debug) {\n stack = prettyStack(promise._stackHolder, 2);\n if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);\n if (promise._prev) getStack(promise._prev, stacks, limit);\n }\n return stacks;\n}\n\nfunction linkToPreviousPromise(promise, prev) {\n // Support long stacks by linking to previous completed promise.\n var numPrev = prev ? prev._numPrev + 1 : 0;\n if (numPrev < LONG_STACKS_CLIP_LIMIT) { // Prohibit infinite Promise loops to get an infinite long memory consuming \"tail\".\n promise._prev = prev;\n promise._numPrev = numPrev;\n }\n}\n\n/* The callback to schedule with queueMicrotask().\n It runs a virtual microtick and executes any callback registered in microtickQueue.\n */\nfunction physicalTick() {\n usePSD(globalPSD, ()=>{\n // Make sure to reset the async context to globalPSD before\n // executing any of the microtick subscribers.\n beginMicroTickScope() && endMicroTickScope();\n });\n}\n\nexport function beginMicroTickScope() {\n var wasRootExec = isOutsideMicroTick;\n isOutsideMicroTick = false;\n needsNewPhysicalTick = false;\n return wasRootExec;\n}\n\n/* Executes micro-ticks without doing try..catch.\n This can be possible because we only use this internally and\n the registered functions are exception-safe (they do try..catch\n internally before calling any external method). If registering\n functions in the microtickQueue that are not exception-safe, this\n would destroy the framework and make it instable. So we don't export\n our asap method.\n*/\nexport function endMicroTickScope() {\n var callbacks, i, l;\n do {\n while (microtickQueue.length > 0) {\n callbacks = microtickQueue;\n microtickQueue = [];\n l = callbacks.length;\n for (i = 0; i < l; ++i) {\n var item = callbacks[i];\n item[0].apply(null, item[1]);\n }\n }\n } while (microtickQueue.length > 0);\n isOutsideMicroTick = true;\n needsNewPhysicalTick = true;\n}\n\nfunction finalizePhysicalTick() {\n var unhandledErrs = unhandledErrors;\n unhandledErrors = [];\n unhandledErrs.forEach(p => {\n p._PSD.onunhandled.call(null, p._value, p);\n });\n var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.\n var i = finalizers.length;\n while (i) finalizers[--i](); \n}\n\nfunction run_at_end_of_this_or_next_physical_tick (fn) {\n function finalizer() {\n fn();\n tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);\n }\n tickFinalizers.push(finalizer);\n ++numScheduledCalls;\n asap(()=>{\n if (--numScheduledCalls === 0) finalizePhysicalTick();\n }, []);\n}\n\nfunction addPossiblyUnhandledError(promise) {\n // Only add to unhandledErrors if not already there. The first one to add to this list\n // will be upon the first rejection so that the root cause (first promise in the\n // rejection chain) is the one listed.\n if (!unhandledErrors.some(p => p._value === promise._value))\n unhandledErrors.push(promise);\n}\n\nfunction markErrorAsHandled(promise) {\n // Called when a reject handled is actually being called.\n // Search in unhandledErrors for any promise whos _value is this promise_value (list\n // contains only rejected promises, and only one item per error)\n var i = unhandledErrors.length;\n while (i) if (unhandledErrors[--i]._value === promise._value) {\n // Found a promise that failed with this same error object pointer,\n // Remove that since there is a listener that actually takes care of it.\n unhandledErrors.splice(i, 1);\n return;\n }\n}\n\nfunction PromiseReject (reason) {\n return new DexiePromise(INTERNAL, false, reason);\n}\n\nexport function wrap (fn, errorCatcher) {\n var psd = PSD;\n return function() {\n var wasRootExec = beginMicroTickScope(),\n outerScope = PSD;\n\n try {\n switchToZone(psd, true);\n return fn.apply(this, arguments);\n } catch (e) {\n errorCatcher && errorCatcher(e);\n } finally {\n switchToZone(outerScope, false);\n if (wasRootExec) endMicroTickScope();\n }\n };\n}\n\n\n//\n// variables used for native await support\n//\nconst task = { awaits: 0, echoes: 0, id: 0}; // The ongoing macro-task when using zone-echoing.\nvar taskCounter = 0; // ID counter for macro tasks.\nvar zoneStack = []; // Stack of left zones to restore asynchronically.\nvar zoneEchoes = 0; // zoneEchoes is a must in order to persist zones between native await expressions.\nvar totalEchoes = 0; // ID counter for micro-tasks. Used to detect possible native await in our Promise.prototype.then.\n\n\nvar zone_id_counter = 0;\nexport function newScope (fn, props, a1, a2) {\n var parent = PSD,\n psd = Object.create(parent);\n psd.parent = parent;\n psd.ref = 0;\n psd.global = false;\n psd.id = ++zone_id_counter;\n // Prepare for promise patching (done in usePSD):\n var globalEnv = globalPSD.env;\n psd.env = patchGlobalPromise ? {\n Promise: DexiePromise, // Changing window.Promise could be omitted for Chrome and Edge, where IDB+Promise plays well!\n PromiseProp: {value: DexiePromise, configurable: true, writable: true},\n all: DexiePromise.all,\n race: DexiePromise.race,\n allSettled: DexiePromise.allSettled,\n any: DexiePromise.any,\n resolve: DexiePromise.resolve,\n reject: DexiePromise.reject,\n nthen: getPatchedPromiseThen (globalEnv.nthen, psd), // native then\n gthen: getPatchedPromiseThen (globalEnv.gthen, psd) // global then\n } : {};\n if (props) extend(psd, props);\n \n // unhandleds and onunhandled should not be specifically set here.\n // Leave them on parent prototype.\n // unhandleds.push(err) will push to parent's prototype\n // onunhandled() will call parents onunhandled (with this scope's this-pointer though!)\n ++parent.ref;\n psd.finalize = function () {\n --this.parent.ref || this.parent.finalize();\n }\n var rv = usePSD (psd, fn, a1, a2);\n if (psd.ref === 0) psd.finalize();\n return rv;\n}\n\n// Function to call if scopeFunc returns NativePromise\n// Also for each NativePromise in the arguments to Promise.all()\nexport function incrementExpectedAwaits() {\n if (!task.id) task.id = ++taskCounter;\n ++task.awaits;\n task.echoes += ZONE_ECHO_LIMIT;\n return task.id;\n}\n\n// Function to call when 'then' calls back on a native promise where onAwaitExpected() had been called.\n// Also call this when a native await calls then method on a promise. In that case, don't supply\n// sourceTaskId because we already know it refers to current task.\nexport function decrementExpectedAwaits() {\n if (!task.awaits) return false;\n if (--task.awaits === 0) task.id = 0;\n task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0.\n return true;\n}\n\nif ((''+nativePromiseThen).indexOf('[native code]') === -1) {\n // If the native promise' prototype is patched, we cannot rely on zone echoing.\n // Disable that here:\n incrementExpectedAwaits = decrementExpectedAwaits = nop;\n}\n\n// Call from Promise.all() and Promise.race()\nexport function onPossibleParallellAsync (possiblePromise) {\n if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) {\n incrementExpectedAwaits(); \n return possiblePromise.then(x => {\n decrementExpectedAwaits();\n return x;\n }, e => {\n decrementExpectedAwaits();\n return rejection(e);\n });\n }\n return possiblePromise;\n}\n\nfunction zoneEnterEcho(targetZone) {\n ++totalEchoes;\n //console.log(\"Total echoes \", totalEchoes);\n if (!task.echoes || --task.echoes === 0) {\n task.echoes = task.id = 0; // Cancel zone echoing.\n }\n\n zoneStack.push(PSD);\n switchToZone(targetZone, true);\n}\n\nfunction zoneLeaveEcho() {\n var zone = zoneStack[zoneStack.length-1];\n zoneStack.pop();\n switchToZone(zone, false);\n}\n\nfunction switchToZone (targetZone, bEnteringZone) {\n var currentZone = PSD;\n if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) {\n // Enter or leave zone asynchronically as well, so that tasks initiated during current tick\n // will be surrounded by the zone when they are invoked.\n queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho);\n }\n if (targetZone === PSD) return;\n\n PSD = targetZone; // The actual zone switch occurs at this line.\n\n // Snapshot on every leave from global zone.\n if (currentZone === globalPSD) globalPSD.env = snapShot();\n\n if (patchGlobalPromise) {\n // Let's patch the global and native Promises (may be same or may be different)\n var GlobalPromise = globalPSD.env.Promise;\n // Swich environments (may be PSD-zone or the global zone. Both apply.)\n var targetEnv = targetZone.env;\n\n // Change Promise.prototype.then for native and global Promise (they MAY differ on polyfilled environments, but both can be accessed)\n // Must be done on each zone change because the patched method contains targetZone in its closure.\n nativePromiseProto.then = targetEnv.nthen;\n GlobalPromise.prototype.then = targetEnv.gthen;\n\n if (currentZone.global || targetZone.global) {\n // Leaving or entering global zone. It's time to patch / restore global Promise.\n\n // Set this Promise to window.Promise so that transiled async functions will work on Firefox, Safari and IE, as well as with Zonejs and angular.\n Object.defineProperty(_global, 'Promise', targetEnv.PromiseProp);\n\n // Support Promise.all() etc to work indexedDB-safe also when people are including es6-promise as a module (they might\n // not be accessing global.Promise but a local reference to it)\n GlobalPromise.all = targetEnv.all;\n GlobalPromise.race = targetEnv.race;\n GlobalPromise.resolve = targetEnv.resolve;\n GlobalPromise.reject = targetEnv.reject;\n if (targetEnv.allSettled) GlobalPromise.allSettled = targetEnv.allSettled;\n if (targetEnv.any) GlobalPromise.any = targetEnv.any;\n }\n }\n}\n\nfunction snapShot () {\n var GlobalPromise = _global.Promise;\n return patchGlobalPromise ? {\n Promise: GlobalPromise,\n PromiseProp: Object.getOwnPropertyDescriptor(_global, \"Promise\"),\n all: GlobalPromise.all,\n race: GlobalPromise.race,\n allSettled: GlobalPromise.allSettled,\n any: GlobalPromise.any,\n resolve: GlobalPromise.resolve,\n reject: GlobalPromise.reject,\n nthen: nativePromiseProto.then,\n gthen: GlobalPromise.prototype.then\n } : {};\n}\n\nexport function usePSD (psd, fn, a1, a2, a3) {\n var outerScope = PSD;\n try {\n switchToZone(psd, true);\n return fn(a1, a2, a3);\n } finally {\n switchToZone(outerScope, false);\n }\n}\n\nfunction nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) {\n return typeof fn !== 'function' ? fn : function () {\n var outerZone = PSD;\n if (possibleAwait) incrementExpectedAwaits();\n switchToZone(zone, true);\n try {\n return fn.apply(this, arguments);\n } finally {\n switchToZone(outerZone, false);\n if (cleanup) queueMicrotask(decrementExpectedAwaits);\n }\n };\n}\n\nfunction getPatchedPromiseThen (origThen, zone) {\n return function (onResolved, onRejected) {\n return origThen.call(this,\n nativeAwaitCompatibleWrap(onResolved, zone),\n nativeAwaitCompatibleWrap(onRejected, zone));\n };\n}\n\nexport var rejection = DexiePromise.reject;\n\nexport {DexiePromise};\n","import { PSD, rejection, newScope } from \"../helpers/promise\";\nimport { DexieOptions } from \"../public/types/dexie-constructor\";\nimport { errnames, exceptions } from \"../errors\";\nimport { nop } from \"./chaining-functions\";\nimport { Transaction } from \"../classes/transaction\";\nimport { Dexie } from '../classes/dexie';\n\n/* Generate a temporary transaction when db operations are done outside a transaction scope.\n*/\nexport function tempTransaction (\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n fn: (resolve, reject, trans: Transaction) => any)\n // Last argument is \"writeLocked\". But this doesnt apply to oneshot direct db operations, so we ignore it.\n{\n if (!db.idbdb || (!db._state.openComplete && (!PSD.letThrough && !db._vip))) {\n if (db._state.openComplete) {\n // db.idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return rejection(new exceptions.DatabaseClosed(db._state.dbOpenError));\n }\n if (!db._state.isBeingOpened) {\n if (!db._options.autoOpen)\n return rejection(new exceptions.DatabaseClosed());\n db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n return db._state.dbReadyPromise.then(() => tempTransaction(db, mode, storeNames, fn));\n } else {\n var trans = db._createTransaction(mode, storeNames, db._dbSchema);\n try {\n trans.create();\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(()=>tempTransaction(db, mode, storeNames, fn));\n }\n return rejection(ex);\n }\n return trans._promise(mode, (resolve, reject) => {\n return newScope(() => { // OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.\n PSD.trans = trans;\n return fn(resolve, reject, trans);\n });\n }).then(result => {\n // Instead of resolving value directly, wait with resolving it until transaction has completed.\n // Otherwise the data would not be in the DB if requesting it in the then() operation.\n // Specifically, to ensure that the following expression will work:\n //\n // db.friends.put({name: \"Arne\"}).then(function () {\n // db.friends.where(\"name\").equals(\"Arne\").count(function(count) {\n // assert (count === 1);\n // });\n // });\n //\n if (mode === 'readwrite') try {trans.idbtrans.commit();} catch {}\n return mode === 'readonly' ? result : trans._completion.then(() => result);\n });/*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.\n trans._reject(err);\n return rejection(err);\n });*/\n }\n}\n","import { Dexie } from \"../classes/dexie\";\n\nexport const DEXIE_VERSION = '{version}'; // Replaced by build-script.\nexport const maxString = String.fromCharCode(65535);\nexport const minKey = -Infinity; // minKey can be constant. maxKey must be a prop of Dexie (_maxKey)\nexport const INVALID_KEY_ARGUMENT =\n \"Invalid key provided. Keys must be of type string, number, Date or Array.\";\nexport const STRING_EXPECTED = \"String expected.\";\nexport const connections: Dexie[] = [];\nexport const isIEOrEdge =\n typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);\nexport const hasIEDeleteObjectStoreBug = isIEOrEdge;\nexport const hangsOnDeleteLargeKeyRange = isIEOrEdge;\nexport const dexieStackFrameFilter = frame => !/(dexie\\.js|dexie\\.min\\.js)/.test(frame);\nexport const DBNAMES_DB = '__dbnames';\nexport const READONLY = 'readonly';\nexport const READWRITE = 'readwrite';\n","export function combine(filter1, filter2) {\n return filter1 ?\n filter2 ?\n function () { return filter1.apply(this, arguments) && filter2.apply(this, arguments); } :\n filter1 :\n filter2;\n}\n","import { DBCoreKeyRange, DBCoreRangeType } from '../public/types/dbcore';\n\nexport const AnyRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Any,\n lower: -Infinity,\n lowerOpen: false,\n upper: [[]],\n upperOpen: false\n}\n\nexport const NeverRange: DBCoreKeyRange = {\n type: DBCoreRangeType.Never,\n lower: -Infinity,\n lowerOpen: true,\n upper: -Infinity,\n upperOpen: true\n}\n","import { deepClone, delByKeyPath, getByKeyPath } from './utils';\n\n// This workaround is needed since obj could be a custom-class instance with an\n// uninitialized keyPath. See the following comment for more context:\n// https://github.com/dfahlander/Dexie.js/issues/1280#issuecomment-823557881\nexport function workaroundForUndefinedPrimKey(keyPath: string | ArrayLike) {\n // Workaround only needed for plain non-dotted keyPaths\n return typeof keyPath === \"string\" && !/\\./.test(keyPath) \n ? (obj: object) => {\n if (obj[keyPath] === undefined && (keyPath in obj)) {\n // property exists but is undefined. This will not be liked by Indexeddb.\n // Need to remove the property before adding it but we need to clone it before\n // doing that to not be intrusive.\n obj = deepClone(obj);\n delete obj[keyPath];\n }\n return obj;\n }\n : (obj: object) => obj;\n}","import { exceptions } from \"../../errors\";\n\nexport function Entity(){\n throw exceptions.Type();\n}\n","// Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys\n\nimport { toStringTag } from './utils';\n\n// ... with the adjustment to return NaN instead of throwing.\nexport function cmp(a: any, b: any): number {\n try {\n const ta = type(a);\n const tb = type(b);\n if (ta !== tb) {\n if (ta === 'Array') return 1;\n if (tb === 'Array') return -1;\n if (ta === 'binary') return 1;\n if (tb === 'binary') return -1;\n if (ta === 'string') return 1;\n if (tb === 'string') return -1;\n if (ta === 'Date') return 1;\n if (tb !== 'Date') return NaN;\n return -1;\n }\n switch (ta) {\n case 'number':\n case 'Date':\n case 'string':\n return a > b ? 1 : a < b ? -1 : 0;\n case 'binary': {\n return compareUint8Arrays(getUint8Array(a), getUint8Array(b));\n }\n case 'Array':\n return compareArrays(a, b);\n }\n } catch {}\n return NaN; // Return value if any given args are valid keys.\n}\n\nexport function compareArrays(a: any[], b: any[]): number {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n const res = cmp(a[i], b[i]);\n if (res !== 0) return res;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\nexport function compareUint8Arrays(\n a: Uint8Array,\n b: Uint8Array\n) {\n const al = a.length;\n const bl = b.length;\n const l = al < bl ? al : bl;\n for (let i = 0; i < l; ++i) {\n if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n }\n return al === bl ? 0 : al < bl ? -1 : 1;\n}\n\n// Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type\nfunction type(x: any) {\n const t = typeof x;\n if (t !== 'object') return t;\n if (ArrayBuffer.isView(x)) return 'binary';\n const tsTag = toStringTag(x); // Cannot use instanceof in Safari\n return tsTag === 'ArrayBuffer' ? 'binary' : (tsTag as 'Array' | 'Date');\n}\n\ntype BinaryType =\n | ArrayBuffer\n | DataView\n | Uint8ClampedArray\n | ArrayBufferView\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Float32Array\n | Float64Array;\n\nfunction getUint8Array(a: BinaryType): Uint8Array {\n if (a instanceof Uint8Array) return a;\n if (ArrayBuffer.isView(a))\n // TypedArray or DataView\n return new Uint8Array(a.buffer, a.byteOffset, a.byteLength);\n return new Uint8Array(a); // ArrayBuffer\n}\n","import { BulkError, exceptions } from '../../errors';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { DexiePromise as Promise, PSD, newScope, rejection, beginMicroTickScope, endMicroTickScope } from '../../helpers/promise';\nimport { Transaction } from '../transaction';\nimport { Dexie } from '../dexie';\nimport { tempTransaction } from '../../functions/temp-transaction';\nimport { Collection } from '../collection';\nimport { isArray, keys, getByKeyPath, setByKeyPath, extend, getProto } from '../../functions/utils';\nimport { maxString } from '../../globals/constants';\nimport { combine } from '../../functions/combine';\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { IndexableType } from '../../public/types/indexable-type';\nimport { debug } from '../../helpers/debug';\nimport { DBCoreTable } from '../../public/types/dbcore';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { workaroundForUndefinedPrimKey } from '../../functions/workaround-undefined-primkey';\nimport { Entity } from '../entity/Entity';\nimport { UpdateSpec } from '../../public';\nimport { cmp } from '../../functions/cmp';\n\n/** class Table\n * \n * https://dexie.org/docs/Table/Table\n */\nexport class Table implements ITable {\n db: Dexie;\n _tx?: Transaction;\n name: string;\n schema: TableSchema;\n hook: TableHooks;\n core: DBCoreTable;\n\n _trans(\n mode: IDBTransactionMode,\n fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike | void,\n writeLocked?: boolean | string) : PromiseExtended\n {\n const trans: Transaction = this._tx || PSD.trans;\n const tableName = this.name;\n \n function checkTableInTransaction(resolve, reject, trans: Transaction) {\n if (!trans.schema[tableName])\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\");\n return fn(trans.idbtrans, trans);\n }\n // Surround all in a microtick scope.\n // Reason: Browsers (modern Safari + older others)\n // still as of 2018-10-10 has problems keeping a transaction\n // alive between micro ticks. Safari because if transaction\n // is created but not used in same microtick, it will go\n // away. That specific issue could be solved in DBCore\n // by opening the transaction just before using it instead.\n // But older Firefoxes and IE11 (with Promise polyfills)\n // will still have probs.\n // The beginMicrotickScope()/endMicrotickScope() works\n // in cooperation with Dexie.Promise to orchestrate\n // the micro-ticks in endMicrotickScope() rather than\n // in native engine.\n const wasRootExec = beginMicroTickScope();\n try {\n return trans && trans.db._novip === this.db._novip ?\n trans === PSD.trans ?\n trans._promise(mode, checkTableInTransaction, writeLocked) :\n newScope(() => trans._promise(mode, checkTableInTransaction, writeLocked), { trans: trans, transless: PSD.transless || PSD }) :\n tempTransaction(this.db, mode, [this.name], checkTableInTransaction);\n } finally {\n if (wasRootExec) endMicroTickScope();\n }\n }\n\n /** Table.get()\n * \n * https://dexie.org/docs/Table/Table.get()\n * \n **/\n get(keyOrCrit, cb?) {\n if (keyOrCrit && keyOrCrit.constructor === Object)\n return this.where(keyOrCrit as { [key: string]: IndexableType }).first(cb);\n\n return this._trans('readonly', (trans) => {\n return this.core.get({trans, key: keyOrCrit})\n .then(res => this.hook.reading.fire(res));\n }).then(cb);\n }\n\n /** Table.where()\n * \n * https://dexie.org/docs/Table/Table.where()\n * \n **/\n where(indexOrCrit: string | string[] | { [key: string]: IndexableType }) {\n if (typeof indexOrCrit === 'string')\n return new this.db.WhereClause(this, indexOrCrit);\n if (isArray(indexOrCrit))\n return new this.db.WhereClause(this, `[${indexOrCrit.join('+')}]`);\n // indexOrCrit is an object map of {[keyPath]:value} \n const keyPaths = keys(indexOrCrit);\n if (keyPaths.length === 1)\n // Only one critera. This was the easy case:\n return this\n .where(keyPaths[0])\n .equals(indexOrCrit[keyPaths[0]]);\n\n // Multiple criterias.\n // Let's try finding a compound index that matches all keyPaths in\n // arbritary order:\n const compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(ix => {\n if (\n ix.compound &&\n keyPaths.every(keyPath => ix.keyPath.indexOf(keyPath) >= 0)) {\n for (let i=0; i a.keyPath.length - b.keyPath.length)[0];\n \n if (compoundIndex && this.db._maxKey !== maxString) {\n // Cool! We found such compound index\n // and this browser supports compound indexes (maxKey !== maxString)!\n const keyPathsInValidOrder = (compoundIndex.keyPath as string[]).slice(0, keyPaths.length);\n return this\n .where(keyPathsInValidOrder)\n .equals(keyPathsInValidOrder.map(kp => indexOrCrit[kp]));\n }\n\n if (!compoundIndex && debug) console.warn(\n `The query ${JSON.stringify(indexOrCrit)} on ${this.name} would benefit of a ` +\n `compound index [${keyPaths.join('+')}]`);\n\n // Ok, now let's fallback to finding at least one matching index\n // and filter the rest.\n const { idxByName } = this.schema;\n const idb = this.db._deps.indexedDB;\n\n function equals (a, b) {\n return idb.cmp(a,b) === 0; // Works with all indexable types including binary keys.\n }\n\n const [idx, filterFunction] = keyPaths.reduce(([prevIndex, prevFilterFn], keyPath) => {\n const index = idxByName[keyPath];\n const value = indexOrCrit[keyPath];\n return [\n prevIndex || index, // idx::=Pick index of first matching keypath\n prevIndex || !index ? // filter::=null if not needed, otherwise combine function filter\n combine(\n prevFilterFn,\n index && index.multi ?\n x => {\n const prop = getByKeyPath(x, keyPath);\n return isArray(prop) && prop.some(item => equals(value, item));\n } : x => equals(value, getByKeyPath(x, keyPath)))\n : prevFilterFn\n ];\n }, [null, null]);\n\n return idx ?\n this.where(idx.name).equals(indexOrCrit[idx.keyPath])\n .filter(filterFunction) :\n compoundIndex ?\n this.filter(filterFunction) : // Has compound but browser bad. Allow filter.\n this.where(keyPaths).equals(''); // No index at all. Fail lazily with \"[a+b+c] is not indexed\"\n }\n\n /** Table.filter()\n * \n * https://dexie.org/docs/Table/Table.filter()\n * \n **/\n filter(filterFunction: (obj: any) => boolean) {\n return this.toCollection().and(filterFunction);\n }\n\n /** Table.count()\n * \n * https://dexie.org/docs/Table/Table.count()\n * \n **/\n count(thenShortcut?: any) {\n return this.toCollection().count(thenShortcut);\n }\n\n /** Table.offset()\n * \n * https://dexie.org/docs/Table/Table.offset()\n * \n **/\n offset(offset: number) {\n return this.toCollection().offset(offset);\n }\n\n /** Table.limit()\n * \n * https://dexie.org/docs/Table/Table.limit()\n * \n **/\n limit(numRows: number) {\n return this.toCollection().limit(numRows);\n }\n\n /** Table.each()\n * \n * https://dexie.org/docs/Table/Table.each()\n * \n **/\n each(callback: (obj: any, cursor: { key: IndexableType, primaryKey: IndexableType }) => any) {\n return this.toCollection().each(callback);\n }\n\n /** Table.toArray()\n * \n * https://dexie.org/docs/Table/Table.toArray()\n * \n **/\n toArray(thenShortcut?: any) {\n return this.toCollection().toArray(thenShortcut);\n }\n\n /** Table.toCollection()\n * \n * https://dexie.org/docs/Table/Table.toCollection()\n * \n **/\n toCollection() {\n return new this.db.Collection(new this.db.WhereClause(this));\n }\n\n /** Table.orderBy()\n * \n * https://dexie.org/docs/Table/Table.orderBy()\n * \n **/\n orderBy(index: string | string[]) {\n return new this.db.Collection(\n new this.db.WhereClause(this, isArray(index) ?\n `[${index.join('+')}]` :\n index));\n }\n\n /** Table.reverse()\n * \n * https://dexie.org/docs/Table/Table.reverse()\n * \n **/\n reverse(): Collection {\n return this.toCollection().reverse();\n }\n\n /** Table.mapToClass()\n * \n * https://dexie.org/docs/Table/Table.mapToClass()\n * \n **/\n mapToClass(constructor: Function) {\n const {db, name: tableName} = this;\n this.schema.mappedClass = constructor;\n if (constructor.prototype instanceof Entity) {\n constructor = class extends (constructor as any) {\n get db () { return db; }\n table() { return tableName; }\n }\n }\n // Collect all inherited property names (including method names) by\n // walking the prototype chain. This is to avoid overwriting them from\n // database data - so application code can rely on inherited props never\n // becoming shadowed by database object props.\n const inheritedProps = new Set();\n for (let proto = constructor.prototype; proto; proto = getProto(proto)) {\n Object.getOwnPropertyNames(proto).forEach(propName => inheritedProps.add(propName));\n }\n \n // Now, subscribe to the when(\"reading\") event to make all objects that come out from this table inherit from given class\n // no matter which method to use for reading (Table.get() or Table.where(...)... )\n const readHook = (obj: Object) => {\n if (!obj) return obj; // No valid object. (Value is null or undefined). Return as is.\n // Create a new object that derives from constructor:\n const res = Object.create(constructor.prototype);\n // Clone members (but never those that collide with a property in the prototype\n // hierchary (MUST BE ABLE TO RELY ON Entity methods and props!)):\n for (let m in obj) if (!inheritedProps.has(m)) try { res[m] = obj[m]; } catch (_) { }\n return res;\n };\n\n if (this.schema.readHook) {\n this.hook.reading.unsubscribe(this.schema.readHook);\n }\n this.schema.readHook = readHook;\n this.hook(\"reading\", readHook);\n return constructor;\n }\n\n /** @deprecated */\n defineClass() {\n function Class (content){\n extend(this, content);\n };\n return this.mapToClass(Class);\n }\n\n /** Table.add()\n * \n * https://dexie.org/docs/Table/Table.add()\n * \n **/\n add(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'add', keys: key != null ? [key] : null, values: [objToAdd]});\n }).then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.update()\n * \n * https://dexie.org/docs/Table/Table.update()\n * \n **/\n update(keyOrObject, modifications: { [keyPath: string]: any; } | ((obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean)): PromiseExtended {\n if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {\n const key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);\n if (key === undefined) return rejection(new exceptions.InvalidArgument(\n \"Given object does not contain its primary key\"));\n /*// object to modify. Also modify given object with the modifications:\n // This part should be here for backward compatibility.\n // If ever feeling too bad about mutating given object, please wait to a new major before removing it,\n // and document the change thoroughly. TODO: Document this change!\n if (!Object.isFrozen(keyOrObject)) try {\n if (typeof modifications !== \"function\") {\n keys(modifications).forEach(keyPath => {\n setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);\n });\n } else {\n // Now since we support function argument, we should have a similar behavior here as well\n // (as long as we do this mutability stuff on the given object)\n modifications(keyOrObject, {value: keyOrObject, primKey: key});\n }\n } catch {\n // Maybe given object was frozen.\n // This part is not essential. Just move on as nothing happened...\n }*/\n return this.where(\":id\").equals(key).modify(modifications);\n } else {\n // key to modify\n return this.where(\":id\").equals(keyOrObject).modify(modifications);\n }\n }\n\n /** Table.put()\n * \n * https://dexie.org/docs/Table/Table.put()\n * \n **/\n put(obj, key?: IndexableType): PromiseExtended {\n const {auto, keyPath} = this.schema.primKey;\n let objToAdd = obj;\n if (keyPath && auto) {\n objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj);\n }\n return this._trans(\n 'readwrite',\n trans => this.core.mutate({trans, type: 'put', values: [objToAdd], keys: key != null ? [key] : null}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : res.lastResult)\n .then(lastResult => {\n if (keyPath) {\n // This part should be here for backward compatibility.\n // If ever feeling too bad about this, please wait to a new major before removing it,\n // and document the change thoroughly.\n try{setByKeyPath(obj, keyPath, lastResult);}catch(_){};\n }\n return lastResult;\n });\n }\n\n /** Table.delete()\n * \n * https://dexie.org/docs/Table/Table.delete()\n * \n **/\n delete(key: IndexableType): PromiseExtended {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'delete', keys: [key]}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.clear()\n * \n * https://dexie.org/docs/Table/Table.clear()\n * \n **/\n clear() {\n return this._trans('readwrite',\n trans => this.core.mutate({trans, type: 'deleteRange', range: AnyRange}))\n .then(res => res.numFailures ? Promise.reject(res.failures[0]) : undefined);\n }\n\n /** Table.bulkGet()\n * \n * https://dexie.org/docs/Table/Table.bulkGet()\n * \n * @param keys \n */\n bulkGet(keys: IndexableType[]) {\n return this._trans('readonly', trans => {\n return this.core.getMany({\n keys,\n trans\n }).then(result => result.map(res => this.hook.reading.fire(res)));\n });\n }\n\n /** Table.bulkAdd()\n * \n * https://dexie.org/docs/Table/Table.bulkAdd()\n * \n **/\n bulkAdd(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkAdd(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToAdd = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n return this.core.mutate(\n {trans, type: 'add', keys: keys as IndexableType[], values: objectsToAdd, wantResults}\n )\n .then(({numFailures, results,lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkAdd(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkPut()\n * \n * https://dexie.org/docs/Table/Table.bulkPut()\n * \n **/\n bulkPut(\n objects: readonly any[],\n keysOrOptions?: ReadonlyArray | { allKeys?: boolean },\n options?: { allKeys?: boolean }\n ) { \n const keys = Array.isArray(keysOrOptions) ? keysOrOptions : undefined;\n options = options || (keys ? undefined : keysOrOptions as { allKeys?: boolean });\n const wantResults = options ? options.allKeys : undefined;\n\n return this._trans('readwrite', trans => {\n const {auto, keyPath} = this.schema.primKey;\n if (keyPath && keys)\n throw new exceptions.InvalidArgument(\"bulkPut(): keys argument invalid on tables with inbound keys\");\n if (keys && keys.length !== objects.length)\n throw new exceptions.InvalidArgument(\"Arguments objects and keys must have the same length\");\n\n const numObjects = objects.length; // Pick length here to allow garbage collection of objects later\n let objectsToPut = keyPath && auto ?\n objects.map(workaroundForUndefinedPrimKey(keyPath)) :\n objects;\n\n return this.core.mutate(\n {trans, type: 'put', keys: keys as IndexableType[], values: objectsToPut, wantResults}\n )\n .then(({numFailures, results, lastResult, failures}) => {\n const result = wantResults ? results : lastResult;\n if (numFailures === 0) return result;\n throw new BulkError(\n `${this.name}.bulkPut(): ${numFailures} of ${numObjects} operations failed`, failures);\n });\n });\n }\n\n /** Table.bulkUpdate()\n *\n * https://dexie.org/docs/Table.Table.bulkUpdate()\n */\n bulkUpdate(\n keysAndChanges: readonly { key: any; changes: UpdateSpec }[]\n ): PromiseExtended {\n const coreTable = this.core;\n const keys = keysAndChanges.map((entry) => entry.key);\n const changeSpecs = keysAndChanges.map((entry) => entry.changes);\n const offsetMap: number[] = [];\n return this._trans('readwrite', (trans) => {\n return coreTable.getMany({ trans, keys, cache: 'clone' }).then((objs) => {\n const resultKeys: any[] = [];\n const resultObjs: any[] = [];\n keysAndChanges.forEach(({ key, changes }, idx) => {\n const obj = objs[idx];\n if (obj) {\n for (const keyPath of Object.keys(changes)) {\n const value = changes[keyPath];\n if (keyPath === this.schema.primKey.keyPath) {\n if (cmp(value, key) !== 0) {\n throw new exceptions.Constraint(\n `Cannot update primary key in bulkUpdate()`\n );\n }\n } else {\n setByKeyPath(obj, keyPath, value);\n }\n }\n offsetMap.push(idx);\n resultKeys.push(key);\n resultObjs.push(obj);\n }\n });\n const numEntries = resultKeys.length;\n return coreTable\n .mutate({\n trans,\n type: 'put',\n keys: resultKeys,\n values: resultObjs,\n updates: {\n keys,\n changeSpecs\n }\n })\n .then(({ numFailures, failures }) => {\n if (numFailures === 0) return numEntries;\n // Failure. bulkPut() may have a subset of keys\n // so we must translate returned 'failutes' into the offsets of given argument:\n for (const offset of Object.keys(failures)) {\n const mappedOffset = offsetMap[Number(offset)];\n if (mappedOffset != null) {\n const failure = failures[offset];\n delete failures[offset];\n failures[mappedOffset] = failure;\n }\n }\n throw new BulkError(\n `${this.name}.bulkUpdate(): ${numFailures} of ${numEntries} operations failed`,\n failures\n );\n });\n });\n });\n }\n\n /** Table.bulkDelete()\n * \n * https://dexie.org/docs/Table/Table.bulkDelete()\n * \n **/\n bulkDelete(keys: ReadonlyArray): PromiseExtended {\n const numKeys = keys.length;\n return this._trans('readwrite', trans => {\n return this.core.mutate({trans, type: 'delete', keys: keys as IndexableType[]});\n }).then(({numFailures, lastResult, failures}) => {\n if (numFailures === 0) return lastResult;\n throw new BulkError(\n `${this.name}.bulkDelete(): ${numFailures} of ${numKeys} operations failed`, failures);\n });\n }\n}\n","import {keys, isArray, asap} from '../functions/utils';\nimport {nop, mirror, reverseStoppableEventChain} from '../functions/chaining-functions';\nimport {exceptions} from '../errors';\n\nexport default function Events(ctx) {\n var evs = {};\n var rv = function (eventName, subscriber) {\n if (subscriber) {\n // Subscribe. If additional arguments than just the subscriber was provided, forward them as well.\n var i = arguments.length, args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n evs[eventName].subscribe.apply(null, args);\n return ctx;\n } else if (typeof (eventName) === 'string') {\n // Return interface allowing to fire or unsubscribe from event\n return evs[eventName];\n }\n };\n rv.addEventType = add;\n \n for (var i = 1, l = arguments.length; i < l; ++i) {\n add(arguments[i]);\n }\n \n return rv;\n\n function add(eventName, chainFunction, defaultFunction) {\n if (typeof eventName === 'object') return addConfiguredEvents(eventName);\n if (!chainFunction) chainFunction = reverseStoppableEventChain;\n if (!defaultFunction) defaultFunction = nop;\n\n var context = {\n subscribers: [],\n fire: defaultFunction,\n subscribe: function (cb) {\n if (context.subscribers.indexOf(cb) === -1) {\n context.subscribers.push(cb);\n context.fire = chainFunction(context.fire, cb);\n }\n },\n unsubscribe: function (cb) {\n context.subscribers = context.subscribers.filter(function (fn) { return fn !== cb; });\n context.fire = context.subscribers.reduce(chainFunction, defaultFunction);\n }\n };\n evs[eventName] = rv[eventName] = context;\n return context;\n }\n\n function addConfiguredEvents(cfg) {\n // events(this, {reading: [functionChain, nop]});\n keys(cfg).forEach(function (eventName) {\n var args = cfg[eventName];\n if (isArray(args)) {\n add(eventName, cfg[eventName][0], cfg[eventName][1]);\n } else if (args === 'asap') {\n // Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack\n // enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.\n var context = add(eventName, mirror, function fire() {\n // Optimazation-safe cloning of arguments into args.\n var i = arguments.length, args = new Array(i);\n while (i--) args[i] = arguments[i];\n // All each subscriber:\n context.subscribers.forEach(function (fn) {\n asap(function fireEvent() {\n fn.apply(null, args);\n });\n });\n });\n } else throw new exceptions.InvalidArgument(\"Invalid event config\");\n });\n }\n}\n","import { arrayToObject, derive } from './utils';\n\n\nexport function makeClassConstructor (prototype: Object, constructor: Function) {\n /*const propertyDescriptorMap = arrayToObject(\n Object.getOwnPropertyNames(prototype),\n propKey => [propKey, Object.getOwnPropertyDescriptor(prototype, propKey)]);\n\n // Both derive and clone the prototype.\n // derive: So that x instanceof T returns true when T is the class template.\n // clone: Optimizes method access a bit (but actually not nescessary)\n const derivedPrototypeClone = Object.create(prototype, propertyDescriptorMap);\n derivedPrototypeClone.constructor = constructor;\n constructor.prototype = derivedPrototypeClone;\n return constructor as any as TConstructor;*/\n\n // Keep the above code in case we want to clone AND derive the parent prototype.\n // Reason would be optimization of property access.\n // The code below will only create a prototypal inheritance from given constructor function\n // to given prototype.\n derive(constructor).from({prototype});\n return constructor as any as TConstructor; \n}\n","import { Dexie } from '../dexie';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { Transaction } from '../transaction/transaction';\nimport { hookCreatingChain, pureFunctionChain, nop, mirror, hookUpdatingChain, hookDeletingChain } from '../../functions/chaining-functions';\nimport { TableHooks } from '../../public/types/table-hooks';\nimport { Table } from './table';\nimport Events from '../../helpers/Events';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\n\nexport interface TableConstructor {\n new (name: string, tableSchema: TableSchema, optionalTrans?: Transaction) : Table;\n prototype: Table;\n}\n\n/** Generates a Table constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTableConstructor (db: Dexie) {\n return makeClassConstructor(\n Table.prototype,\n\n function Table (this: Table, name: string, tableSchema: TableSchema, trans?: Transaction) {\n this.db = db;\n this._tx = trans;\n this.name = name;\n this.schema = tableSchema;\n this.hook = db._allTables[name] ? db._allTables[name].hook : Events(null, {\n \"creating\": [hookCreatingChain, nop],\n \"reading\": [pureFunctionChain, mirror],\n \"updating\": [hookUpdatingChain, nop],\n \"deleting\": [hookDeletingChain, nop]\n }) as TableHooks;\n }\n\n );\n}\n","import { combine } from \"../../functions/combine\";\nimport { exceptions } from \"../../errors\";\nimport { hasOwn } from \"../../functions/utils\";\nimport { wrap } from \"../../helpers/promise\";\nimport { Collection } from './';\nimport { DBCoreCursor, DBCoreTable, DBCoreTransaction, DBCoreTableSchema, DBCoreRangeType } from '../../public/types/dbcore';\nimport { nop } from '../../functions/chaining-functions';\n\ntype CollectionContext = Collection[\"_ctx\"];\n\nexport function isPlainKeyRange (ctx: CollectionContext, ignoreLimitFilter?: boolean) {\n return !(ctx.filter || ctx.algorithm || ctx.or) &&\n (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);\n} \n\nexport function addFilter(ctx: CollectionContext, fn: Function) {\n ctx.filter = combine(ctx.filter, fn);\n}\n\nexport function addReplayFilter (ctx: CollectionContext, factory, isLimitFilter?) {\n var curr = ctx.replayFilter;\n ctx.replayFilter = curr ? ()=>combine(curr(), factory()) : factory;\n ctx.justLimit = isLimitFilter && !curr;\n}\n\nexport function addMatchFilter(ctx: CollectionContext, fn) {\n ctx.isMatch = combine(ctx.isMatch, fn);\n}\n\nexport function getIndexOrStore(ctx: CollectionContext, coreSchema: DBCoreTableSchema) {\n // TODO: Rewrite this. No need to know ctx.isPrimKey. ctx.index should hold the keypath.\n // Still, throw if not found!\n if (ctx.isPrimKey) return coreSchema.primaryKey;\n const index = coreSchema.getIndexByKeyPath(ctx.index);\n if (!index) throw new exceptions.Schema(\"KeyPath \" + ctx.index + \" on object store \" + coreSchema.name + \" is not indexed\");\n return index;\n}\n\nexport function openCursor(ctx: CollectionContext, coreTable: DBCoreTable, trans: DBCoreTransaction) {\n const index = getIndexOrStore(ctx, coreTable.schema);\n return coreTable.openCursor({\n trans,\n values: !ctx.keysOnly,\n reverse: ctx.dir === 'prev',\n unique: !!ctx.unique,\n query: {\n index, \n range: ctx.range\n }\n });\n}\n\nexport function iter (\n ctx: CollectionContext, \n fn: (item, cursor: DBCoreCursor, advance: Function)=>void,\n coreTrans: DBCoreTransaction,\n coreTable: DBCoreTable): Promise\n{\n const filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;\n if (!ctx.or) {\n return iterate(\n openCursor(ctx, coreTable, coreTrans),\n combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper);\n } else {\n const set = {};\n\n const union = (item: any, cursor: DBCoreCursor, advance) => {\n if (!filter || filter(cursor, advance, result=>cursor.stop(result), err => cursor.fail(err))) {\n var primaryKey = cursor.primaryKey;\n var key = '' + primaryKey;\n if (key === '[object ArrayBuffer]') key = '' + new Uint8Array(primaryKey);\n if (!hasOwn(set, key)) {\n set[key] = true;\n fn(item, cursor, advance);\n }\n }\n }\n\n return Promise.all([\n ctx.or._iterate(union, coreTrans),\n iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper)\n ]);\n }\n}\n\nfunction iterate(cursorPromise: Promise, filter, fn, valueMapper): Promise {\n \n // Apply valueMapper (hook('reading') or mappped class)\n var mappedFn = valueMapper ? (x,c,a) => fn(valueMapper(x),c,a) : fn;\n // Wrap fn with PSD and microtick stuff from Promise.\n var wrappedFn = wrap(mappedFn);\n \n return cursorPromise.then(cursor => {\n if (cursor) {\n return cursor.start(()=>{\n var c = ()=>cursor.continue();\n if (!filter || filter(cursor, advancer => c = advancer, val=>{cursor.stop(val);c=nop}, e => {cursor.fail(e);c = nop;}))\n wrappedFn(cursor.value, cursor, advancer => c = advancer);\n c();\n });\n }\n });\n}\n","import { Collection as ICollection } from \"../../public/types/collection\";\nimport { Dexie } from \"../dexie\";\nimport { Table } from \"../table\";\nimport { IndexableType, IndexableTypeArrayReadonly } from \"../../public/types/indexable-type\";\nimport { PromiseExtended } from \"../../public/types/promise-extended\";\nimport { iter, isPlainKeyRange, getIndexOrStore, addReplayFilter, addFilter, addMatchFilter } from \"./collection-helpers\";\nimport { rejection } from \"../../helpers/promise\";\nimport { combine } from \"../../functions/combine\";\nimport { extend, hasOwn, deepClone, keys, setByKeyPath, getByKeyPath } from \"../../functions/utils\";\nimport { ModifyError } from \"../../errors\";\nimport { hangsOnDeleteLargeKeyRange } from \"../../globals/constants\";\nimport { ThenShortcut } from \"../../public/types/then-shortcut\";\nimport { Transaction } from '../transaction';\nimport { DBCoreCursor, DBCoreTransaction, DBCoreRangeType, DBCoreMutateResponse, DBCoreKeyRange } from '../../public/types/dbcore';\nimport { cmp } from \"../../functions/cmp\";\n\n/** class Collection\n * \n * https://dexie.org/docs/Collection/Collection\n */\nexport class Collection implements ICollection {\n db: Dexie;\n _ctx: {\n table: Table;\n index?: string | null;\n isPrimKey?: boolean;\n range: DBCoreKeyRange;\n keysOnly: boolean;\n dir: \"next\" | \"prev\";\n unique: \"\" | \"unique\";\n algorithm?: Function | null;\n filter?: Function | null;\n replayFilter: Function | null;\n justLimit: boolean; // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: Function | null;\n offset: number,\n limit: number,\n error: any, // If set, any promise must be rejected with this error\n or: Collection,\n valueMapper: (any) => any\n }\n \n _ondirectionchange?: Function;\n\n _read(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike, cb?): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readonly', fn).then(cb);\n }\n\n _write(fn: (idbtrans: IDBTransaction, dxTrans: Transaction) => PromiseLike): PromiseExtended {\n var ctx = this._ctx;\n return ctx.error ?\n ctx.table._trans(null, rejection.bind(null, ctx.error)) :\n ctx.table._trans('readwrite', fn, \"locked\"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.\n }\n\n _addAlgorithm(fn) {\n var ctx = this._ctx;\n ctx.algorithm = combine(ctx.algorithm, fn);\n }\n\n _iterate(\n fn: (item, cursor: DBCoreCursor, advance: Function) => void,\n coreTrans: DBCoreTransaction) : Promise\n {\n return iter(this._ctx, fn, coreTrans, this._ctx.table.core);\n }\n\n /** Collection.clone()\n * \n * https://dexie.org/docs/Collection/Collection.clone()\n * \n **/\n clone(props?) {\n var rv = Object.create(this.constructor.prototype),\n ctx = Object.create(this._ctx);\n if (props) extend(ctx, props);\n rv._ctx = ctx;\n return rv;\n }\n\n /** Collection.raw()\n * \n * https://dexie.org/docs/Collection/Collection.raw()\n * \n **/\n raw() {\n this._ctx.valueMapper = null;\n return this;\n }\n\n /** Collection.each()\n * \n * https://dexie.org/docs/Collection/Collection.each()\n * \n **/\n each(fn: (obj, cursor: DBCoreCursor) => any): PromiseExtended {\n var ctx = this._ctx;\n\n return this._read(trans => iter(ctx, fn, trans, ctx.table.core));\n }\n\n /** Collection.count()\n * \n * https://dexie.org/docs/Collection/Collection.count()\n * \n **/\n count(cb?) {\n return this._read(trans => {\n const ctx = this._ctx;\n const coreTable = ctx.table.core;\n if (isPlainKeyRange(ctx, true)) {\n // This is a plain key range. We can use the count() method if the index.\n return coreTable.count({\n trans,\n query: {\n index: getIndexOrStore(ctx, coreTable.schema),\n range: ctx.range\n }\n }).then(count => Math.min(count, ctx.limit));\n } else {\n // Algorithms, filters or expressions are applied. Need to count manually.\n var count = 0;\n return iter(ctx, () => { ++count; return false; }, trans, coreTable)\n .then(()=>count);\n }\n }).then(cb);\n }\n\n /** Collection.sortBy()\n * \n * https://dexie.org/docs/Collection/Collection.sortBy()\n * \n **/\n sortBy(keyPath: string): PromiseExtended;\n sortBy(keyPath: string, thenShortcut: ThenShortcut) : PromiseExtended;\n sortBy(keyPath: string, cb?: ThenShortcut) {\n const parts = keyPath.split('.').reverse(),\n lastPart = parts[0],\n lastIndex = parts.length - 1;\n function getval(obj, i) {\n if (i) return getval(obj[parts[i]], i - 1);\n return obj[lastPart];\n }\n var order = this._ctx.dir === \"next\" ? 1 : -1;\n\n function sorter(a, b) {\n var aVal = getval(a, lastIndex),\n bVal = getval(b, lastIndex);\n return aVal < bVal ? -order : aVal > bVal ? order : 0;\n }\n return this.toArray(function (a) {\n return a.sort(sorter);\n }).then(cb);\n }\n\n /** Collection.toArray()\n * \n * https://dexie.org/docs/Collection/Collection.toArray()\n * \n **/\n toArray(cb?): PromiseExtended {\n return this._read(trans => {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAll() or\n // IDBKeyRange.getAll():\n const {valueMapper} = ctx;\n const index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n limit: ctx.limit,\n values: true,\n query: {\n index,\n range: ctx.range\n }\n }).then(({result}) => valueMapper ? result.map(valueMapper) : result);\n } else {\n // Getting array through a cursor.\n const a = [];\n return iter(ctx, item => a.push(item), trans, ctx.table.core).then(()=>a);\n }\n }, cb);\n }\n\n /** Collection.offset()\n * \n * https://dexie.org/docs/Collection/Collection.offset()\n * \n **/\n offset(offset: number) : Collection{\n var ctx = this._ctx;\n if (offset <= 0) return this;\n ctx.offset += offset; // For count()\n if (isPlainKeyRange(ctx)) {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return (cursor, advance) => {\n if (offsetLeft === 0) return true;\n if (offsetLeft === 1) { --offsetLeft; return false; }\n advance(() => {\n cursor.advance(offsetLeft);\n offsetLeft = 0;\n });\n return false;\n };\n });\n } else {\n addReplayFilter(ctx, () => {\n var offsetLeft = offset;\n return () => (--offsetLeft < 0);\n });\n }\n return this;\n }\n\n /** Collection.limit()\n * \n * https://dexie.org/docs/Collection/Collection.limit()\n * \n **/\n limit(numRows: number) : Collection {\n this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()\n addReplayFilter(this._ctx, () => {\n var rowsLeft = numRows;\n return function (cursor, advance, resolve) {\n if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included\n return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.\n };\n }, true);\n return this;\n }\n\n /** Collection.until()\n * \n * https://dexie.org/docs/Collection/Collection.until()\n * \n **/\n until(filterFunction: (x) => boolean, bIncludeStopEntry?) {\n addFilter(this._ctx, function (cursor, advance, resolve) {\n if (filterFunction(cursor.value)) {\n advance(resolve);\n return bIncludeStopEntry;\n } else {\n return true;\n }\n });\n return this;\n }\n\n /** Collection.first()\n * \n * https://dexie.org/docs/Collection/Collection.first()\n * \n **/\n first(cb?) {\n return this.limit(1).toArray(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.last()\n * \n * https://dexie.org/docs/Collection/Collection.last()\n * \n **/\n last(cb?) {\n return this.reverse().first(cb);\n }\n\n /** Collection.filter()\n * \n * https://dexie.org/docs/Collection/Collection.filter()\n * \n **/\n filter(filterFunction: (x) => boolean): Collection {\n /// function(val){return true/false}\n addFilter(this._ctx, function (cursor) {\n return filterFunction(cursor.value);\n });\n // match filters not used in Dexie.js but can be used by 3rd part libraries to test a\n // collection for a match without querying DB. Used by Dexie.Observable.\n addMatchFilter(this._ctx, filterFunction);\n return this;\n }\n\n /** Collection.and()\n * \n * https://dexie.org/docs/Collection/Collection.and()\n * \n **/\n and(filter: (x) => boolean) {\n return this.filter(filter);\n }\n\n /** Collection.or()\n * \n * https://dexie.org/docs/Collection/Collection.or()\n * \n **/\n or(indexName: string) {\n return new this.db.WhereClause(this._ctx.table, indexName, this);\n }\n\n /** Collection.reverse()\n * \n * https://dexie.org/docs/Collection/Collection.reverse()\n * \n **/\n reverse() {\n this._ctx.dir = (this._ctx.dir === \"prev\" ? \"next\" : \"prev\");\n if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);\n return this;\n }\n\n /** Collection.desc()\n * \n * https://dexie.org/docs/Collection/Collection.desc()\n * \n **/\n desc() {\n return this.reverse();\n }\n\n /** Collection.eachKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachKey()\n * \n **/\n eachKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.key, cursor); });\n }\n\n /** Collection.eachUniqueKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachUniqueKey()\n * \n **/\n eachUniqueKey(cb?) {\n this._ctx.unique = \"unique\";\n return this.eachKey(cb);\n }\n\n /** Collection.eachPrimaryKey()\n * \n * https://dexie.org/docs/Collection/Collection.eachPrimaryKey()\n * \n **/\n eachPrimaryKey(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n return this.each(function (val, cursor) { cb(cursor.primaryKey, cursor); });\n }\n\n /** Collection.keys()\n * \n * https://dexie.org/docs/Collection/Collection.keys()\n * \n **/\n keys(cb?) {\n var ctx = this._ctx;\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.key);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.primaryKeys()\n * \n * https://dexie.org/docs/Collection/Collection.primaryKeys()\n * \n **/\n primaryKeys(cb?) : PromiseExtended {\n var ctx = this._ctx;\n if (ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {\n // Special optimation if we could use IDBObjectStore.getAllKeys() or\n // IDBKeyRange.getAllKeys():\n return this._read(trans => {\n var index = getIndexOrStore(ctx, ctx.table.core.schema);\n return ctx.table.core.query({\n trans,\n values: false,\n limit: ctx.limit,\n query: {\n index,\n range: ctx.range\n }});\n }).then(({result})=>result).then(cb);\n }\n ctx.keysOnly = !ctx.isMatch;\n var a = [];\n return this.each(function (item, cursor) {\n a.push(cursor.primaryKey);\n }).then(function () {\n return a;\n }).then(cb);\n }\n\n /** Collection.uniqueKeys()\n * \n * https://dexie.org/docs/Collection/Collection.uniqueKeys()\n * \n **/\n uniqueKeys(cb?) {\n this._ctx.unique = \"unique\";\n return this.keys(cb);\n }\n\n /** Collection.firstKey()\n * \n * https://dexie.org/docs/Collection/Collection.firstKey()\n * \n **/\n firstKey(cb?) {\n return this.limit(1).keys(function (a) { return a[0]; }).then(cb);\n }\n\n /** Collection.lastKey()\n * \n * https://dexie.org/docs/Collection/Collection.lastKey()\n * \n **/\n lastKey(cb?) {\n return this.reverse().firstKey(cb);\n }\n\n /** Collection.distinct()\n * \n * https://dexie.org/docs/Collection/Collection.distinct()\n * \n **/\n distinct() {\n var ctx = this._ctx,\n idx = ctx.index && ctx.table.schema.idxByName[ctx.index];\n if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.\n var set = {};\n addFilter(this._ctx, function (cursor: DBCoreCursor) {\n var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string\n var found = hasOwn(set, strKey);\n set[strKey] = true;\n return !found;\n });\n return this;\n }\n\n //\n // Methods that mutate storage\n //\n\n /** Collection.modify()\n * \n * https://dexie.org/docs/Collection/Collection.modify()\n * \n **/\n modify(changes: { [keyPath: string]: any }) : PromiseExtended\n modify(changes: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean): PromiseExtended {\n var ctx = this._ctx;\n return this._write(trans => {\n var modifyer: (obj: any, ctx:{value: any, primKey: IndexableType}) => void | boolean\n if (typeof changes === 'function') {\n // Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)\n modifyer = changes;\n } else {\n // changes is a set of {keyPath: value} and no one is listening to the updating hook.\n var keyPaths = keys(changes);\n var numKeys = keyPaths.length;\n modifyer = function (item) {\n var anythingModified = false;\n for (var i = 0; i < numKeys; ++i) {\n var keyPath = keyPaths[i], val = changes[keyPath];\n if (getByKeyPath(item, keyPath) !== val) {\n setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath\n anythingModified = true;\n }\n }\n return anythingModified;\n };\n }\n\n const coreTable = ctx.table.core;\n const {outbound, extractKey} = coreTable.schema.primaryKey;\n const limit = this.db._options.modifyChunkSize || 200;\n const totalFailures = [];\n let successCount = 0;\n const failedKeys: IndexableType[] = [];\n const applyMutateResult = (expectedCount: number, res: DBCoreMutateResponse) => {\n const {failures, numFailures} = res;\n successCount += expectedCount - numFailures;\n for (let pos of keys(failures)) {\n totalFailures.push(failures[pos]);\n }\n }\n return this.clone().primaryKeys().then(keys => {\n\n const nextChunk = (offset: number) => {\n const count = Math.min(limit, keys.length - offset);\n return coreTable.getMany({\n trans,\n keys: keys.slice(offset, offset + count),\n cache: \"immutable\" // Optimize for 2 things:\n // 1) observability-middleware can track changes better.\n // 2) hooks middleware don't have to query the existing values again when tracking changes.\n // We can use \"immutable\" because we promise to not touch the values we retrieve here!\n }).then(values => {\n const addValues = [];\n const putValues = [];\n const putKeys = outbound ? [] : null;\n const deleteKeys = [];\n for (let i=0; i 0 &&\n coreTable.mutate({trans, type: 'add', values: addValues})\n .then(res => {\n for (let pos in res.failures) {\n // Remove from deleteKeys the key of the object that failed to change its primary key\n deleteKeys.splice(parseInt(pos), 1);\n }\n applyMutateResult(addValues.length, res);\n })\n ).then(()=>(putValues.length > 0 || (criteria && typeof changes === 'object')) &&\n coreTable.mutate({\n trans,\n type: 'put',\n keys: putKeys,\n values: putValues,\n criteria,\n changeSpec: typeof changes !== 'function'\n && changes\n }).then(res=>applyMutateResult(putValues.length, res))\n ).then(()=>(deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&\n coreTable.mutate({\n trans,\n type: 'delete',\n keys: deleteKeys,\n criteria\n }).then(res=>applyMutateResult(deleteKeys.length, res))\n ).then(()=>{\n return keys.length > offset + count && nextChunk(offset + limit);\n });\n });\n }\n\n return nextChunk(0).then(()=>{\n if (totalFailures.length > 0)\n throw new ModifyError(\"Error modifying one or more objects\", totalFailures, successCount, failedKeys as IndexableTypeArrayReadonly);\n\n return keys.length;\n });\n });\n\n });\n }\n\n /** Collection.delete()\n * \n * https://dexie.org/docs/Collection/Collection.delete()\n * \n **/\n delete() : PromiseExtended {\n var ctx = this._ctx,\n range = ctx.range;\n //deletingHook = ctx.table.hook.deleting.fire,\n //hasDeleteHook = deletingHook !== nop;\n if (isPlainKeyRange(ctx) &&\n ((ctx.isPrimKey && !hangsOnDeleteLargeKeyRange) || range.type === DBCoreRangeType.Any)) // if no range, we'll use clear().\n {\n // May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)\n // For chromium, this is the way most optimized version.\n // For IE/Edge, this could hang the indexedDB engine and make operating system instable\n // (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)\n return this._write(trans => {\n // Our API contract is to return a count of deleted items, so we have to count() before delete().\n const {primaryKey} = ctx.table.core.schema;\n const coreRange = range;\n return ctx.table.core.count({trans, query: {index: primaryKey, range: coreRange}}).then(count => {\n return ctx.table.core.mutate({trans, type: 'deleteRange', range: coreRange})\n .then(({failures, lastResult, results, numFailures}) => {\n if (numFailures) throw new ModifyError(\"Could not delete some values\",\n Object.keys(failures).map(pos => failures[pos]),\n count - numFailures);\n return count - numFailures;\n });\n });\n });\n }\n\n return this.modify(deleteCallback);\n }\n}\n\nconst deleteCallback = (value, ctx) => ctx.value = null;\n","import { Dexie } from '../../classes/dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Collection } from './collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { AnyRange } from '../../dbcore/keyrange';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\nimport { mirror } from '../../functions/chaining-functions';\n\n/** Constructs a Collection instance. */\nexport interface CollectionConstructor {\n new(whereClause?: WhereClause | null, keyRangeGenerator?: () => DBCoreKeyRange): Collection;\n prototype: Collection;\n}\n\n/** Generates a Collection constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createCollectionConstructor(db: Dexie) {\n return makeClassConstructor(\n Collection.prototype,\n\n function Collection(\n this: Collection,\n whereClause?: WhereClause | null,\n keyRangeGenerator?: () => DBCoreKeyRange)\n {\n this.db = db;\n let keyRange = AnyRange, error = null;\n if (keyRangeGenerator) try {\n keyRange = keyRangeGenerator();\n } catch (ex) {\n error = ex;\n }\n\n const whereCtx = whereClause._ctx;\n const table = whereCtx.table;\n const readingHook = table.hook.reading.fire;\n this._ctx = {\n table: table,\n index: whereCtx.index,\n isPrimKey: (!whereCtx.index || (table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name)),\n range: keyRange,\n keysOnly: false,\n dir: \"next\",\n unique: \"\",\n algorithm: null,\n filter: null,\n replayFilter: null,\n justLimit: true, // True if a replayFilter is just a filter that performs a \"limit\" operation (or none at all)\n isMatch: null,\n offset: 0,\n limit: Infinity,\n error: error, // If set, any promise must be rejected with this error\n or: whereCtx.or,\n valueMapper: readingHook !== mirror ? readingHook : null\n };\n }\n );\n}\n","import { IndexableType } from '../public/types/indexable-type';\n\nexport function simpleCompare(a, b) {\n return a < b ? -1 : a === b ? 0 : 1;\n}\n\nexport function simpleCompareReverse(a, b) {\n return a > b ? -1 : a === b ? 0 : 1;\n}\n","import { WhereClause } from './where-clause';\nimport { Collection } from '../collection';\nimport { STRING_EXPECTED } from '../../globals/constants';\nimport { simpleCompare, simpleCompareReverse } from '../../functions/compare-functions';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange, DBCoreRangeType } from '../../public/types/dbcore';\n\nexport function fail(collectionOrWhereClause: Collection | WhereClause, err, T?) {\n var collection = collectionOrWhereClause instanceof WhereClause ?\n new collectionOrWhereClause.Collection (collectionOrWhereClause) :\n collectionOrWhereClause;\n \n collection._ctx.error = T ? new T(err) : new TypeError(err);\n return collection;\n}\n\nexport function emptyCollection(whereClause: WhereClause) {\n return new whereClause.Collection (whereClause, () => rangeEqual(\"\")).limit(0);\n}\n\nexport function upperFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toUpperCase() :\n (s: string) => s.toLowerCase();\n}\n\nexport function lowerFactory(dir: 'next' | 'prev') {\n return dir === \"next\" ?\n (s: string) => s.toLowerCase() :\n (s: string) => s.toUpperCase();\n}\n\nexport function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {\n var length = Math.min(key.length, lowerNeedle.length);\n var llp = -1;\n for (var i = 0; i < length; ++i) {\n var lwrKeyChar = lowerKey[i];\n if (lwrKeyChar !== lowerNeedle[i]) {\n if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);\n if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);\n if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);\n return null;\n }\n if (cmp(key[i], lwrKeyChar) < 0) llp = i;\n }\n if (length < lowerNeedle.length && dir === \"next\") return key + upperNeedle.substr(key.length);\n if (length < key.length && dir === \"prev\") return key.substr(0, upperNeedle.length);\n return (llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1));\n}\n\nexport function addIgnoreCaseAlgorithm(whereClause: WhereClause, match, needles, suffix) {\n /// \n var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix,\n needlesLen = needles.length;\n if (!needles.every(s => typeof s === 'string')) {\n return fail(whereClause, STRING_EXPECTED);\n }\n function initDirection(dir) {\n upper = upperFactory(dir);\n lower = lowerFactory(dir);\n compare = (dir === \"next\" ? simpleCompare : simpleCompareReverse);\n var needleBounds = needles.map(function (needle){\n return {lower: lower(needle), upper: upper(needle)};\n }).sort(function(a,b) {\n return compare(a.lower, b.lower);\n });\n upperNeedles = needleBounds.map(function (nb){ return nb.upper; });\n lowerNeedles = needleBounds.map(function (nb){ return nb.lower; });\n direction = dir;\n nextKeySuffix = (dir === \"next\" ? \"\" : suffix);\n }\n initDirection(\"next\");\n\n var c = new whereClause.Collection (\n whereClause,\n ()=>createRange(upperNeedles[0], lowerNeedles[needlesLen-1] + suffix)\n );\n\n c._ondirectionchange = function (direction) {\n // This event onlys occur before filter is called the first time.\n initDirection(direction);\n };\n\n var firstPossibleNeedle = 0;\n\n c._addAlgorithm(function (cursor, advance, resolve) {\n /// \n /// \n /// \n var key = cursor.key;\n if (typeof key !== 'string') return false;\n var lowerKey = lower(key);\n if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {\n return true;\n } else {\n var lowestPossibleCasing = null;\n for (var i=firstPossibleNeedle; i 0) {\n lowestPossibleCasing = casing;\n }\n }\n if (lowestPossibleCasing !== null) {\n advance(function () { cursor.continue(lowestPossibleCasing + nextKeySuffix); });\n } else {\n advance(resolve);\n }\n return false;\n }\n });\n return c;\n}\n\nexport function createRange (lower: IndexableType, upper: IndexableType, lowerOpen?: boolean, upperOpen?: boolean): DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Range,\n lower,\n upper,\n lowerOpen,\n upperOpen\n };\n}\n\nexport function rangeEqual (value: IndexableType) : DBCoreKeyRange {\n return {\n type: DBCoreRangeType.Equal,\n lower: value,\n upper: value\n };\n}\n","import { WhereClause as IWhereClause } from \"../../public/types/where-clause\";\nimport { Collection } from \"../collection\";\nimport { Table } from \"../table\";\nimport { IndexableType } from \"../../public/types/indexable-type\";\nimport { emptyCollection, fail, addIgnoreCaseAlgorithm, createRange, rangeEqual } from './where-clause-helpers';\nimport { INVALID_KEY_ARGUMENT, STRING_EXPECTED, maxString, minKey } from '../../globals/constants';\nimport { getArrayOf, NO_CHAR_ARRAY } from '../../functions/utils';\nimport { exceptions } from '../../errors';\nimport { Dexie } from '../dexie';\nimport { Collection as ICollection} from \"../../public/types/collection\";\n\n/** class WhereClause\n * \n * https://dexie.org/docs/WhereClause/WhereClause\n */\nexport class WhereClause implements IWhereClause {\n db: Dexie;\n _IDBKeyRange: typeof IDBKeyRange;\n _ctx: {\n table: Table;\n index: string;\n or: Collection;\n }\n _cmp: (a: IndexableType, b: IndexableType) => number;\n _ascending: (a: IndexableType, b: IndexableType) => number;\n _descending: (a: IndexableType, b: IndexableType) => number;\n _min: (a: IndexableType, b: IndexableType) => IndexableType;\n _max: (a: IndexableType, b: IndexableType) => IndexableType;\n\n get Collection() {\n return this._ctx.table.db.Collection;\n }\n\n /** WhereClause.between()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.between()\n * \n **/\n between(lower: IndexableType, upper: IndexableType, includeLower?: boolean, includeUpper?: boolean) {\n includeLower = includeLower !== false; // Default to true\n includeUpper = includeUpper === true; // Default to false\n try {\n if ((this._cmp(lower, upper) > 0) ||\n (this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)))\n return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.\n return new this.Collection(this, ()=>createRange(lower, upper, !includeLower, !includeUpper));\n } catch (e) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n }\n\n /** WhereClause.equals()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equals()\n * \n **/\n equals(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => rangeEqual(value)) as ICollection;\n }\n\n /** WhereClause.above()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.above()\n * \n **/\n above(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, true));\n }\n\n /** WhereClause.aboveOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.aboveOrEqual()\n * \n **/\n aboveOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(value, undefined, false));\n }\n\n /** WhereClause.below()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.below()\n * \n **/\n below(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value, false, true));\n }\n\n /** WhereClause.belowOrEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.belowOrEqual()\n * \n **/\n belowOrEqual(value: IndexableType) {\n if (value == null) return fail(this, INVALID_KEY_ARGUMENT);\n return new this.Collection(this, () => createRange(undefined, value));\n }\n\n /** WhereClause.startsWith()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWith()\n * \n **/\n startsWith(str: string) {\n if (typeof str !== 'string') return fail(this, STRING_EXPECTED);\n return this.between(str, str + maxString, true, true);\n }\n\n /** WhereClause.startsWithIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithIgnoreCase()\n * \n **/\n startsWithIgnoreCase(str: string) {\n if (str === \"\") return this.startsWith(str);\n return addIgnoreCaseAlgorithm(this, (x, a) => x.indexOf(a[0]) === 0, [str], maxString);\n }\n\n /** WhereClause.equalsIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.equalsIgnoreCase()\n * \n **/\n equalsIgnoreCase(str: string) {\n return addIgnoreCaseAlgorithm(this, (x, a) => x === a[0], [str], \"\");\n }\n\n /** WhereClause.anyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOfIgnoreCase()\n * \n **/\n anyOfIgnoreCase(...values: string[]): Collection;\n anyOfIgnoreCase(values: string[]): Collection;\n anyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.indexOf(x) !== -1, set, \"\");\n }\n\n /** WhereClause.startsWithAnyOfIgnoreCase()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOfIgnoreCase()\n * \n **/\n startsWithAnyOfIgnoreCase(...values: string[]): Collection;\n startsWithAnyOfIgnoreCase(values: string[]): Collection;\n startsWithAnyOfIgnoreCase() {\n var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return emptyCollection(this);\n return addIgnoreCaseAlgorithm(this, (x, a) => a.some(n => x.indexOf(n) === 0), set, maxString);\n }\n\n /** WhereClause.anyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.anyOf()\n * \n **/\n anyOf(...values: string[]): Collection;\n anyOf(values: string[]): Collection;\n anyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n let compare = this._cmp;\n try { set.sort(compare); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n if (set.length === 0) return emptyCollection(this);\n const c = new this.Collection(this, () => createRange(set[0], set[set.length - 1]));\n\n c._ondirectionchange = direction => {\n compare = (direction === \"next\" ?\n this._ascending :\n this._descending);\n set.sort(compare);\n };\n\n let i = 0;\n c._addAlgorithm((cursor, advance, resolve) => {\n const key = cursor.key;\n while (compare(key, set[i]) > 0) {\n // The cursor has passed beyond this key. Check next.\n ++i;\n if (i === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (compare(key, set[i]) === 0) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => { cursor.continue(set[i]); });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.notEqual()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.notEqual()\n * \n **/\n notEqual(value: IndexableType) {\n return this.inAnyRange([[minKey, value], [value, this.db._maxKey]], { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.noneOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.noneOf()\n * \n **/\n noneOf(...values: string[]): Collection;\n noneOf(values: string[]): Collection;\n noneOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n if (set.length === 0) return new this.Collection(this); // Return entire collection.\n try { set.sort(this._ascending); } catch (e) { return fail(this, INVALID_KEY_ARGUMENT); }\n // Transform [\"a\",\"b\",\"c\"] to a set of ranges for between/above/below: [[minKey,\"a\"], [\"a\",\"b\"], [\"b\",\"c\"], [\"c\",maxKey]]\n const ranges = set.reduce(\n (res, val) => res ?\n res.concat([[res[res.length - 1][1], val]]) :\n [[minKey, val]],\n null);\n ranges.push([set[set.length - 1], this.db._maxKey]);\n return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });\n }\n\n /** WhereClause.inAnyRange()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.inAnyRange()\n * \n **/\n inAnyRange(\n ranges: ReadonlyArray<{ 0: IndexableType, 1: IndexableType }>,\n options?: { includeLowers?: boolean, includeUppers?: boolean })\n {\n const cmp = this._cmp,\n ascending = this._ascending,\n descending = this._descending,\n min = this._min,\n max = this._max;\n\n if (ranges.length === 0) return emptyCollection(this);\n if (!ranges.every(range =>\n range[0] !== undefined &&\n range[1] !== undefined &&\n ascending(range[0], range[1]) <= 0)) {\n return fail(\n this,\n \"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower\",\n exceptions.InvalidArgument);\n }\n const includeLowers = !options || options.includeLowers !== false; // Default to true\n const includeUppers = options && options.includeUppers === true; // Default to false\n\n function addRange(ranges, newRange) {\n let i = 0, l = ranges.length;\n for (; i < l; ++i) {\n const range = ranges[i];\n if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {\n range[0] = min(range[0], newRange[0]);\n range[1] = max(range[1], newRange[1]);\n break;\n }\n }\n if (i === l)\n ranges.push(newRange);\n return ranges;\n }\n\n let sortDirection = ascending;\n function rangeSorter(a, b) { return sortDirection(a[0], b[0]); }\n\n // Join overlapping ranges\n let set;\n try {\n set = ranges.reduce(addRange, []);\n set.sort(rangeSorter);\n } catch (ex) {\n return fail(this, INVALID_KEY_ARGUMENT);\n }\n\n let rangePos = 0;\n const keyIsBeyondCurrentEntry = includeUppers ?\n key => ascending(key, set[rangePos][1]) > 0 :\n key => ascending(key, set[rangePos][1]) >= 0;\n\n const keyIsBeforeCurrentEntry = includeLowers ?\n key => descending(key, set[rangePos][0]) > 0 :\n key => descending(key, set[rangePos][0]) >= 0;\n\n function keyWithinCurrentRange(key) {\n return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);\n }\n\n let checkKey = keyIsBeyondCurrentEntry;\n\n const c = new this.Collection(\n this,\n () => createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers));\n\n c._ondirectionchange = direction => {\n if (direction === \"next\") {\n checkKey = keyIsBeyondCurrentEntry;\n sortDirection = ascending;\n } else {\n checkKey = keyIsBeforeCurrentEntry;\n sortDirection = descending;\n }\n set.sort(rangeSorter);\n };\n\n c._addAlgorithm((cursor, advance, resolve) => {\n var key = cursor.key;\n while (checkKey(key)) {\n // The cursor has passed beyond this key. Check next.\n ++rangePos;\n if (rangePos === set.length) {\n // There is no next. Stop searching.\n advance(resolve);\n return false;\n }\n }\n if (keyWithinCurrentRange(key)) {\n // The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.\n return true;\n } else if (this._cmp(key, set[rangePos][1]) === 0 || this._cmp(key, set[rangePos][0]) === 0) {\n // includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.\n // Continue to next key but don't include this one.\n return false;\n } else {\n // cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.\n advance(() => {\n if (sortDirection === ascending) cursor.continue(set[rangePos][0]);\n else cursor.continue(set[rangePos][1]);\n });\n return false;\n }\n });\n return c;\n }\n\n /** WhereClause.startsWithAnyOf()\n * \n * https://dexie.org/docs/WhereClause/WhereClause.startsWithAnyOf()\n * \n **/\n startsWithAnyOf(...prefixes: string[]): Collection;\n startsWithAnyOf(prefixes: string[]): Collection;\n startsWithAnyOf() {\n const set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);\n\n if (!set.every(s => typeof s === 'string')) {\n return fail(this, \"startsWithAnyOf() only works with strings\");\n }\n if (set.length === 0) return emptyCollection(this);\n\n return this.inAnyRange(set.map((str: string) => [str, str + maxString]));\n }\n\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { WhereClause } from './where-clause';\nimport { Table } from '../table';\nimport { Collection } from '../collection';\nimport { exceptions } from '../../errors';\nimport { cmp } from '../../functions/cmp';\n\nexport interface WhereClauseConstructor {\n new(table: Table, index?: string, orCollection?: Collection): WhereClause;\n prototype: WhereClause;\n}\n\n/** Generates a WhereClause constructor.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createWhereClauseConstructor(db: Dexie) {\n return makeClassConstructor(\n WhereClause.prototype,\n\n function WhereClause(this: WhereClause, table: Table, index?: string, orCollection?: Collection) {\n this.db = db;\n this._ctx = {\n table: table,\n index: index === \":id\" ? null : index,\n or: orCollection\n };\n this._cmp = this._ascending = cmp;\n this._descending = (a, b) => cmp(b, a);\n this._max = (a, b) => cmp(a,b) > 0 ? a : b;\n this._min = (a, b) => cmp(a,b) < 0 ? a : b;\n this._IDBKeyRange = db._deps.IDBKeyRange;\n if (!this._IDBKeyRange) throw new exceptions.MissingAPI();\n }\n );\n}\n","import { wrap } from \"../helpers/promise\";\n\nexport function eventRejectHandler(reject) {\n return wrap(function (event) {\n preventDefault(event);\n reject (event.target.error);\n return false;\n });\n}\n\nexport function eventSuccessHandler (resolve) {\n return wrap(function (event){\n resolve(event.target.result);\n });\n}\n\nexport function hookedEventRejectHandler (reject) {\n return wrap(function (event) {\n // See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.\n \n var req = event.target,\n err = req.error,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n hookErrorHandler = ctx && ctx.onerror;\n hookErrorHandler && hookErrorHandler(err);\n preventDefault(event);\n reject (err);\n return false;\n });\n}\n\nexport function hookedEventSuccessHandler(resolve) {\n // wrap() is needed when calling hooks because the rare scenario of:\n // * hook does a db operation that fails immediately (IDB throws exception)\n // For calling db operations on correct transaction, wrap makes sure to set PSD correctly.\n // wrap() will also execute in a virtual tick.\n // * If not wrapped in a virtual tick, direct exception will launch a new physical tick.\n // * If this was the last event in the bulk, the promise will resolve after a physical tick\n // and the transaction will have committed already.\n // If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,\n // because it is always marked with _lib = true when created using Transaction._promise().\n return wrap(function(event) {\n var req = event.target,\n ctx = req._hookCtx,// Contains the hook error handler. Put here instead of closure to boost performance.\n result = ctx.value || req.result, // Pass the object value on updates. The result from IDB is the primary key.\n hookSuccessHandler = ctx && ctx.onsuccess;\n hookSuccessHandler && hookSuccessHandler(result);\n resolve && resolve(result);\n }, resolve);\n}\n\n\nexport function preventDefault(event) {\n if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.stopPropagation();\n if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.\n event.preventDefault();\n}\n\nexport function BulkErrorHandlerCatchAll(errorList, done?, supportHooks?) {\n return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(e => {\n errorList.push(e);\n done && done();\n });\n}\n\n","import Events from '../helpers/Events';\nimport { GlobalDexieEvents } from '../public/types/db-events';\n\nexport const DEXIE_STORAGE_MUTATED_EVENT_NAME = 'storagemutated' as 'storagemutated';\n\n// Name of the global event fired using DOM dispatchEvent (if not in node).\n// Reason for propagating this as a DOM event is for getting reactivity across\n// multiple versions of Dexie within the same app (as long as they are\n// compatible with regards to the event data).\n// If the ObservabilitySet protocol change in a way that would not be backward\n// compatible, make sure also update the event name to a new number at the end\n// so that two Dexie instances of different versions continue to work together\n// - maybe not able to communicate but won't fail due to unexpected data in\n// the detail property of the CustomEvent. If so, also make sure to udpate\n// docs and explain at which Dexie version the new name and format of the event\n// is being used.\nexport const STORAGE_MUTATED_DOM_EVENT_NAME = 'x-storagemutated-1';\n\nexport const globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME) as GlobalDexieEvents;\n","import { Transaction as ITransaction } from '../../public/types/transaction';\nimport { DexiePromise, wrap, rejection } from \"../../helpers/promise\";\nimport { DbSchema } from '../../public/types/db-schema';\nimport { assert, hasOwn } from '../../functions/utils';\nimport { PSD, usePSD } from '../../helpers/promise';\nimport { Dexie } from '../dexie';\nimport { exceptions } from '../../errors';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { preventDefault } from '../../functions/event-wrappers';\nimport { newScope } from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { Table } from '../table';\nimport { globalEvents } from '../../globals/global-events';\n\n/** Transaction\n * \n * https://dexie.org/docs/Transaction/Transaction\n * \n **/\nexport class Transaction implements ITransaction {\n db: Dexie;\n active: boolean;\n mode: IDBTransactionMode;\n chromeTransactionDurability: ChromeTransactionDurability;\n idbtrans: IDBTransaction;\n storeNames: string[];\n explicit?: boolean;\n on: any;\n parent?: Transaction;\n schema: DbSchema;\n _memoizedTables: {[tableName: string]: Table};\n\n _reculock: number;\n _blockedFuncs: { 0: () => any, 1: any }[];\n _resolve: () => void;\n _reject: (Error) => void;\n _waitingFor: DexiePromise; // for waitFor()\n _waitingQueue: Function[]; // for waitFor()\n _spinCount: number; // Just for debugging waitFor()\n _completion: DexiePromise;\n\n //\n // Transaction internal methods (not required by API users, but needed internally and eventually by dexie extensions)\n //\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _lock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n // Temporary set all requests into a pending queue if they are called before database is ready.\n ++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)\n if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;\n return this;\n }\n\n /** Transaction._unlock()\n * \n * Internal method.\n */\n _unlock() {\n assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.\n if (--this._reculock === 0) {\n if (!PSD.global) PSD.lockOwnerFor = null;\n while (this._blockedFuncs.length > 0 && !this._locked()) {\n var fnAndPSD = this._blockedFuncs.shift();\n try { usePSD(fnAndPSD[1], fnAndPSD[0]); } catch (e) { }\n }\n }\n return this;\n }\n\n /** Transaction._lock()\n * \n * Internal method.\n */\n _locked() {\n // Checks if any write-lock is applied on this transaction.\n // To simplify the Dexie API for extension implementations, we support recursive locks.\n // This is accomplished by using \"Promise Specific Data\" (PSD).\n // PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).\n // PSD is local to code executing on top of the call stacks of any of any code executed by Promise():\n // * callback given to the Promise() constructor (function (resolve, reject){...})\n // * callbacks given to then()/catch()/finally() methods (function (value){...})\n // If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.\n // Derivation is done so that the inner PSD __proto__ points to the outer PSD.\n // PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.\n return this._reculock && PSD.lockOwnerFor !== this;\n }\n\n /** Transaction.create()\n * \n * Internal method.\n * \n */\n create(idbtrans?: IDBTransaction & {[prop: string]: any}) {\n if (!this.mode) return this;\n const idbdb = this.db.idbdb;\n const dbOpenError = this.db._state.dbOpenError;\n assert(!this.idbtrans);\n if (!idbtrans && !idbdb) {\n switch (dbOpenError && dbOpenError.name) {\n case \"DatabaseClosedError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.DatabaseClosed(dbOpenError);\n case \"MissingAPIError\":\n // Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()\n throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);\n default:\n // Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!\n throw new exceptions.OpenFailed(dbOpenError);\n }\n }\n if (!this.active) throw new exceptions.TransactionInactive();\n assert(this._completion._state === null); // Completion Promise must still be pending.\n\n idbtrans = this.idbtrans = idbtrans ||\n (this.db.core \n ? this.db.core.transaction(this.storeNames, this.mode as 'readwrite' | 'readonly', { durability: this.chromeTransactionDurability })\n : idbdb.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability })\n ) as IDBTransaction;\n\n idbtrans.onerror = wrap(ev => {\n preventDefault(ev);// Prohibit default bubbling to window.error\n this._reject(idbtrans.error);\n });\n idbtrans.onabort = wrap(ev => {\n preventDefault(ev);\n this.active && this._reject(new exceptions.Abort(idbtrans.error));\n this.active = false;\n this.on(\"abort\").fire(ev);\n });\n idbtrans.oncomplete = wrap(() => {\n this.active = false;\n this._resolve();\n if ('mutatedParts' in idbtrans) {\n globalEvents.storagemutated.fire(idbtrans[\"mutatedParts\"]);\n }\n });\n return this;\n }\n\n /** Transaction._promise()\n * \n * Internal method.\n */\n _promise(\n mode: IDBTransactionMode,\n fn: (resolve, reject, trans: Transaction) => PromiseLike | void,\n bWriteLock?: string | boolean): DexiePromise\n {\n if (mode === 'readwrite' && this.mode !== 'readwrite')\n return rejection(new exceptions.ReadOnly(\"Transaction is readonly\"));\n\n if (!this.active)\n return rejection(new exceptions.TransactionInactive());\n\n if (this._locked()) {\n return new DexiePromise((resolve, reject) => {\n this._blockedFuncs.push([() => {\n this._promise(mode, fn, bWriteLock).then(resolve, reject);\n }, PSD]);\n });\n\n } else if (bWriteLock) {\n return newScope(() => {\n var p = new DexiePromise((resolve, reject) => {\n this._lock();\n const rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p.finally(() => this._unlock());\n p._lib = true;\n return p;\n });\n\n } else {\n var p = new DexiePromise((resolve, reject) => {\n var rv = fn(resolve, reject, this);\n if (rv && rv.then) rv.then(resolve, reject);\n });\n p._lib = true;\n return p;\n }\n }\n\n /** Transaction._root()\n * \n * Internal method. Retrieves the root transaction in the tree of sub transactions.\n */\n _root() {\n return this.parent ? this.parent._root() : this;\n }\n\n /** Transaction.waitFor()\n * \n * Internal method. Can be accessed from the public API through\n * Dexie.waitFor(): https://dexie.org/docs/Dexie/Dexie.waitFor()\n * \n **/\n waitFor(promiseLike: PromiseLike) {\n // Always operate on the root transaction (in case this is a sub stransaction)\n var root = this._root();\n // For stability reasons, convert parameter to promise no matter what type is passed to waitFor().\n // (We must be able to call .then() on it.)\n const promise = DexiePromise.resolve(promiseLike);\n if (root._waitingFor) {\n // Already called waitFor(). Wait for both to complete.\n root._waitingFor = root._waitingFor.then(() => promise);\n } else {\n // We're not in waiting state. Start waiting state.\n root._waitingFor = promise;\n root._waitingQueue = [];\n // Start interacting with indexedDB until promise completes:\n var store = root.idbtrans.objectStore(root.storeNames[0]);\n (function spin() {\n ++root._spinCount; // For debugging only\n while (root._waitingQueue.length) (root._waitingQueue.shift())();\n if (root._waitingFor) store.get(-Infinity).onsuccess = spin;\n }());\n }\n var currentWaitPromise = root._waitingFor;\n return new DexiePromise((resolve, reject) => {\n promise.then(\n res => root._waitingQueue.push(wrap(resolve.bind(null, res))),\n err => root._waitingQueue.push(wrap(reject.bind(null, err)))\n ).finally(() => {\n if (root._waitingFor === currentWaitPromise) {\n // No one added a wait after us. Safe to stop the spinning.\n root._waitingFor = null;\n }\n });\n });\n } \n\n /** Transaction.abort()\n * \n * https://dexie.org/docs/Transaction/Transaction.abort()\n */\n abort() {\n if (this.active) {\n this.active = false;\n if (this.idbtrans) this.idbtrans.abort();\n this._reject(new exceptions.Abort());\n }\n }\n\n /** Transaction.table()\n * \n * https://dexie.org/docs/Transaction/Transaction.table()\n */\n table(tableName: string) {\n const memoizedTables = (this._memoizedTables || (this._memoizedTables = {}));\n if (hasOwn(memoizedTables, tableName))\n return memoizedTables[tableName];\n const tableSchema = this.schema[tableName];\n if (!tableSchema) {\n throw new exceptions.NotFound(\"Table \" + tableName + \" not part of transaction\"); \n }\n\n const transactionBoundTable = new this.db.Table(tableName, tableSchema, this);\n transactionBoundTable.core = this.db.core.table(tableName);\n memoizedTables[tableName] = transactionBoundTable;\n return transactionBoundTable;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Transaction } from './transaction';\nimport { DbSchema } from '../../public/types/db-schema';\nimport Events from '../../helpers/Events';\nimport Promise, { rejection } from '../../helpers/promise';\n\nexport interface TransactionConstructor {\n new (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction) : T;\n prototype: T;\n}\n\n/** Generates a Transaction constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createTransactionConstructor(db: Dexie) {\n return makeClassConstructor>(\n Transaction.prototype,\n function Transaction (\n this: Transaction,\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n chromeTransactionDurability: ChromeTransactionDurability,\n parent?: Transaction)\n {\n this.db = db;\n this.mode = mode;\n this.storeNames = storeNames;\n this.schema = dbschema;\n this.chromeTransactionDurability = chromeTransactionDurability;\n this.idbtrans = null;\n this.on = Events(this, \"complete\", \"error\", \"abort\");\n this.parent = parent || null;\n this.active = true;\n this._reculock = 0;\n this._blockedFuncs = [];\n this._resolve = null;\n this._reject = null;\n this._waitingFor = null;\n this._waitingQueue = null;\n this._spinCount = 0; // Just for debugging waitFor()\n this._completion = new Promise ((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n \n this._completion.then(\n ()=> {\n this.active = false;\n this.on.complete.fire();\n },\n e => {\n var wasActive = this.active;\n this.active = false;\n this.on.error.fire(e);\n this.parent ?\n this.parent._reject(e) :\n wasActive && this.idbtrans && this.idbtrans.abort();\n return rejection(e); // Indicate we actually DO NOT catch this error.\n });\n \n });\n}\n","import { IndexSpec } from '../public/types/index-spec';\n\nexport function createIndexSpec(\n name: string,\n keyPath: string | string[],\n unique: boolean,\n multi: boolean,\n auto: boolean,\n compound: boolean,\n isPrimKey: boolean\n): IndexSpec {\n return {\n name,\n keyPath,\n unique,\n multi,\n auto,\n compound,\n src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? \"++\" : \"\") + nameFromKeyPath(keyPath)\n }\n}\n\nexport function nameFromKeyPath (keyPath?: string | string[]): string {\n return typeof keyPath === 'string' ?\n keyPath :\n keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : \"\";\n}\n","import { IndexSpec } from '../public/types/index-spec';\nimport { TableSchema } from '../public/types/table-schema';\nimport { createIndexSpec } from './index-spec';\nimport { arrayToObject } from '../functions/utils';\n\nexport function createTableSchema (\n name: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n): TableSchema {\n return {\n name,\n primKey,\n indexes,\n mappedClass: null,\n idxByName: arrayToObject(indexes, index => [index.name, index])\n };\n}\n","import { maxString } from '../globals/constants';\n\nexport function safariMultiStoreFix(storeNames: string[]) {\n return storeNames.length === 1 ? storeNames[0] : storeNames;\n}\n\nexport function getNativeGetDatabaseNamesFn(indexedDB) {\n var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);\n return fn && fn.bind(indexedDB);\n}\n\nexport let getMaxKey = (IdbKeyRange: typeof IDBKeyRange) => {\n try {\n IdbKeyRange.only([[]]);\n getMaxKey = () => [[]];\n return [[]];\n } catch (e) {\n getMaxKey = () => maxString;\n return maxString;\n }\n}\n","import { getByKeyPath } from '../functions/utils';\n\nexport function getKeyExtractor (keyPath: null | string | string[]) : (a: any) => any {\n if (keyPath == null) {\n return () => undefined;\n } else if (typeof keyPath === 'string') {\n return getSinglePathKeyExtractor(keyPath);\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n\nexport function getSinglePathKeyExtractor(keyPath: string) {\n const split = keyPath.split('.');\n if (split.length === 1) {\n return obj => obj[keyPath];\n } else {\n return obj => getByKeyPath(obj, keyPath);\n }\n}\n","import {\n DBCore,\n DBCoreCursor,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryResponse,\n DBCoreRangeType,\n DBCoreSchema,\n DBCoreTableSchema,\n DBCoreTable,\n DBCoreMutateResponse,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { eventRejectHandler, preventDefault } from '../functions/event-wrappers';\nimport { wrap } from '../helpers/promise';\nimport { getMaxKey } from '../functions/quirks';\nimport { getKeyExtractor } from './get-key-extractor';\n\nexport function arrayify(arrayLike: {length: number, [index: number]: T}): T[] {\n return [].slice.call(arrayLike);\n}\nexport function pick(obj: T, props: Prop[]): Pick {\n const result = {} as Pick;\n props.forEach(prop => result[prop] = obj[prop]);\n return result;\n}\n\nlet _id_counter = 0;\n\nexport function getKeyPathAlias(keyPath: null | string | string[]) {\n return keyPath == null ?\n \":id\" :\n typeof keyPath === 'string' ?\n keyPath :\n `[${keyPath.join('+')}]`;\n}\n\nexport function createDBCore (\n db: IDBDatabase,\n IdbKeyRange: typeof IDBKeyRange,\n tmpTrans: IDBTransaction) : DBCore\n{\n function extractSchema(db: IDBDatabase, trans: IDBTransaction) : {schema: DBCoreSchema, hasGetAll: boolean} {\n const tables = arrayify(db.objectStoreNames);\n return {\n schema: {\n name: db.name,\n tables: tables.map(table => trans.objectStore(table)).map(store => {\n const {keyPath, autoIncrement} = store;\n const compound = isArray(keyPath);\n const outbound = keyPath == null;\n const indexByKeyPath: {[keyPathAlias: string]: DBCoreIndex} = {};\n const result = {\n name: store.name,\n primaryKey: {\n name: null,\n isPrimaryKey: true,\n outbound,\n compound,\n keyPath,\n autoIncrement,\n unique: true,\n extractKey: getKeyExtractor(keyPath)\n } as DBCoreIndex,\n indexes: arrayify(store.indexNames).map(indexName => store.index(indexName))\n .map(index => {\n const {name, unique, multiEntry, keyPath} = index;\n const compound = isArray(keyPath);\n const result: DBCoreIndex = {\n name,\n compound,\n keyPath,\n unique,\n multiEntry,\n extractKey: getKeyExtractor(keyPath)\n };\n indexByKeyPath[getKeyPathAlias(keyPath)] = result;\n return result;\n }),\n getIndexByKeyPath: (keyPath: null | string | string[]) => indexByKeyPath[getKeyPathAlias(keyPath)]\n };\n indexByKeyPath[\":id\"] = result.primaryKey;\n if (keyPath != null) {\n indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey;\n }\n return result;\n })\n },\n hasGetAll: tables.length > 0 && ('getAll' in trans.objectStore(tables[0])) &&\n !(typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604) // Bug with getAll() on Safari ver<604. See discussion following PR #579\n };\n }\n\n function makeIDBKeyRange (range: DBCoreKeyRange) : IDBKeyRange | null {\n if (range.type === DBCoreRangeType.Any) return null;\n if (range.type === DBCoreRangeType.Never) throw new Error(\"Cannot convert never type to IDBKeyRange\");\n const {lower, upper, lowerOpen, upperOpen} = range;\n const idbRange = lower === undefined ?\n upper === undefined ?\n null : //IDBKeyRange.lowerBound(-Infinity, false) : // Any range (TODO: Should we return null instead?)\n IdbKeyRange.upperBound(upper, !!upperOpen) : // below\n upper === undefined ?\n IdbKeyRange.lowerBound(lower, !!lowerOpen) : // above\n IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen);\n return idbRange;\n }\n\n function createDbCoreTable(tableSchema: DBCoreTableSchema): DBCoreTable {\n const tableName = tableSchema.name;\n\n function mutate ({trans, type, keys, values, range}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const outbound = store.keyPath == null;\n const isAddOrPut = type === \"put\" || type === \"add\";\n if (!isAddOrPut && type !== 'delete' && type !== 'deleteRange')\n throw new Error (\"Invalid operation type: \" + type);\n\n const {length} = keys || values || {length: 1}; // keys.length if keys. values.length if values. 1 if range.\n if (keys && values && keys.length !== values.length) {\n throw new Error(\"Given keys array must have same length as given values array.\");\n }\n if (length === 0)\n // No items to write. Don't even bother!\n return resolve({numFailures: 0, failures: {}, results: [], lastResult: undefined});\n\n let req: IDBRequest;\n const reqs: IDBRequest[] = [];\n \n const failures: {[operationNumber: number]: Error} = [];\n let numFailures = 0;\n const errorHandler = \n event => {\n ++numFailures;\n preventDefault(event);\n };\n \n if (type === 'deleteRange') {\n // Here the argument is the range\n if (range.type === DBCoreRangeType.Never)\n return resolve({numFailures, failures, results: [], lastResult: undefined}); // Deleting the Never range shoulnt do anything.\n if (range.type === DBCoreRangeType.Any)\n reqs.push(req = store.clear()); // Deleting the Any range is equivalent to store.clear()\n else\n reqs.push(req = store.delete(makeIDBKeyRange(range)));\n } else {\n // No matter add, put or delete - find out arrays of first and second arguments to it.\n const [args1, args2] = isAddOrPut ?\n outbound ?\n [values, keys] :\n [values, null] :\n [keys, null];\n\n if (isAddOrPut) {\n for (let i=0; i {\n const lastResult = event.target.result;\n reqs.forEach((req, i) => req.error != null && (failures[i] = req.error));\n resolve({\n numFailures,\n failures,\n results: type === \"delete\" ? keys : reqs.map(req => req.result),\n lastResult\n });\n };\n \n req.onerror = event => { // wrap() not needed. All paths calling outside will wrap!\n errorHandler(event);\n done(event);\n };\n \n req.onsuccess = done;\n });\n }\n \n function openCursor ({trans, values, query, reverse, unique}: DBCoreOpenCursorRequest): Promise\n {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n // source\n const source = index.isPrimaryKey ?\n store :\n store.index(index.name);\n // direction\n const direction = reverse ?\n unique ?\n \"prevunique\" :\n \"prev\" :\n unique ?\n \"nextunique\" :\n \"next\";\n // request\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(makeIDBKeyRange(range), direction) :\n source.openKeyCursor(makeIDBKeyRange(range), direction);\n \n // iteration\n req.onerror = eventRejectHandler(reject);\n req.onsuccess = wrap(ev => {\n\n const cursor = req.result as unknown as DBCoreCursor;\n if (!cursor) {\n resolve(null);\n return;\n }\n (cursor as any).___id = ++_id_counter;\n (cursor as any).done = false;\n const _cursorContinue = cursor.continue.bind(cursor);\n let _cursorContinuePrimaryKey = cursor.continuePrimaryKey;\n if (_cursorContinuePrimaryKey) _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor);\n const _cursorAdvance = cursor.advance.bind(cursor);\n const doThrowCursorIsNotStarted = ()=>{throw new Error(\"Cursor not started\");}\n const doThrowCursorIsStopped = ()=>{throw new Error(\"Cursor not stopped\");}\n (cursor as any).trans = trans;\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted;\n cursor.fail = wrap(reject);\n cursor.next = function (this: DBCoreCursor) {\n // next() must work with \"this\" pointer in order to function correctly for ProxyCursors (derived objects)\n // without having to re-define next() on each child.\n let gotOne = 1;\n return this.start(() => gotOne-- ? this.continue() : this.stop()).then(() => this);\n };\n cursor.start = (callback) => {\n //console.log(\"Starting cursor\", (cursor as any).___id);\n const iterationPromise = new Promise((resolveIteration, rejectIteration) =>{\n resolveIteration = wrap(resolveIteration);\n req.onerror = eventRejectHandler(rejectIteration);\n cursor.fail = rejectIteration;\n cursor.stop = value => {\n //console.log(\"Cursor stop\", cursor);\n cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped;\n resolveIteration(value);\n };\n });\n // Now change req.onsuccess to a callback that doesn't call initCursor but just observer.next()\n const guardedCallback = () => {\n if (req.result) {\n //console.log(\"Next result\", cursor);\n try {\n callback();\n } catch (err) {\n cursor.fail(err);\n }\n } else {\n (cursor as any).done = true;\n cursor.start = ()=>{throw new Error(\"Cursor behind last entry\");}\n cursor.stop();\n }\n }\n req.onsuccess = wrap(ev => {\n //cursor.continue = _cursorContinue;\n //cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n //cursor.advance = _cursorAdvance;\n req.onsuccess = guardedCallback;\n guardedCallback();\n });\n cursor.continue = _cursorContinue;\n cursor.continuePrimaryKey = _cursorContinuePrimaryKey;\n cursor.advance = _cursorAdvance;\n guardedCallback();\n return iterationPromise;\n };\n resolve(cursor);\n }, reject); \n });\n }\n \n function query (hasGetAll: boolean) {\n return (request: DBCoreQueryRequest) => {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const {trans, values, limit, query} = request;\n const nonInfinitLimit = limit === Infinity ? undefined : limit;\n const {index, range} = query;\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n if (limit === 0) return resolve({result: []});\n if (hasGetAll) {\n const req = values ?\n (source as any).getAll(idbKeyRange, nonInfinitLimit) :\n (source as any).getAllKeys(idbKeyRange, nonInfinitLimit);\n req.onsuccess = event => resolve({result: event.target.result});\n req.onerror = eventRejectHandler(reject);\n } else {\n let count = 0;\n const req = values || !('openKeyCursor' in source) ?\n source.openCursor(idbKeyRange) :\n source.openKeyCursor(idbKeyRange)\n const result = [];\n req.onsuccess = event => {\n const cursor = req.result as IDBCursorWithValue;\n if (!cursor) return resolve({result});\n result.push(values ? cursor.value : cursor.primaryKey);\n if (++count === limit) return resolve({result});\n cursor.continue();\n };\n req.onerror = eventRejectHandler(reject);\n }\n });\n };\n }\n \n return {\n name: tableName,\n schema: tableSchema,\n \n mutate,\n\n getMany ({trans, keys}) {\n return new Promise((resolve, reject) => {\n resolve = wrap(resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const length = keys.length;\n const result = new Array(length);\n let keyCount = 0;\n let callbackCount = 0;\n let valueCount = 0;\n let req: IDBRequest & {_pos?: number};\n \n const successHandler = event => {\n const req = event.target;\n if ((result[req._pos] = req.result) != null) ++valueCount;\n if (++callbackCount === keyCount) resolve(result);\n };\n const errorHandler = eventRejectHandler(reject);\n \n for (let i=0; i((resolve, reject) => {\n resolve = wrap (resolve);\n const store = (trans as IDBTransaction).objectStore(tableName);\n const req = store.get(key);\n req.onsuccess = event => resolve((event.target as any).result);\n req.onerror = eventRejectHandler(reject);\n });\n },\n\n query: query(hasGetAll),\n \n openCursor,\n\n count ({query, trans}) {\n const {index, range} = query;\n return new Promise((resolve, reject) => {\n const store = (trans as IDBTransaction).objectStore(tableName);\n const source = index.isPrimaryKey ? store : store.index(index.name);\n const idbKeyRange = makeIDBKeyRange(range);\n const req = idbKeyRange ? source.count(idbKeyRange) : source.count();\n req.onsuccess = wrap(ev => resolve((ev.target as IDBRequest).result));\n req.onerror = eventRejectHandler(reject);\n });\n }\n };\n }\n\n const {schema, hasGetAll} = extractSchema(db, tmpTrans);\n const tables = schema.tables.map(tableSchema => createDbCoreTable(tableSchema));\n const tableMap: {[name: string]: DBCoreTable} = {};\n tables.forEach(table => tableMap[table.name] = table);\n return {\n stack: \"dbcore\",\n \n transaction: db.transaction.bind(db),\n\n table(name: string) {\n const result = tableMap[name];\n if (!result) throw new Error(`Table '${name}' not found`);\n return tableMap[name];\n },\n\n MIN_KEY: -Infinity,\n\n MAX_KEY: getMaxKey(IdbKeyRange),\n\n schema\n\n };\n}\n","import { Dexie } from './';\nimport { createDBCore } from '../../dbcore/dbcore-indexeddb';\nimport { DBCore } from '../../public/types/dbcore';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { DexieStacks, Middleware } from '../../public/types/middleware';\nimport { exceptions } from '../../errors';\n\nfunction createMiddlewareStack(\n stackImpl: {stack: string},\n middlewares: Middleware<{stack: string}>[]): TStack {\n return middlewares.reduce((down, {create}) => ({...down, ...create(down)}), stackImpl) as TStack;\n} \n\nfunction createMiddlewareStacks(\n middlewares: {[StackName in keyof DexieStacks]?: Middleware[]},\n idbdb: IDBDatabase,\n {IDBKeyRange, indexedDB}: DexieDOMDependencies,\n tmpTrans: IDBTransaction): {[StackName in keyof DexieStacks]?: DexieStacks[StackName]}\n{\n const dbcore = createMiddlewareStack(\n createDBCore(idbdb, IDBKeyRange, tmpTrans),\n middlewares.dbcore);\n \n // TODO: Create other stacks the same way as above. They might be dependant on the result\n // of creating dbcore stack.\n\n return {\n dbcore\n };\n}\n\nexport function generateMiddlewareStacks(db: Dexie, tmpTrans: IDBTransaction) {\n const idbdb = tmpTrans.db;\n const stacks = createMiddlewareStacks(db._middlewares, idbdb, db._deps, tmpTrans);\n db.core = stacks.dbcore!;\n db.tables.forEach(table => {\n const tableName = table.name;\n if (db.core.schema.tables.some(tbl => tbl.name === tableName)) {\n table.core = db.core.table(tableName);\n if (db[tableName] instanceof db.Table) {\n db[tableName].core = table.core;\n }\n }\n });\n}\n","import { Dexie } from '../dexie';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { _global } from \"../../globals/global\";\nimport { setProp, keys, slice, isArray, shallowClone, isAsyncFunction, defineProperty, getPropertyDescriptor } from '../../functions/utils';\nimport { Transaction } from '../transaction';\nimport { Version } from './version';\nimport Promise, { PSD, newScope, NativePromise, decrementExpectedAwaits, incrementExpectedAwaits } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { TableSchema } from '../../public/types/table-schema';\nimport { IndexSpec } from '../../public/types/index-spec';\nimport { hasIEDeleteObjectStoreBug, isIEOrEdge } from '../../globals/constants';\nimport { createIndexSpec, nameFromKeyPath } from '../../helpers/index-spec';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { generateMiddlewareStacks } from '../dexie/generate-middleware-stacks';\n\nexport function setApiOnPlace(db: Dexie, objs: Object[], tableNames: string[], dbschema: DbSchema) {\n tableNames.forEach(tableName => {\n const schema = dbschema[tableName];\n objs.forEach(obj => {\n const propDesc = getPropertyDescriptor(obj, tableName);\n if (!propDesc || (\"value\" in propDesc && propDesc.value === undefined)) {\n // Either the prop is not declared, or it is initialized to undefined.\n if (obj === db.Transaction.prototype || obj instanceof db.Transaction) {\n // obj is a Transaction prototype (or prototype of a subclass to Transaction)\n // Make the API a getter that returns this.table(tableName)\n setProp(obj, tableName, {\n get(this: Transaction) { return this.table(tableName); },\n set(value: any) {\n // Issue #1039\n // Let \"this.schema = dbschema;\" and other props in transaction constructor work even if there's a name collision with the table name.\n defineProperty(this, tableName, {value, writable: true, configurable: true, enumerable: true});\n }\n });\n } else {\n // Table will not be bound to a transaction (will use Dexie.currentTransaction)\n obj[tableName] = new db.Table(tableName, schema);\n }\n }\n });\n });\n}\n\nexport function removeTablesApi(db: Dexie, objs: Object[]) {\n objs.forEach(obj => {\n for (let key in obj) {\n if (obj[key] instanceof db.Table) delete obj[key];\n }\n });\n}\n\nexport function lowerVersionFirst(a: Version, b: Version) {\n return a._cfg.version - b._cfg.version;\n}\n\nexport function runUpgraders(db: Dexie, oldVersion: number, idbUpgradeTrans: IDBTransaction, reject) {\n const globalSchema = db._dbSchema;\n const trans = db._createTransaction('readwrite', db._storeNames, globalSchema);\n trans.create(idbUpgradeTrans);\n trans._completion.catch(reject);\n const rejectTransaction = trans._reject.bind(trans);\n const transless = PSD.transless || PSD;\n newScope(() => {\n PSD.trans = trans;\n PSD.transless = transless;\n if (oldVersion === 0) {\n // Create tables:\n keys(globalSchema).forEach(tableName => {\n createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);\n });\n generateMiddlewareStacks(db, idbUpgradeTrans);\n Promise.follow(() => db.on.populate.fire(trans)).catch(rejectTransaction);\n } else\n updateTablesAndIndexes(db, oldVersion, trans, idbUpgradeTrans).catch(rejectTransaction);\n });\n}\n\nexport type UpgradeQueueItem = (idbtrans: IDBTransaction) => PromiseLike | void;\n\nexport function updateTablesAndIndexes(\n db: Dexie,\n oldVersion: number,\n trans: Transaction,\n idbUpgradeTrans: IDBTransaction)\n{\n // Upgrade version to version, step-by-step from oldest to newest version.\n // Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)\n const queue: UpgradeQueueItem[] = [];\n const versions = db._versions;\n let globalSchema = db._dbSchema = buildGlobalSchema(db, db.idbdb, idbUpgradeTrans);\n let anyContentUpgraderHasRun = false;\n\n const versToRun = versions.filter(v => v._cfg.version >= oldVersion);\n versToRun.forEach(version => {\n queue.push(() => {\n const oldSchema = globalSchema;\n const newSchema = version._cfg.dbschema;\n adjustToExistingIndexNames(db, oldSchema, idbUpgradeTrans);\n adjustToExistingIndexNames(db, newSchema, idbUpgradeTrans);\n\n globalSchema = db._dbSchema = newSchema;\n\n const diff = getSchemaDiff(oldSchema, newSchema);\n // Add tables \n diff.add.forEach(tuple => {\n createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes);\n });\n // Change tables\n diff.change.forEach(change => {\n if (change.recreate) {\n throw new exceptions.Upgrade(\"Not yet support for changing primary key\");\n } else {\n const store = idbUpgradeTrans.objectStore(change.name);\n // Add indexes\n change.add.forEach(idx => addIndex(store, idx));\n // Update indexes\n change.change.forEach(idx => {\n store.deleteIndex(idx.name);\n addIndex(store, idx);\n });\n // Delete indexes\n change.del.forEach(idxName => store.deleteIndex(idxName));\n }\n });\n\n const contentUpgrade = version._cfg.contentUpgrade;\n\n if (contentUpgrade && version._cfg.version > oldVersion) {\n // Update db.core with new tables and indexes:\n generateMiddlewareStacks(db, idbUpgradeTrans);\n trans._memoizedTables = {}; // Invalidate memoization as transaction shape may change between versions.\n\n anyContentUpgraderHasRun = true;\n\n // Add to-be-deleted tables to contentUpgrade transaction\n let upgradeSchema = shallowClone(newSchema);\n diff.del.forEach(table => {\n upgradeSchema[table] = oldSchema[table];\n });\n\n // Safe to affect Transaction.prototype globally in this moment,\n // because when this code runs, there may not be any other code\n // that can access any transaction instance, else than this particular\n // upgrader function.\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], keys(upgradeSchema), upgradeSchema);\n trans.schema = upgradeSchema;\n\n // Support for native async await.\n const contentUpgradeIsAsync = isAsyncFunction(contentUpgrade);\n if (contentUpgradeIsAsync) {\n incrementExpectedAwaits();\n }\n \n let returnValue: any;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = contentUpgrade(trans);\n if (returnValue) {\n if (contentUpgradeIsAsync) {\n // contentUpgrade is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n }\n }\n });\n return (returnValue && typeof returnValue.then === 'function' ?\n Promise.resolve(returnValue) : promiseFollowed.then(()=>returnValue));\n }\n });\n queue.push(idbtrans => {\n if (!anyContentUpgraderHasRun || !hasIEDeleteObjectStoreBug) { // Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.\n const newSchema = version._cfg.dbschema;\n // Delete old tables\n deleteRemovedTables(newSchema, idbtrans);\n }\n // Restore the final API\n removeTablesApi(db, [db.Transaction.prototype]);\n setApiOnPlace(db, [db.Transaction.prototype], db._storeNames, db._dbSchema);\n trans.schema = db._dbSchema;\n });\n });\n\n // Now, create a queue execution engine\n function runQueue() {\n return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) :\n Promise.resolve();\n }\n\n return runQueue().then(() => {\n createMissingTables(globalSchema, idbUpgradeTrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)\n });\n}\n\nexport interface SchemaDiff {\n del: string[],\n add: [string, TableSchema][];\n change: TableSchemaDiff[];\n}\n\nexport interface TableSchemaDiff {\n name: string,\n recreate: boolean,\n del: string[],\n add: IndexSpec[],\n change: IndexSpec[]\n}\n\nexport function getSchemaDiff(oldSchema: DbSchema, newSchema: DbSchema): SchemaDiff {\n const diff: SchemaDiff = {\n del: [], // Array of table names\n add: [], // Array of [tableName, newDefinition]\n change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}\n };\n let table: string;\n for (table in oldSchema) {\n if (!newSchema[table]) diff.del.push(table);\n }\n for (table in newSchema) {\n const oldDef = oldSchema[table],\n newDef = newSchema[table];\n if (!oldDef) {\n diff.add.push([table, newDef]);\n } else {\n const change = {\n name: table,\n def: newDef,\n recreate: false,\n del: [],\n add: [],\n change: []\n };\n if (\n (\n // compare keyPaths no matter if string or string[]\n // compare falsy keypaths same no matter if they are null or empty string.\n ''+(oldDef.primKey.keyPath||'')\n ) !== (\n ''+(newDef.primKey.keyPath||'')\n ) ||\n // Compare the autoIncrement flag also\n (oldDef.primKey.auto !== newDef.primKey.auto && !isIEOrEdge)) // IE has bug reading autoIncrement prop.\n {\n // Primary key has changed. Remove and re-add table.\n change.recreate = true;\n diff.change.push(change);\n } else {\n // Same primary key. Just find out what differs:\n const oldIndexes = oldDef.idxByName;\n const newIndexes = newDef.idxByName;\n let idxName: string;\n for (idxName in oldIndexes) {\n if (!newIndexes[idxName]) change.del.push(idxName);\n }\n for (idxName in newIndexes) {\n const oldIdx = oldIndexes[idxName],\n newIdx = newIndexes[idxName];\n if (!oldIdx) change.add.push(newIdx);\n else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);\n }\n if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {\n diff.change.push(change);\n }\n }\n }\n }\n return diff;\n}\n\nexport function createTable(\n idbtrans: IDBTransaction,\n tableName: string,\n primKey: IndexSpec,\n indexes: IndexSpec[]\n) {\n const store = idbtrans.db.createObjectStore(\n tableName,\n primKey.keyPath ?\n { keyPath: primKey.keyPath, autoIncrement: primKey.auto } :\n { autoIncrement: primKey.auto }\n );\n indexes.forEach(idx => addIndex(store, idx));\n return store;\n}\n\nexport function createMissingTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n keys(newSchema).forEach(tableName => {\n if (!idbtrans.db.objectStoreNames.contains(tableName)) {\n createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);\n }\n });\n}\n\nexport function deleteRemovedTables(newSchema: DbSchema, idbtrans: IDBTransaction) {\n [].slice.call(idbtrans.db.objectStoreNames).forEach(storeName =>\n newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName));\n}\n\nexport function addIndex(store: IDBObjectStore, idx: IndexSpec) {\n store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });\n}\n\nfunction buildGlobalSchema(\n db: Dexie,\n idbdb: IDBDatabase,\n tmpTrans: IDBTransaction\n) {\n const globalSchema = {};\n const dbStoreNames = slice(idbdb.objectStoreNames, 0);\n dbStoreNames.forEach(storeName => {\n const store = tmpTrans.objectStore(storeName);\n let keyPath = store.keyPath;\n const primKey = createIndexSpec(\n nameFromKeyPath(keyPath),\n keyPath || \"\",\n false,\n false,\n !!store.autoIncrement,\n keyPath && typeof keyPath !== \"string\",\n true\n );\n const indexes: IndexSpec[] = [];\n for (let j = 0; j < store.indexNames.length; ++j) {\n const idbindex = store.index(store.indexNames[j]);\n keyPath = idbindex.keyPath;\n var index = createIndexSpec(\n idbindex.name,\n keyPath,\n !!idbindex.unique,\n !!idbindex.multiEntry,\n false,\n keyPath && typeof keyPath !== \"string\",\n false\n );\n indexes.push(index);\n }\n globalSchema[storeName] = createTableSchema(storeName, primKey, indexes);\n });\n return globalSchema;\n}\n\nexport function readGlobalSchema(db: Dexie, idbdb: IDBDatabase, tmpTrans: IDBTransaction) {\n db.verno = idbdb.version / 10;\n const globalSchema = db._dbSchema = buildGlobalSchema(db, idbdb, tmpTrans);\n db._storeNames = slice(idbdb.objectStoreNames, 0);\n setApiOnPlace(db, [db._allTables], keys(globalSchema), globalSchema);\n}\n\nexport function verifyInstalledSchema(db: Dexie, tmpTrans: IDBTransaction): boolean {\n const installedSchema = buildGlobalSchema(db, db.idbdb, tmpTrans);\n const diff = getSchemaDiff(installedSchema, db._dbSchema);\n return !(diff.add.length || diff.change.some(ch => ch.add.length || ch.change.length));\n}\n\nexport function adjustToExistingIndexNames(db: Dexie, schema: DbSchema, idbtrans: IDBTransaction) {\n // Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db\n const storeNames = idbtrans.db.objectStoreNames;\n\n for (let i = 0; i < storeNames.length; ++i) {\n const storeName = storeNames[i];\n const store = idbtrans.objectStore(storeName);\n db._hasGetAll = 'getAll' in store;\n\n for (let j = 0; j < store.indexNames.length; ++j) {\n const indexName = store.indexNames[j];\n const keyPath = store.index(indexName).keyPath;\n const dexieName = typeof keyPath === 'string' ? keyPath : \"[\" + slice(keyPath).join('+') + \"]\";\n if (schema[storeName]) {\n const indexSpec = schema[storeName].idxByName[dexieName];\n if (indexSpec) {\n indexSpec.name = indexName;\n delete schema[storeName].idxByName[dexieName];\n schema[storeName].idxByName[indexName] = indexSpec;\n }\n }\n }\n }\n\n // Bug with getAll() on Safari ver<604 on Workers only, see discussion following PR #579\n if (typeof navigator !== 'undefined' && /Safari/.test(navigator.userAgent) &&\n !/(Chrome\\/|Edge\\/)/.test(navigator.userAgent) &&\n _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope &&\n [].concat(navigator.userAgent.match(/Safari\\/(\\d*)/))[1] < 604)\n {\n db._hasGetAll = false;\n }\n}\n\nexport function parseIndexSyntax(primKeyAndIndexes: string): IndexSpec[] {\n return primKeyAndIndexes.split(',').map((index, indexNum) => {\n index = index.trim();\n const name = index.replace(/([&*]|\\+\\+)/g, \"\"); // Remove \"&\", \"++\" and \"*\"\n // Let keyPath of \"[a+b]\" be [\"a\",\"b\"]:\n const keyPath = /^\\[/.test(name) ? name.match(/^\\[(.*)\\]$/)[1].split('+') : name;\n\n return createIndexSpec(\n name,\n keyPath || null,\n /\\&/.test(index),\n /\\*/.test(index),\n /\\+\\+/.test(index),\n isArray(keyPath),\n indexNum === 0\n );\n });\n}\n","import { Version as IVersion } from '../../public/types/version';\nimport { DbSchema } from '../../public/types/db-schema';\nimport { extend, keys } from '../../functions/utils';\nimport { Dexie } from '../dexie';\nimport { Transaction } from '../transaction';\nimport { removeTablesApi, setApiOnPlace, parseIndexSyntax } from './schema-helpers';\nimport { exceptions } from '../../errors';\nimport { createTableSchema } from '../../helpers/table-schema';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\n\n/** class Version\n *\n * https://dexie.org/docs/Version/Version\n */\nexport class Version implements IVersion {\n db: Dexie;\n _cfg: {\n version: number,\n storesSource: { [tableName: string]: string | null },\n dbschema: DbSchema,\n tables: {},\n contentUpgrade: Function | null\n }\n\n _parseStoresSpec(stores: { [tableName: string]: string | null }, outSchema: DbSchema): any {\n keys(stores).forEach(tableName => {\n if (stores[tableName] !== null) {\n var indexes = parseIndexSyntax(stores[tableName]);\n var primKey = indexes.shift();\n if (primKey.multi) throw new exceptions.Schema(\"Primary key cannot be multi-valued\");\n indexes.forEach(idx => {\n if (idx.auto) throw new exceptions.Schema(\"Only primary key can be marked as autoIncrement (++)\");\n if (!idx.keyPath) throw new exceptions.Schema(\"Index must have a name and cannot be an empty string\");\n });\n outSchema[tableName] = createTableSchema(tableName, primKey, indexes);\n }\n });\n }\n\n stores(stores: { [key: string]: string | null; }): IVersion {\n const db = this.db;\n this._cfg.storesSource = this._cfg.storesSource ?\n extend(this._cfg.storesSource, stores) :\n stores;\n const versions = db._versions;\n\n // Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.\n const storesSpec: { [key: string]: string; } = {};\n let dbschema = {};\n versions.forEach(version => { // 'versions' is always sorted by lowest version first.\n extend(storesSpec, version._cfg.storesSource);\n dbschema = (version._cfg.dbschema = {});\n version._parseStoresSpec(storesSpec, dbschema);\n });\n // Update the latest schema to this version\n db._dbSchema = dbschema;\n // Update APIs\n removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);\n setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);\n db._storeNames = keys(dbschema);\n return this;\n }\n\n upgrade(upgradeFunction: (trans: Transaction) => PromiseLike | void): Version {\n this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction);\n return this;\n }\n}\n","import { Dexie } from '../dexie';\nimport { makeClassConstructor } from '../../functions/make-class-constructor';\nimport { Version } from './version';\n\nexport interface VersionConstructor {\n new(versionNumber: number): Version;\n prototype: Version;\n}\n\n/** Generates a Version constructor bound to given Dexie instance.\n * \n * The purpose of having dynamically created constructors, is to allow\n * addons to extend classes for a certain Dexie instance without affecting\n * other db instances.\n */\nexport function createVersionConstructor(db: Dexie) {\n return makeClassConstructor(\n Version.prototype,\n\n function Version(this: Version, versionNumber: number) {\n this.db = db;\n this._cfg = {\n version: versionNumber,\n storesSource: null,\n dbschema: {},\n tables: {},\n contentUpgrade: null\n };\n });\n\n}\n","import { Dexie } from \"../classes/dexie/dexie\";\nimport { Table } from \"../public/types/table\";\nimport { DBNAMES_DB } from \"../globals/constants\";\nimport { DexieDOMDependencies } from \"../public/types/dexie-dom-dependencies\";\nimport { nop } from \"../functions/chaining-functions\";\n\ntype IDBKeyNamesVar = typeof IDBKeyRange;\n\nfunction getDbNamesTable(indexedDB: IDBFactory, IDBKeyRange: IDBKeyNamesVar) {\n let dbNamesDB = indexedDB[\"_dbNamesDB\"];\n if (!dbNamesDB) {\n dbNamesDB = indexedDB[\"_dbNamesDB\"] = new Dexie(DBNAMES_DB, {\n addons: [],\n indexedDB,\n IDBKeyRange,\n });\n dbNamesDB.version(1).stores({ dbnames: \"name\" });\n }\n return dbNamesDB.table(\"dbnames\") as Table<{ name: string }, string>;\n}\n\nfunction hasDatabasesNative(indexedDB: IDBFactory) {\n return indexedDB && typeof indexedDB.databases === \"function\";\n}\n\nexport function getDatabaseNames({\n indexedDB,\n IDBKeyRange,\n}: DexieDOMDependencies) {\n return hasDatabasesNative(indexedDB)\n ? Promise.resolve(indexedDB.databases()).then((infos) =>\n infos\n // Select name prop of infos:\n .map((info) => info.name)\n // Filter out DBNAMES_DB as previous Dexie or browser version would not have included it in the result.\n .filter((name) => name !== DBNAMES_DB)\n )\n : getDbNamesTable(indexedDB, IDBKeyRange).toCollection().primaryKeys();\n}\n\nexport function _onDatabaseCreated(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).put({name}).catch(nop);\n}\n\nexport function _onDatabaseDeleted(\n { indexedDB, IDBKeyRange }: DexieDOMDependencies,\n name: string\n) {\n !hasDatabasesNative(indexedDB) &&\n name !== DBNAMES_DB &&\n getDbNamesTable(indexedDB, IDBKeyRange).delete(name).catch(nop);\n}\n","import { newScope } from '../../helpers/promise';\nimport { PSD } from '../../helpers/promise';\n\nexport function vip (fn) {\n // To be used by subscribers to the on('ready') event.\n // This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.\n // This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD\n // from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since\n // the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.\n // Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()\n // the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by\n // the caller will not resolve until database is opened.\n return newScope(function () {\n PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.\n return fn();\n });\n}\n\n","/**\n * Work around Safari 14 IndexedDB open bug.\n *\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547\n * The only solution is to keep nudging it until it's awake.\n */\nfunction idbReady() {\n var isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n var intervalId;\n return new Promise(function (resolve) {\n var tryIdb = function () { return indexedDB.databases().finally(resolve); };\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(function () { return clearInterval(intervalId); });\n}\n\nexport default idbReady;\n","import { cmp } from \"../functions/cmp\";\nimport { extend, iteratorSymbol, props } from '../functions/utils';\nimport { IndexableType } from '../public';\nimport {\n EmptyRange,\n IntervalTree,\n IntervalTreeNode,\n RangeSetConstructor,\n RangeSetPrototype,\n} from \"../public/types/rangeset\";\n\n/* An interval tree implementation to efficiently detect overlapping ranges of queried indexes.\n *\n * https://en.wikipedia.org/wiki/Interval_tree\n * \n */\n\nfunction isEmptyRange(node: IntervalTree | {from: IndexableType, to: IndexableType}): node is EmptyRange {\n return !(\"from\" in node);\n}\n\nexport type RangeSet = RangeSetPrototype & IntervalTree;\n\nexport const RangeSet = function(fromOrTree: any, to?: any) {\n if (this) {\n // Called with new()\n extend(this, arguments.length ? {d:1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree} : {d:0});\n } else {\n // Called without new()\n const rv = new RangeSet();\n if (fromOrTree && (\"d\" in fromOrTree)) {\n extend(rv, fromOrTree);\n }\n return rv;\n }\n} as RangeSetConstructor;\n\nprops(RangeSet.prototype, {\n add(rangeSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n mergeRanges(this, rangeSet);\n return this;\n },\n addKey(key: IndexableType) {\n addRange(this, key, key);\n return this;\n },\n addKeys(keys: IndexableType[]) {\n keys.forEach(key => addRange(this, key, key));\n return this;\n },\n\n [iteratorSymbol](): Iterator {\n return getRangeSetIterator(this);\n }\n});\n\nfunction addRange(target: IntervalTree, from: IndexableType, to: IndexableType) {\n const diff = cmp(from, to);\n // cmp() returns NaN if one of the args are IDB-invalid keys.\n // Avoid storing invalid keys in rangeset:\n if (isNaN(diff)) return;\n\n // Caller is trying to add a range where from is greater than to:\n if (diff > 0) throw RangeError();\n \n if (isEmptyRange(target)) return extend(target, { from, to, d: 1 });\n const left = target.l;\n const right = target.r;\n if (cmp(to, target.from) < 0) {\n left\n ? addRange(left, from, to)\n : (target.l = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n if (cmp(from, target.to) > 0) {\n right\n ? addRange(right, from, to)\n : (target.r = { from, to, d: 1, l: null, r: null });\n return rebalance(target);\n }\n // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed.\n\n // Grow left?\n if (cmp(from, target.from) < 0) {\n target.from = from;\n target.l = null; // Cut off for now. Re-add later.\n target.d = right ? right.d + 1 : 1;\n }\n // Grow right?\n if (cmp(to, target.to) > 0) {\n target.to = to;\n target.r = null; // Cut off for now. Re-add later.\n target.d = target.l ? target.l.d + 1 : 1;\n }\n const rightWasCutOff = !target.r;\n // Re-add left?\n if (left && !target.l) {\n //Ranges to the left may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, left);\n }\n // Re-add right?\n if (right && rightWasCutOff) {\n //Ranges to the right may be swallowed. Cut it of and re-add all.\n //Could probably be done more efficiently!\n mergeRanges(target, right);\n }\n}\n\nexport function mergeRanges(target: IntervalTree, newSet: IntervalTree | {from: IndexableType, to: IndexableType}) {\n function _addRangeSet(\n target: IntervalTree,\n { from, to, l, r }: IntervalTreeNode | {from: IndexableType, to: IndexableType, l?: undefined, r?: undefined}\n ) {\n addRange(target, from, to);\n if (l) _addRangeSet(target, l);\n if (r) _addRangeSet(target, r);\n }\n\n if(!isEmptyRange(newSet)) _addRangeSet(target, newSet);\n}\n\nexport function rangesOverlap(\n rangeSet1: IntervalTree,\n rangeSet2: IntervalTree\n): boolean {\n // Start iterating other from scratch.\n const i1 = getRangeSetIterator(rangeSet2);\n let nextResult1 = i1.next();\n if (nextResult1.done) return false;\n let a = nextResult1.value;\n\n // Start iterating this from start of other\n const i2 = getRangeSetIterator(rangeSet1);\n let nextResult2 = i2.next(a.from); // Start from beginning of other range\n let b = nextResult2.value;\n\n while (!nextResult1.done && !nextResult2.done) {\n if (cmp(b!.from, a.to) <= 0 && cmp(b!.to, a.from) >= 0) return true;\n cmp(a.from, b!.from) < 0\n ? (a = (nextResult1 = i1.next(b!.from)).value!) // a is behind. forward it to beginning of next b-range\n : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range\n }\n return false;\n}\n\ntype RangeSetIteratorState =\n | {\n up?: RangeSetIteratorState;\n n: IntervalTreeNode;\n s: 0 | 1 | 2 | 3;\n }\n | undefined\n | null;\nexport function getRangeSetIterator(\n node: EmptyRange | IntervalTreeNode\n): Generator {\n let state: RangeSetIteratorState = isEmptyRange(node) ? null : { s: 0, n: node };\n\n return {\n next(key?) {\n const keyProvided = arguments.length > 0;\n while (state) {\n switch (state.s) {\n case 0:\n // Initial state for node.\n // Fast forward to leftmost node.\n state.s = 1;\n if (keyProvided) {\n while (state.n.l && cmp(key, state.n.from) < 0)\n state = { up: state, n: state.n.l, s: 1 };\n } else {\n while (state.n.l) state = { up: state, n: state.n.l, s: 1 };\n }\n // intentionally fall into case 1:\n case 1:\n // We're on a node where it's left part is already handled or does not exist.\n state.s = 2;\n if (!keyProvided || cmp(key, state.n.to) <= 0)\n return { value: state.n, done: false };\n case 2:\n // We've emitted our node and should continue with the right part or let parent take over from it's state 1\n if (state.n.r) {\n state.s = 3; // So when child is done, we know we're done.\n state = { up: state, n: state.n.r, s: 0 };\n continue; // Will fall in to case 0 with fast forward to left leaf of this subtree.\n }\n // intentionally fall into case 3:\n case 3:\n state = state.up;\n }\n }\n return { done: true };\n },\n } as Generator;\n}\n\nfunction rebalance(target: IntervalTreeNode) {\n const diff = (target.r?.d || 0) - (target.l?.d || 0);\n const r = diff > 1 ? \"r\" : diff < -1 ? \"l\" : \"\";\n if (r) {\n\n // Rotate (https://en.wikipedia.org/wiki/Tree_rotation)\n //\n // \n // [OLDROOT]\n // [OLDROOT.L] [NEWROOT]\n // [NEWROOT.L] [NEWROOT.R]\n //\n // Is going to become:\n //\n // \n // [NEWROOT]\n // [OLDROOT] [NEWROOT.R]\n // [OLDROOT.L] [NEWROOT.L] \n\n // * clone now has the props of OLDROOT\n // Plan:\n // * target must be given the props of NEWROOT\n // * target[l] must point to a new OLDROOT\n // * target[r] must point to NEWROOT.R\n // * OLDROOT[r] must point to NEWROOT.L\n const l = r === \"r\" ? \"l\" : \"r\"; // Support both left/right rotation\n const rootClone = { ...target };\n // We're gonna copy props from target's right node into target so that target will\n // have same range as old target[r] (instead of changing pointers, we copy values.\n // that way we do not need to adjust pointers in parents).\n const oldRootRight = target[r]; \n target.from = oldRootRight.from;\n target.to = oldRootRight.to;\n target[r] = oldRootRight[r];\n rootClone[r] = oldRootRight[l];\n target[l] = rootClone;\n rootClone.d = computeDepth(rootClone);\n }\n target.d = computeDepth(target);\n}\n\nfunction computeDepth({ r, l }: Pick) {\n return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1;\n}\n","import { cloneSimpleObjectTree, deepClone, keys, objectIsEmpty } from \"../functions/utils\";\nimport { mergeRanges, RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\n\nexport function extendObservabilitySet(\n target: ObservabilitySet,\n newSet: ObservabilitySet\n): ObservabilitySet {\n keys(newSet).forEach(part => {\n if (target[part]) mergeRanges(target[part], newSet[part]);\n else target[part] = cloneSimpleObjectTree(newSet[part]); // Somewhat faster\n });\n return target;\n}\n","import { rangesOverlap } from '../helpers/rangeset';\nimport { ObservabilitySet } from '../public/types/db-events';\n\nexport function obsSetsOverlap(os1: ObservabilitySet, os2: ObservabilitySet) {\n return Object.keys(os1).some(\n (key) => os2[key] && rangesOverlap(os2[key], os1[key])\n );\n}\n","import { type GlobalQueryCache } from \"../../public/types/cache\";\n\nexport const cache: GlobalQueryCache = {}\n","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport { extendObservabilitySet } from '../extend-observability-set';\nimport { obsSetsOverlap } from '../obs-sets-overlap';\nimport { cache } from './cache';\n\nlet unsignaledParts: ObservabilitySet = {};\nlet isTaskEnqueued = false;\n\nexport function signalSubscribersLazily(part: ObservabilitySet) {\n extendObservabilitySet(unsignaledParts, part);\n if (!isTaskEnqueued) {\n isTaskEnqueued = true;\n setTimeout(() => {\n isTaskEnqueued = false;\n const parts = unsignaledParts;\n unsignaledParts = {};\n signalSubscribersNow(parts);\n }, 0);\n }\n}\n\nexport function signalSubscribersNow(\n updatedParts: ObservabilitySet,\n deleteAffectedCacheEntries = false\n) {\n const queriesToSignal = new Set<() => void>();\n for (const key in updatedParts) {\n const parts = /^idb\\:\\/\\/(.*)\\/(.*)\\//.exec(key);\n if (parts) {\n const [, dbName, tableName] = parts;\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (tblCache)\n signalTableSubscribersNow(\n tblCache,\n updatedParts,\n queriesToSignal,\n deleteAffectedCacheEntries\n );\n }\n }\n // Now when affected cache entries are removed, signal collected subscribers to requery.\n queriesToSignal.forEach((requery) => requery());\n}\n\nfunction signalTableSubscribersNow(\n tblCache: TblQueryCache,\n updatedParts: ObservabilitySet,\n outQueriesToSignal: Set<() => void>,\n deleteAffectedCacheEntries: boolean\n) {\n const updatedEntryLists: [string, CacheEntry[]][] =\n deleteAffectedCacheEntries && [];\n for (const [indexName, entries] of Object.entries(tblCache.queries.query)) {\n const filteredEntries: CacheEntry[] = deleteAffectedCacheEntries && [];\n for (const entry of entries) {\n if (entry.obsSet && obsSetsOverlap(updatedParts, entry.obsSet)) {\n // This query is affected by the mutation. Remove it from cache\n // and signal all subscribers to requery.\n entry.subscribers.forEach((requery) => outQueriesToSignal.add(requery));\n } else if (deleteAffectedCacheEntries) {\n filteredEntries.push(entry);\n }\n }\n // Collect cache entries to be updated\n if (deleteAffectedCacheEntries)\n updatedEntryLists.push([indexName, filteredEntries]);\n }\n if (deleteAffectedCacheEntries) {\n for (const [indexName, filteredEntries] of updatedEntryLists) {\n tblCache.queries.query[indexName] = filteredEntries;\n }\n }\n}\n","import { Dexie } from './dexie';\nimport * as Debug from '../../helpers/debug';\nimport { rejection } from '../../helpers/promise';\nimport { exceptions } from '../../errors';\nimport { eventRejectHandler, preventDefault } from '../../functions/event-wrappers';\nimport Promise, { wrap } from '../../helpers/promise';\nimport { connections } from '../../globals/constants';\nimport { runUpgraders, readGlobalSchema, adjustToExistingIndexNames, verifyInstalledSchema } from '../version/schema-helpers';\nimport { safariMultiStoreFix } from '../../functions/quirks';\nimport { _onDatabaseCreated } from '../../helpers/database-enumerator';\nimport { vip } from './vip';\nimport { promisableChain, nop } from '../../functions/chaining-functions';\nimport { generateMiddlewareStacks } from './generate-middleware-stacks';\nimport { slice } from '../../functions/utils';\nimport safari14Workaround from 'safari-14-idb-fix';\nimport { type ObservabilitySet } from '../../public/types/db-events';\nimport { RangeSet } from '../../helpers/rangeset';\nimport { DEXIE_STORAGE_MUTATED_EVENT_NAME, globalEvents } from '../../globals/global-events';\nimport { signalSubscribersNow } from '../../live-query/cache/signalSubscribers';\n\nexport function dexieOpen (db: Dexie) {\n const state = db._state;\n const {indexedDB} = db._deps;\n if (state.isBeingOpened || db.idbdb)\n return state.dbReadyPromise.then(() => state.dbOpenError ?\n rejection (state.dbOpenError) :\n db);\n Debug.debug && (state.openCanceller._stackHolder = Debug.getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.\n state.isBeingOpened = true;\n state.dbOpenError = null;\n state.openComplete = false;\n const openCanceller = state.openCanceller;\n\n function throwIfCancelled() {\n // If state.openCanceller object reference is replaced, it means db.close() has been called,\n // meaning this open flow should be cancelled.\n if (state.openCanceller !== openCanceller) throw new exceptions.DatabaseClosed('db.open() was cancelled');\n }\n \n // Function pointers to call when the core opening process completes.\n let resolveDbReady = state.dbReadyResolve,\n // upgradeTransaction to abort on failure.\n upgradeTransaction: (IDBTransaction | null) = null,\n wasCreated = false;\n \n // safari14Workaround = Workaround by jakearchibald for new nasty bug in safari 14.\n return Promise.race([openCanceller, (typeof navigator === 'undefined' ? Promise.resolve() : safari14Workaround()).then(() => new Promise((resolve, reject) => {\n // Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:\n // IE fails when deleting objectStore after reading from it.\n // A future version of Dexie.js will stopover an intermediate version to workaround this.\n // At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.\n \n throwIfCancelled();\n // If no API, throw!\n if (!indexedDB) throw new exceptions.MissingAPI();\n const dbName = db.name;\n \n const req = state.autoSchema ?\n indexedDB.open(dbName) :\n indexedDB.open(dbName, Math.round(db.verno * 10));\n if (!req) throw new exceptions.MissingAPI(); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134\n req.onerror = eventRejectHandler(reject);\n req.onblocked = wrap(db._fireOnBlocked);\n req.onupgradeneeded = wrap (e => {\n upgradeTransaction = req.transaction;\n if (state.autoSchema && !db._options.allowEmptyDB) { // Unless an addon has specified db._allowEmptyDB, lets make the call fail.\n // Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.\n // If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we\n // do not create a new database by accident here.\n req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!\n upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)\n // Close database and delete it.\n req.result.close();\n const delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!\n delreq.onsuccess = delreq.onerror = wrap(() => {\n reject (new exceptions.NoSuchDatabase(`Database ${dbName} doesnt exist`));\n });\n } else {\n upgradeTransaction.onerror = eventRejectHandler(reject);\n var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.\n wasCreated = oldVer < 1;\n db.idbdb = req.result;\n runUpgraders(db, oldVer / 10, upgradeTransaction, reject);\n }\n }, reject);\n \n req.onsuccess = wrap (() => {\n // Core opening procedure complete. Now let's just record some stuff.\n upgradeTransaction = null;\n const idbdb = db.idbdb = req.result;\n\n const objectStoreNames = slice(idbdb.objectStoreNames);\n if (objectStoreNames.length > 0) try {\n const tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), 'readonly');\n if (state.autoSchema) readGlobalSchema(db, idbdb, tmpTrans);\n else {\n adjustToExistingIndexNames(db, db._dbSchema, tmpTrans);\n if (!verifyInstalledSchema(db, tmpTrans)) {\n console.warn(`Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Some queries may fail.`);\n }\n }\n generateMiddlewareStacks(db, tmpTrans);\n } catch (e) {\n // Safari 8 may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.\n // BUGBUG: It will bail out anyway as of Dexie 3.\n // Should we support Safari 8 anymore? Believe all\n // Dexie users use the shim for that platform anyway?!\n // If removing Safari 8 support, go ahead and remove the safariMultiStoreFix() function\n // as well as absurd upgrade version quirk for Safari.\n }\n \n connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.\n \n idbdb.onversionchange = wrap(ev => {\n state.vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)\n db.on(\"versionchange\").fire(ev);\n });\n \n idbdb.onclose = wrap(ev => {\n db.on(\"close\").fire(ev);\n });\n\n if (wasCreated) _onDatabaseCreated(db._deps, dbName);\n\n resolve();\n\n }, reject);\n }))]).then(() => {\n // Before finally resolving the dbReadyPromise and this promise,\n // call and await all on('ready') subscribers:\n // Dexie.vip() makes subscribers able to use the database while being opened.\n // This is a must since these subscribers take part of the opening procedure.\n throwIfCancelled();\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>db.on.ready.fire(db.vip))).then(function fireRemainders() {\n if (state.onReadyBeingFired.length > 0) {\n // In case additional subscribers to db.on('ready') were added during the time db.on.ready.fire was executed.\n let remainders = state.onReadyBeingFired.reduce(promisableChain, nop);\n state.onReadyBeingFired = [];\n return Promise.resolve(vip(()=>remainders(db.vip))).then(fireRemainders)\n }\n });\n }).finally(()=>{\n if (state.openCanceller === openCanceller) {\n // Only modify state if not cancelled in the mean time.\n state.onReadyBeingFired = null;\n state.isBeingOpened = false;\n }\n }).catch(err => {\n state.dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.\n try {\n // Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.\n upgradeTransaction && upgradeTransaction.abort();\n } catch { }\n if (openCanceller === state.openCanceller) {\n // Still in the same open flow - The error reason was not due to external call to db.close().\n // Make sure to call db.close() to finalize resources.\n db._close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.\n }\n return rejection (err);\n }).finally(()=>{\n state.openComplete = true;\n resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.\n }).then(()=>{\n if (wasCreated) {\n // Propagate full range on primary keys and indexes on all tables now that the DB is ready and opened,\n // and all upgraders and on('ready') subscribers have run.\n const everything: ObservabilitySet = {};\n db.tables.forEach(table => {\n table.schema.indexes.forEach(idx => {\n if (idx.name) everything[`idb://${db.name}/${table.name}/${idx.name}`] = new RangeSet(-Infinity, [[[]]]);\n });\n everything[`idb://${db.name}/${table.name}/`] = everything[`idb://${db.name}/${table.name}/:dels`] = new RangeSet(-Infinity, [[[]]]);\n });\n // Database was created. If another tab had it open when it was deleted and reopened, that tab must be updated now.\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything);\n // Wipe the cache and trigger optimistic queries:\n signalSubscribersNow(everything, true);\n }\n // Resolve the db.open() with the db instance.\n return db;\n });\n}\n","import { isArray } from '../functions/utils';\n\nexport function awaitIterator (iterator: Iterator) {\n var callNext = result => iterator.next(result),\n doThrow = error => iterator.throw(error),\n onSuccess = step(callNext),\n onError = step(doThrow);\n\n function step(getNext: (any)=>any) {\n return (val?) => {\n var next = getNext(val),\n value = next.value;\n\n return next.done ? value :\n (!value || typeof value.then !== 'function' ?\n isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) :\n value.then(onSuccess, onError));\n };\n }\n\n return step(callNext)();\n}\n","import { TransactionMode } from '../../public/types/transaction-mode';\nimport { errnames, exceptions } from '../../errors';\nimport { flatten, isAsyncFunction } from '../../functions/utils';\nimport { Dexie } from './dexie';\nimport { Transaction } from '../transaction';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise, {\n PSD,\n NativePromise,\n decrementExpectedAwaits,\n rejection,\n incrementExpectedAwaits\n} from '../../helpers/promise';\n\nexport function extractTransactionArgs(mode: TransactionMode, _tableArgs_, scopeFunc) {\n // Let table arguments be all arguments between mode and last argument.\n var i = arguments.length;\n if (i < 2) throw new exceptions.InvalidArgument(\"Too few arguments\");\n // Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)\n // and clone arguments except the first one into local var 'args'.\n var args = new Array(i - 1);\n while (--i) args[i - 1] = arguments[i];\n // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.\n scopeFunc = args.pop();\n var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.\n return [mode, tables, scopeFunc];\n}\n\nexport function enterTransactionScope(\n db: Dexie,\n mode: IDBTransactionMode,\n storeNames: string[],\n parentTransaction: Transaction | undefined,\n scopeFunc: ()=>PromiseLike | any\n) {\n return Promise.resolve().then(() => {\n // Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().\n const transless = PSD.transless || PSD;\n // Our transaction.\n //return new Promise((resolve, reject) => {\n const trans = db._createTransaction(mode, storeNames, db._dbSchema, parentTransaction);\n trans.explicit = true;\n // Let the transaction instance be part of a Promise-specific data (PSD) value.\n const zoneProps = {\n trans: trans,\n transless: transless\n };\n\n if (parentTransaction) {\n // Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)\n trans.idbtrans = parentTransaction.idbtrans;\n } else {\n try {\n trans.create(); // Create the native transaction so that complete() or error() will trigger even if no operation is made upon it.\n db._state.PR1398_maxLoop = 3;\n } catch (ex) {\n if (ex.name === errnames.InvalidState && db.isOpen() && --db._state.PR1398_maxLoop > 0) {\n console.warn('Dexie: Need to reopen db');\n db._close();\n return db.open().then(() => enterTransactionScope(\n db,\n mode,\n storeNames,\n null,\n scopeFunc\n ));\n }\n return rejection(ex);\n }\n }\n\n // Support for native async await.\n const scopeFuncIsAsync = isAsyncFunction(scopeFunc);\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n\n let returnValue;\n const promiseFollowed = Promise.follow(() => {\n // Finally, call the scope function with our table and transaction arguments.\n returnValue = scopeFunc.call(trans, trans);\n if (returnValue) {\n if (scopeFuncIsAsync) {\n // scopeFunc is a native async function - we know for sure returnValue is native promise.\n var decrementor = decrementExpectedAwaits.bind(null, null);\n returnValue.then(decrementor, decrementor);\n } else if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {\n // scopeFunc returned an iterator with throw-support. Handle yield as await.\n returnValue = awaitIterator(returnValue);\n }\n }\n }, zoneProps);\n return (returnValue && typeof returnValue.then === 'function' ?\n // Promise returned. User uses promise-style transactions.\n Promise.resolve(returnValue).then(x => trans.active ?\n x // Transaction still active. Continue.\n : rejection(new exceptions.PrematureCommit(\n \"Transaction committed too early. See http://bit.ly/2kdckMn\")))\n // No promise returned. Wait for all outstanding promises before continuing. \n : promiseFollowed.then(() => returnValue)\n ).then(x => {\n // sub transactions don't react to idbtrans.oncomplete. We must trigger a completion:\n if (parentTransaction) trans._resolve();\n // wait for trans._completion\n // (if root transaction, this means 'complete' event. If sub-transaction, we've just fired it ourselves)\n return trans._completion.then(() => x);\n }).catch(e => {\n trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!\n return rejection(e);\n });\n });\n}\n","import {\n DBCore,\n DBCoreIndex,\n DBCoreKeyRange,\n DBCoreQueryRequest,\n DBCoreRangeType,\n DBCoreOpenCursorRequest,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreTable,\n} from \"../public/types/dbcore\";\nimport { isArray } from '../functions/utils';\nimport { getKeyExtractor } from './get-key-extractor';\nimport { getKeyPathAlias } from './dbcore-indexeddb';\nimport { Middleware } from '../public/types/middleware';\n\ninterface VirtualIndex extends DBCoreIndex {\n /** True if this index is virtual, i.e. represents a compound index internally,\n * but makes it act as as having a subset of its keyPaths.\n */\n isVirtual: boolean;\n\n /** Number of keypaths that this index comprises. Can be 0..N.\n * Note: This is the length of the *virtual index*, not the real index.\n */\n keyLength: number;\n\n /** Number of popped keypaths from the real index.\n */\n keyTail: number;\n\n /** LowLevelIndex represents the actual IndexedDB index behind it */\n lowLevelIndex: DBCoreIndex;\n}\n\n// Move into some util:\nexport function pad (a: any | any[], value: any, count: number) {\n const result = isArray(a) ? a.slice() : [a];\n for (let i=0; i 0;\n const virtualIndex = {\n ...lowLevelIndex,\n name: isVirtual\n ? `${keyPathAlias}(virtual-from:${lowLevelIndex.name})`\n : lowLevelIndex.name,\n lowLevelIndex,\n isVirtual,\n keyTail,\n keyLength,\n extractKey: getKeyExtractor(keyPath),\n unique: !isVirtual && lowLevelIndex.unique\n };\n indexList.push(virtualIndex);\n if (!virtualIndex.isPrimaryKey) {\n allVirtualIndexes.push(virtualIndex);\n }\n if (keyLength > 1) {\n const virtualKeyPath = keyLength === 2 ?\n keyPath[0] : // This is a compound [a, b]. Add a virtual normal index a.\n keyPath.slice(0, keyLength - 1); // This is compound [a,b,c]. Add virtual compound [a,b].\n addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex);\n }\n indexList.sort((a,b) => a.keyTail - b.keyTail); // Shortest keyTail is the best one (represents real index)\n return virtualIndex;\n }\n \n const primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);\n indexLookup[\":id\"] = [primaryKey];\n for (const index of schema.indexes) {\n addVirtualIndexes(index.keyPath, 0, index);\n }\n \n function findBestIndex(keyPath: null | string | string[]): VirtualIndex {\n const result = indexLookup[getKeyPathAlias(keyPath)];\n return result && result[0];\n }\n \n function translateRange (range: DBCoreKeyRange, keyTail: number): DBCoreKeyRange {\n return {\n type: range.type === DBCoreRangeType.Equal ?\n DBCoreRangeType.Range :\n range.type,\n lower: pad(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail),\n lowerOpen: true, // doesn't matter true or false\n upper: pad(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail),\n upperOpen: true // doesn't matter true or false\n };\n }\n \n function translateRequest (req: DBCoreQueryRequest): DBCoreQueryRequest;\n function translateRequest (req: DBCoreOpenCursorRequest): DBCoreOpenCursorRequest;\n function translateRequest (req: DBCoreCountRequest): DBCoreCountRequest {\n const index = req.query.index as VirtualIndex;\n return index.isVirtual ? {\n ...req,\n query: {\n index: index.lowLevelIndex,\n range: translateRange(req.query.range, index.keyTail)\n }\n } : req;\n }\n \n const result: DBCoreTable = {\n ...table,\n schema: {\n ...schema,\n primaryKey,\n indexes: allVirtualIndexes,\n getIndexByKeyPath: findBestIndex\n },\n\n count(req) {\n return table.count(translateRequest(req));\n }, \n \n query(req) {\n return table.query(translateRequest(req));\n },\n \n openCursor(req) {\n const {keyTail, isVirtual, keyLength} = (req.query.index as VirtualIndex);\n if (!isVirtual) return table.openCursor(req);\n \n function createVirtualCursor(cursor: DBCoreCursor) : DBCoreCursor {\n function _continue (key?: any) {\n key != null ?\n cursor.continue(pad(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) :\n req.unique ?\n cursor.continue(\n cursor.key.slice(0, keyLength)\n .concat(req.reverse\n ? down.MIN_KEY\n : down.MAX_KEY, keyTail)\n ) :\n cursor.continue()\n }\n const virtualCursor = Object.create(cursor, {\n continue: {value: _continue},\n continuePrimaryKey: {\n value(key: any, primaryKey: any) {\n cursor.continuePrimaryKey(pad(key, down.MAX_KEY, keyTail), primaryKey);\n }\n },\n primaryKey: {\n get() {\n return cursor.primaryKey;\n }\n },\n key: {\n get() {\n const key = cursor.key as any[]; // A virtual cursor always operates on compound key\n return keyLength === 1 ?\n key[0] : // Cursor.key should not be an array.\n key.slice(0, keyLength); // Cursor.key should be first part of array.\n }\n },\n value: {\n get() {\n return cursor.value;\n }\n }\n });\n return virtualCursor;\n }\n \n return table.openCursor(translateRequest(req))\n .then(cursor => cursor && createVirtualCursor(cursor));\n }\n };\n return result;\n }\n }\n}\n\nexport const virtualIndexMiddleware : Middleware = {\n stack: \"dbcore\",\n name: \"VirtualIndexMiddleware\",\n level: 1,\n create: createVirtualIndexMiddleware\n};\n\n","import { keys, hasOwn, toStringTag } from './utils';\n\nexport function getObjectDiff(a: any, b: any, rv?: any, prfx?: string) {\n // Compares objects a and b and produces a diff object.\n rv = rv || {};\n prfx = prfx || '';\n keys(a).forEach((prop) => {\n if (!hasOwn(b, prop)) {\n // Property removed\n rv[prfx + prop] = undefined;\n } else {\n var ap = a[prop],\n bp = b[prop];\n if (typeof ap === 'object' && typeof bp === 'object' && ap && bp) {\n const apTypeName = toStringTag(ap);\n const bpTypeName = toStringTag(bp);\n\n if (apTypeName !== bpTypeName) {\n rv[prfx + prop] = b[prop]; // Property changed to other type\n } else if (apTypeName === 'Object') {\n // Pojo objects (not Date, ArrayBuffer, Array etc). Go deep.\n getObjectDiff(ap, bp, rv, prfx + prop + '.');\n } else if (ap !== bp) {\n // Values differ.\n // Could have checked if Date, arrays or binary types have same\n // content here but I think that would be a suboptimation.\n // Prefer simplicity.\n rv[prfx + prop] = b[prop];\n }\n } else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed\n }\n });\n keys(b).forEach((prop) => {\n if (!hasOwn(a, prop)) {\n rv[prfx + prop] = b[prop]; // Property added\n }\n });\n return rv;\n}\n","import {\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreIndex,\n DBCoreTable,\n} from \"../public/types/dbcore\";\n\nexport function getEffectiveKeys (\n primaryKey: DBCoreIndex,\n req: (Pick & {keys?: any[]}) | Pick)\n{\n //const {outbound} = primaryKey;\n if (req.type === 'delete') return req.keys;\n return req.keys || req.values.map(primaryKey.extractKey)\n}\n","import {\n DBCore,\n DBCoreTable,\n DBCoreMutateResponse,\n DBCoreDeleteRangeRequest,\n DBCoreAddRequest,\n DBCorePutRequest,\n DBCoreDeleteRequest,\n DBCoreTransaction,\n DBCoreKeyRange\n} from \"../public/types/dbcore\";\nimport { nop } from '../functions/chaining-functions';\nimport { hasOwn, setByKeyPath } from '../functions/utils';\nimport { getObjectDiff } from \"../functions/get-object-diff\";\nimport { PSD } from '../helpers/promise';\n//import { LockableTableMiddleware } from '../dbcore/lockable-table-middleware';\nimport { getEffectiveKeys } from '../dbcore/get-effective-keys';\nimport { Middleware } from '../public/types/middleware';\nimport { Transaction } from '../classes/transaction';\n\nexport const hooksMiddleware: Middleware = {\n stack: \"dbcore\",\n name: \"HooksMiddleware\",\n level: 2,\n create: (downCore: DBCore) => ({\n ...downCore,\n table(tableName: string) {\n const downTable = downCore.table(tableName);\n const {primaryKey} = downTable.schema;\n \n const tableMiddleware: DBCoreTable = {\n ...downTable,\n mutate(req):Promise {\n const dxTrans = PSD.trans as Transaction;\n // Hooks can be transaction-bound. Need to grab them from transaction.table and not\n // db.table!\n const {deleting, creating, updating} = dxTrans.table(tableName).hook;\n switch (req.type) {\n case 'add':\n if (creating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'put':\n if (creating.fire === nop && updating.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'delete':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>addPutOrDelete(req), true);\n case 'deleteRange':\n if (deleting.fire === nop) break;\n return dxTrans._promise('readwrite', ()=>deleteRange(req), true);\n }\n // Any of the breaks above happened (no hooks) - do the default:\n return downTable.mutate(req);\n\n\n function addPutOrDelete(req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest): Promise {\n const dxTrans = PSD.trans;\n const keys = req.keys || getEffectiveKeys(primaryKey, req);\n if (!keys) throw new Error(\"Keys missing\");\n // Clone Request and set keys arg\n req = req.type === 'add' || req.type === 'put' ?\n {...req, keys} :\n {...req};\n if (req.type !== 'delete') req.values = [...req.values];\n if (req.keys) req.keys = [...req.keys];\n \n return getExistingValues(downTable, req, keys).then (existingValues => {\n const contexts = keys.map((key, i) => {\n const existingValue = existingValues[i];\n const ctx = { onerror: null, onsuccess: null };\n if (req.type === 'delete') {\n // delete operation\n deleting.fire.call(ctx, key, existingValue, dxTrans);\n } else if (req.type === 'add' || existingValue === undefined) {\n // The add() or put() resulted in a create\n const generatedPrimaryKey = creating.fire.call(ctx, key, req.values[i], dxTrans);\n if (key == null && generatedPrimaryKey != null) {\n key = generatedPrimaryKey;\n req.keys[i] = key;\n if (!primaryKey.outbound) {\n setByKeyPath(req.values[i], primaryKey.keyPath, key);\n }\n }\n } else {\n // The put() operation resulted in an update\n const objectDiff = getObjectDiff(existingValue, req.values[i]);\n const additionalChanges = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans);\n if (additionalChanges) {\n const requestedValue = req.values[i];\n Object.keys(additionalChanges).forEach(keyPath => {\n if (hasOwn(requestedValue, keyPath)) {\n // keyPath is already present as a literal property of the object\n requestedValue[keyPath] = additionalChanges[keyPath];\n } else {\n // keyPath represents a new or existing path into the object\n setByKeyPath(requestedValue, keyPath, additionalChanges[keyPath]);\n }\n });\n }\n }\n return ctx;\n });\n return downTable.mutate(req).then(({failures, results, numFailures, lastResult}) => {\n for (let i=0; i {\n contexts.forEach(ctx => ctx.onerror && ctx.onerror(error));\n return Promise.reject(error);\n });\n });\n }\n \n function deleteRange(req: DBCoreDeleteRangeRequest): Promise {\n return deleteNextChunk(req.trans, req.range, 10000);\n }\n \n function deleteNextChunk(trans: DBCoreTransaction, range: DBCoreKeyRange, limit: number) {\n // Query what keys in the DB within the given range\n return downTable.query({trans, values: false, query: {index: primaryKey, range}, limit})\n .then(({result}) => {\n // Given a set of keys, bulk delete those using the same procedure as in addPutOrDelete().\n // This will make sure that deleting hook is called.\n return addPutOrDelete({type: 'delete', keys: result, trans}).then(res => {\n if (res.numFailures > 0) return Promise.reject(res.failures[0]);\n if (result.length < limit) {\n return {failures: [], numFailures: 0, lastResult: undefined} as DBCoreMutateResponse;\n } else {\n return deleteNextChunk(trans, {...range, lower: result[result.length - 1], lowerOpen: true}, limit);\n }\n });\n })\n }\n }\n };\n //const {lock, lockableMiddleware} = LockableTableMiddleware(tableMiddleware);\n\n return tableMiddleware;\n },\n }) as DBCore\n};\n\nfunction getExistingValues(\n table: DBCoreTable,\n req: DBCoreAddRequest | DBCorePutRequest | DBCoreDeleteRequest,\n effectiveKeys: any[]\n) {\n return req.type === \"add\"\n ? Promise.resolve([])\n : table.getMany({ trans: req.trans, keys: effectiveKeys, cache: \"immutable\" });\n}\n","import { deepClone } from \"../functions/utils\";\nimport { DBCore } from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport Promise from \"../helpers/promise\";\nimport { cmp } from '../functions/cmp';\n\nexport function getFromTransactionCache(\n keys: readonly any[],\n cache: { keys: any[]; values: any[] } | undefined | null,\n clone?: boolean\n) {\n try {\n if (!cache) return null;\n if (cache.keys.length < keys.length) return null;\n const result: any[] = [];\n // Compare if the exact same order of keys was retrieved in same transaction:\n // Allow some cached keys to be omitted from provided set of keys\n // Use case: 1. getMany(keys) 2. update a subset of those 3. call put with the updated ones ==> middlewares should be able to find old values\n for (let i = 0, j = 0; i < cache.keys.length && j < keys.length; ++i) {\n if (cmp(cache.keys[i], keys[j]) !== 0) continue;\n result.push(clone ? deepClone(cache.values[i]) : cache.values[i]);\n ++j;\n }\n // If got all keys caller was looking for, return result.\n return result.length === keys.length ? result : null;\n } catch {\n return null;\n }\n}\n\nexport const cacheExistingValuesMiddleware: Middleware = {\n stack: \"dbcore\",\n level: -1,\n create: (core) => {\n return {\n table: (tableName) => {\n const table = core.table(tableName);\n return {\n ...table,\n getMany: (req) => {\n if (!req.cache) {\n return table.getMany(req);\n }\n const cachedResult = getFromTransactionCache(\n req.keys,\n req.trans[\"_cache\"],\n req.cache === \"clone\"\n );\n if (cachedResult) {\n return Promise.resolve(cachedResult);\n }\n return table.getMany(req).then((res) => {\n req.trans[\"_cache\"] = {\n keys: req.keys,\n values: req.cache === \"clone\" ? deepClone(res) : res,\n };\n return res;\n });\n },\n mutate: (req) => {\n // Invalidate cache on any mutate except \"add\" which can't change existing values:\n if (req.type !== \"add\") req.trans[\"_cache\"] = null;\n return table.mutate(req);\n },\n };\n },\n };\n },\n};\n","import { DBCore, DBCoreTable } from '../../public/types/dbcore';\nimport { LiveQueryContext } from '../live-query';\n\nexport function isCachableContext(ctx: LiveQueryContext, table: DBCoreTable) {\n return (\n ctx.trans.mode === 'readonly' &&\n !!ctx.subscr &&\n !ctx.trans.explicit &&\n ctx.trans.db._options.cache !== 'disabled' &&\n !table.schema.primaryKey.outbound\n );\n}\n\n","import { DBCoreCountRequest, DBCoreGetManyRequest, DBCoreGetRequest, DBCoreOpenCursorRequest, DBCoreQueryRequest } from '../../public/types/dbcore';\n\n\nexport function isCachableRequest(type: string, req: Partial) {\n switch (type) {\n case 'query':\n return req.values && !req.unique;\n case 'get':\n return false;\n case 'getMany':\n return false;\n case 'count':\n return false;\n case 'openCursor':\n return false;\n }\n}\n","import { LiveQueryContext } from \".\";\nimport { getFromTransactionCache } from \"../dbcore/cache-existing-values-middleware\";\nimport { getEffectiveKeys } from \"../dbcore/get-effective-keys\";\nimport { exceptions } from \"../errors\";\nimport { cmp } from \"../functions/cmp\";\nimport { isArray, keys } from \"../functions/utils\";\nimport { PSD } from \"../helpers/promise\";\nimport { RangeSet } from \"../helpers/rangeset\";\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport {\n DBCore,\n DBCoreCountRequest,\n DBCoreCursor,\n DBCoreGetManyRequest,\n DBCoreGetRequest,\n DBCoreIndex,\n DBCoreOpenCursorRequest,\n DBCoreQueryRequest,\n DBCoreQueryResponse,\n DBCoreTable,\n DBCoreTableSchema,\n DBCoreTransaction,\n} from \"../public/types/dbcore\";\nimport { Middleware } from \"../public/types/middleware\";\nimport { isCachableContext } from \"./cache/is-cachable-context\";\nimport { isCachableRequest } from \"./cache/is-cachable-request\";\nimport { extendObservabilitySet } from \"./extend-observability-set\";\n\nexport const observabilityMiddleware: Middleware = {\n stack: \"dbcore\",\n level: 0,\n name: \"Observability\",\n create: (core) => {\n const dbName = core.schema.name;\n const FULL_RANGE = new RangeSet(core.MIN_KEY, core.MAX_KEY);\n\n return {\n ...core,\n transaction: (stores, mode, options) => {\n if (PSD.subscr && mode !== 'readonly') {\n throw new exceptions.ReadOnly(`Readwrite transaction in liveQuery context. Querier source: ${(PSD as LiveQueryContext).querier}`);\n }\n return core.transaction(stores, mode, options);\n },\n table: (tableName) => {\n const table = core.table(tableName);\n const { schema } = table;\n const { primaryKey } = schema;\n const { extractKey, outbound } = primaryKey;\n const tableClone: DBCoreTable = {\n ...table,\n mutate: (req) => {\n const trans = req.trans as DBCoreTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n const mutatedParts = req.mutatedParts || (req.mutatedParts = {});\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (mutatedParts[part] ||\n (mutatedParts[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n\n const { type } = req;\n let [keys, newObjs] =\n req.type === \"deleteRange\"\n ? [req.range] // keys will be an DBCoreKeyRange object - transformed later on to a [from,to]-style range.\n : req.type === \"delete\"\n ? [req.keys] // keys known already here. newObjs will be undefined.\n : req.values.length < 50\n ? [getEffectiveKeys(primaryKey, req).filter(id => id), req.values] // keys except autoIncremented - they will be added later on.\n : []; // keys and newObjs will both be undefined - changeSpec will become true (changed for entire table)\n\n const oldCache = req.trans[\"_cache\"];\n\n // Add the mutated table and optionally keys to the mutatedTables set on the transaction.\n // Used by subscribers to txcommit event and for Collection.prototype.subscribe().\n if (isArray(keys)) {\n // keys is an array - delete, add or put of less than 50 rows.\n // Individual keys (add put or delete)\n pkRangeSet.addKeys(keys);\n // Only get oldObjs if they have been cached recently\n // (This applies to Collection.modify() only, but also if updating/deleting hooks have subscribers)\n const oldObjs = type === 'delete' || keys.length === newObjs.length ? getFromTransactionCache(keys, oldCache) : null;\n\n // Supply detailed values per index for both old and new objects:\n if (!oldObjs && type !== \"add\") {\n // delete or put and we don't know old values.\n // Indicate this in the \":dels\" part, for the sake of count() queries only!\n delsRangeSet.addKeys(keys);\n }\n if (oldObjs || newObjs) {\n // No matter if knowning oldObjs or not, track the indices if it's a put, add or delete.\n trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs);\n }\n } else if (keys) {\n // keys is a DBCoreKeyRange object. Transform it to [from,to]-style range.\n // As we can't know deleted index ranges, mark index-based subscriptions must trigger.\n const range = { from: keys.lower, to: keys.upper };\n delsRangeSet.add(range);\n // deleteRange. keys is a DBCoreKeyRange objects. Transform it to [from,to]-style range.\n pkRangeSet.add(range);\n } else {\n // Too many requests to record the details without slowing down write performance.\n // Let's just record a generic large range on primary key, the virtual :dels index and\n // all secondary indices:\n pkRangeSet.add(FULL_RANGE);\n delsRangeSet.add(FULL_RANGE);\n schema.indexes.forEach(idx => getRangeSet(idx.name).add(FULL_RANGE));\n }\n\n return table.mutate(req).then((res) => {\n // Merge the mutated parts from the request into the transaction's mutatedParts\n // now when the request went fine.\n if (keys && (req.type === 'add' || req.type === 'put')) {\n // Less than 50 requests (keys truthy) (otherwise we've added full range anyway)\n // autoincrement means we might not have got all keys until now\n pkRangeSet.addKeys(res.results);\n }\n trans.mutatedParts = extendObservabilitySet (\n trans.mutatedParts || {},\n mutatedParts\n );\n return res;\n });\n },\n };\n\n const getRange: (req: any) => [DBCoreIndex, RangeSet] = ({\n query: { index, range },\n }:\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest) => [\n index,\n new RangeSet(range.lower ?? core.MIN_KEY, range.upper ?? core.MAX_KEY),\n ];\n\n const readSubscribers: {[method in\n Exclude]: \n (req: any) => [DBCoreIndex, RangeSet]\n } = {\n get: (req) => [primaryKey, new RangeSet(req.key)],\n getMany: (req) => [primaryKey, new RangeSet().addKeys(req.keys)],\n count: getRange,\n query: getRange,\n openCursor: getRange,\n }\n\n keys(readSubscribers).forEach(method => {\n tableClone[method] = function (\n req:\n | DBCoreGetRequest\n | DBCoreGetManyRequest\n | DBCoreQueryRequest\n | DBCoreCountRequest\n | DBCoreOpenCursorRequest\n ) {\n const { subscr } = PSD as LiveQueryContext;\n const isLiveQuery = !!subscr;\n let cachable = isCachableContext(PSD as LiveQueryContext, table) && isCachableRequest(method, req);\n const obsSet = cachable\n ? req.obsSet = {} // Implicit read transaction - track changes for this query only for the request's duration\n : subscr; // Explicit read transaction - track changes across entire live query\n\n if (isLiveQuery) {\n // Current zone want's to track all queries so they can be subscribed to.\n // (The query is executed within a \"liveQuery\" zone)\n // Check whether the query applies to a certain set of ranges:\n // Track what we should be observing:\n const getRangeSet = (indexName: string) => {\n const part = `idb://${dbName}/${tableName}/${indexName}`;\n return (obsSet[part] ||\n (obsSet[part] = new RangeSet())) as RangeSet;\n };\n const pkRangeSet = getRangeSet(\"\");\n const delsRangeSet = getRangeSet(\":dels\");\n const [queriedIndex, queriedRanges] = readSubscribers[method](req);\n // A generic rule here: queried ranges should always be subscribed to.\n getRangeSet(queriedIndex.name || \"\").add(queriedRanges);\n if (!queriedIndex.isPrimaryKey) {\n // Only count(), query() and openCursor() operates on secondary indices.\n // Since put(), delete() and deleteRange() mutations may happen without knowing oldObjs,\n // the mutate() method will be missing what secondary indices that are being deleted from\n // the subscribed range. We are working around this issue by recording all the resulting\n // primary keys from the queries. This only works for those kinds of queries where we can\n // derive the primary key from the result.\n // In this block we are accomplishing this using various strategies depending on the properties\n // of the query result.\n\n if (method === \"count\") {\n // We've got a problem! Delete and put mutations happen without known the oldObjs.\n // Those mutation could change the count.\n // Solution: Dedicated \":dels\" url represends a subscription to all mutations without oldObjs\n // (specially triggered in the mutators put(), delete() and deleteRange() when they don't know oldObject)\n delsRangeSet.add(FULL_RANGE);\n } else {\n // openCursor() or query()\n\n // Prepare a keysPromise in case the we're doing an IDBIndex.getAll() on a store with outbound keys.\n const keysPromise =\n method === \"query\" &&\n outbound &&\n (req as DBCoreQueryRequest).values &&\n table.query({\n ...(req as DBCoreQueryRequest),\n values: false,\n });\n\n return table[method].apply(this, arguments).then((res) => {\n if (method === \"query\") {\n if (outbound && (req as DBCoreQueryRequest).values) {\n // If keys are outbound, we can't use extractKey to map what keys to observe.\n // We've queried an index (like 'dateTime') on an outbound table\n // and retrieve a list of objects\n // from who we cannot know their primary keys.\n // \"Luckily\" though, we've prepared the keysPromise to assist us in exact this condition.\n return keysPromise.then(\n ({ result: resultingKeys }: DBCoreQueryResponse) => {\n pkRangeSet.addKeys(resultingKeys);\n return res;\n }\n );\n }\n // query() inbound values, keys or outbound keys. Secondary indexes only since\n // for primary keys we would only add results within the already registered range.\n const pKeys = (req as DBCoreQueryRequest).values\n ? (res as DBCoreQueryResponse).result.map(extractKey)\n : (res as DBCoreQueryResponse).result;\n if ((req as DBCoreQueryRequest).values) {\n // Subscribe to any mutation made on the returned keys,\n // so that we detect both deletions and updated properties.\n pkRangeSet.addKeys(pKeys);\n } else {\n // Subscribe only to mutations on the returned keys\n // in case the mutator was unable to know oldObjs.\n // If it has oldObj, the mutator won't put anything in \":dels\" because\n // it can more fine-grained put the exact removed and added index value in the correct\n // index range that we subscribe to in the queried range sets.\n // We don't load values so a change on a property outside our index will not\n // require us to re-execute the query.\n delsRangeSet.addKeys(pKeys);\n }\n } else if (method === \"openCursor\") {\n // Caller requests a cursor.\n // For the same reason as when method===\"query\", we only need to observe\n // those keys whose values are possibly used or rendered - which could\n // only happen on keys where they get the cursor's key, primaryKey or value.\n const cursor: DBCoreCursor | null = res;\n const wantValues = (req as DBCoreOpenCursorRequest).values;\n return (\n cursor &&\n Object.create(cursor, {\n key: {\n get() {\n delsRangeSet.addKey(cursor.primaryKey);\n return cursor.key;\n },\n },\n primaryKey: {\n get() {\n const pkey = cursor.primaryKey;\n delsRangeSet.addKey(pkey);\n return pkey;\n },\n },\n value: {\n get() {\n wantValues && pkRangeSet.addKey(cursor.primaryKey);\n return cursor.value;\n },\n },\n })\n );\n }\n return res;\n });\n }\n }\n }\n return table[method].apply(this, arguments);\n };\n });\n return tableClone;\n },\n };\n },\n};\n\nfunction trackAffectedIndexes(\n getRangeSet: (index: string) => RangeSet,\n schema: DBCoreTableSchema,\n oldObjs: readonly any[] | undefined,\n newObjs: readonly any[] | undefined\n) {\n function addAffectedIndex(ix: DBCoreIndex) {\n const rangeSet = getRangeSet(ix.name || \"\");\n function extractKey(obj: any) {\n return obj != null ? ix.extractKey(obj) : null;\n }\n const addKeyOrKeys = (key: any) => ix.multiEntry && isArray(key)\n // multiEntry and the old property was an array - add each array entry to the rangeSet:\n ? key.forEach(key => rangeSet.addKey(key))\n // Not multiEntry or the old property was not an array - add each array entry to the rangeSet:\n : rangeSet.addKey(key);\n\n (oldObjs || newObjs).forEach((_, i) => {\n const oldKey = oldObjs && extractKey(oldObjs[i]);\n const newKey = newObjs && extractKey(newObjs[i]);\n if (cmp(oldKey, newKey) !== 0) {\n // The index has changed. Add both old and new value of the index.\n if (oldKey != null) addKeyOrKeys(oldKey); // If oldKey is invalid key, addKey() will be a noop.\n if (newKey != null) addKeyOrKeys(newKey); // If newKey is invalid key, addKey() will be a noop.\n }\n });\n }\n schema.indexes.forEach(addAffectedIndex);\n}\n","import { cmp } from '../../functions/cmp';\nimport { IndexableType } from '../../public';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function isAboveLower(key: IndexableType, range: DBCoreKeyRange) {\n return range.lower === undefined\n ? true // lower is less than anything because it is undefined\n : range.lowerOpen\n ? cmp(key, range.lower) > 0 // lowerOpen: Exclude lower bound\n : cmp(key, range.lower) >= 0; // !lowerOpen: Include lower bound\n}\n\nexport function isBelowUpper(key: IndexableType, range: DBCoreKeyRange) {\n return range.upper === undefined\n ? true // upper is greater than anything because it is undefined\n : range.upperOpen\n ? cmp(key, range.upper) < 0 // upperOpen: Exclude upper bound\n : cmp(key, range.upper) <= 0; // !upperOpen: Include upper bound\n}\n\nexport function isWithinRange(key: IndexableType, range: DBCoreKeyRange) {\n return isAboveLower(key, range) && isBelowUpper(key, range);\n}\n","import { cmp } from '../../functions/cmp';\nimport { deepClone } from '../../functions/utils';\nimport { RangeSet, rangesOverlap } from '../../helpers/rangeset';\nimport { CacheEntry } from '../../public/types/cache';\nimport {\n DBCoreIndex,\n DBCoreMutateRequest,\n DBCoreQueryRequest,\n DBCoreTable,\n} from '../../public/types/dbcore';\nimport { isWithinRange } from './is-within-range';\n\nexport function applyOptimisticOps(\n result: any[],\n req: DBCoreQueryRequest,\n ops: DBCoreMutateRequest[] | undefined,\n table: DBCoreTable,\n cacheEntry: CacheEntry,\n immutable: boolean\n): any[] {\n if (!ops || ops.length === 0) return result;\n const index = req.query.index;\n const primaryKey = table.schema.primaryKey;\n const extractPrimKey = primaryKey.extractKey;\n const extractIndex = index.extractKey;\n const extractLowLevelIndex = (index.lowLevelIndex || index).extractKey;\n\n let finalResult = ops.reduce((result, op) => {\n let modifedResult = result;\n const includedValues =\n op.type === 'add' || op.type === 'put'\n ? op.values.filter((v) =>\n isWithinRange(extractIndex(v), req.query.range)\n ).map(v => {\n v = deepClone(v);// v might come from user so we can't just freeze it.\n if (immutable) Object.freeze(v);\n return v;\n }) \n : [];\n switch (op.type) {\n case 'add':\n modifedResult = result.concat(\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n case 'put':\n const keySet = new RangeSet().addKeys(\n op.values.map((v) => extractPrimKey(v))\n );\n modifedResult = result\n .filter((item) => {\n const key = req.values ? extractPrimKey(item) : item;\n return !rangesOverlap(new RangeSet(key), keySet);\n })\n .concat(\n req.values\n ? includedValues\n : includedValues.map((v) => extractPrimKey(v))\n );\n break;\n case 'delete':\n const keysToDelete = new RangeSet().addKeys(op.keys);\n modifedResult = result.filter((item) => {\n const key = req.values ? extractPrimKey(item) : item;\n return !rangesOverlap(new RangeSet(key), keysToDelete);\n });\n\n break;\n case 'deleteRange':\n const range = op.range;\n modifedResult = result.filter((item) => !isWithinRange(extractPrimKey(item), range));\n break;\n }\n return modifedResult;\n }, result);\n\n // If no changes were made, we can return the original result.\n if (finalResult === result) return result;\n\n // Sort the result on sortIndex:\n finalResult.sort((a, b) =>\n cmp(extractLowLevelIndex(a), extractLowLevelIndex(b)) ||\n cmp(extractPrimKey(a), extractPrimKey(b))\n );\n\n // If we have a limit we need to respect it:\n if (req.limit && req.limit < Infinity) {\n if (finalResult.length > req.limit) {\n finalResult.length = req.limit; // Cut of any extras after sorting correctly.\n } else if (result.length === req.limit && finalResult.length < req.limit) {\n // We're missing some items because of the limit. We need to add them back.\n // The easiest way is to mark the cache entry as dirty, which will cause\n // it to be requeried after the write-transaction successfully completes.\n cacheEntry.dirty = true;\n }\n }\n return immutable ? Object.freeze(finalResult) as any[] : finalResult;\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function areRangesEqual(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n cmp(r1.lower, r2.lower) === 0 &&\n cmp(r1.upper, r2.upper) === 0 &&\n !!r1.lowerOpen === !!r2.lowerOpen &&\n !!r1.upperOpen === !!r2.upperOpen\n );\n}\n","import { cmp } from '../../functions/cmp';\nimport { DBCoreKeyRange } from '../../public/types/dbcore';\n\nexport function compareLowers(lower1: any, lower2: any, lowerOpen1: boolean, lowerOpen2: boolean) {\n if (lower1 === undefined) return lower2 !== undefined ? -1 : 0;\n if (lower2 === undefined) return 1; // since lower1 !== undefined\n const c = cmp(lower1, lower2);\n if (c === 0) {\n if (lowerOpen1 && lowerOpen2) return 0;\n if (lowerOpen1) return 1\n if (lowerOpen2) return -1;\n }\n return c;\n}\n\nexport function compareUppers(upper1: any, upper2: any, upperOpen1: boolean, upperOpen2: boolean) {\n if (upper1 === undefined) return upper2 !== undefined ? 1 : 0;\n if (upper2 === undefined) return -1; // since upper1 !== undefined\n const c = cmp(upper1, upper2);\n if (c === 0) {\n if (upperOpen1 && upperOpen2) return 0;\n if (upperOpen1) return -1\n if (upperOpen2) return 1;\n }\n return c;\n}\n\nexport function isSuperRange(r1: DBCoreKeyRange, r2: DBCoreKeyRange) {\n return (\n compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 &&\n compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0\n );\n}","import { CacheEntry, TblQueryCache } from '../../public/types/cache';\nimport {\n DBCoreCountRequest,\n DBCoreQueryRequest,\n} from '../../public/types/dbcore';\nimport { areRangesEqual } from './are-ranges-equal';\nimport { cache } from './cache';\nimport { isSuperRange } from './is-super-range';\n\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query',\n req: DBCoreQueryRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'count',\n req: DBCoreCountRequest\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]];\nexport function findCompatibleQuery(\n dbName: string,\n tableName: string,\n type: 'query' | 'count',\n req: Partial & Partial\n): [] | [CacheEntry, boolean, TblQueryCache, CacheEntry[]] {\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return [];\n const queries = tblCache.queries[type];\n if (!queries) return [null, false, tblCache, null];\n const indexName = req.query ? req.query.index.name : null;\n const entries = queries[indexName || ''];\n if (!entries) return [null, false, tblCache, null];\n\n switch (type) {\n case 'query':\n const equalEntry = entries.find(\n (entry) =>\n (entry.req as DBCoreQueryRequest).limit === req.limit &&\n (entry.req as DBCoreQueryRequest).values === req.values &&\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n if (equalEntry)\n return [\n equalEntry,\n true, // exact match\n tblCache,\n entries,\n ];\n const superEntry = entries.find((entry) => {\n const limit = 'limit' in entry.req ? entry.req.limit : Infinity;\n return (\n limit >= req.limit &&\n (req.values ? (entry.req as DBCoreQueryRequest).values : true) &&\n isSuperRange(entry.req.query.range, req.query.range)\n );\n });\n return [superEntry, false, tblCache, entries];\n case 'count':\n const countQuery = entries.find((entry) =>\n areRangesEqual(entry.req.query.range, req.query.range)\n );\n return [countQuery, !!countQuery, tblCache, entries];\n }\n}\n","import { delArrayItem } from \"../../functions/utils\";\nimport { CacheEntry } from \"../../public/types/cache\";\n\nexport function subscribeToCacheEntry(cacheEntry: CacheEntry, container: CacheEntry[], requery: ()=>void, signal: AbortSignal) {\n cacheEntry.subscribers.add(requery);\n signal.addEventListener(\"abort\", () => {\n cacheEntry.subscribers.delete(requery);\n if (cacheEntry.subscribers.size === 0) {\n enqueForDeletion(cacheEntry, container);\n }\n });\n}\n\n\nfunction enqueForDeletion(cacheEntry: CacheEntry, container: CacheEntry[]) {\n setTimeout(() => {\n if (cacheEntry.subscribers.size === 0) { // Still empty (no new subscribers readded after grace time)\n delArrayItem(container, cacheEntry);\n }\n }, 3000);\n}\n","import { LiveQueryContext } from '..';\nimport { getEffectiveKeys } from '../../dbcore/get-effective-keys';\nimport { deepClone, delArrayItem, setByKeyPath } from '../../functions/utils';\nimport DexiePromise, { PSD } from '../../helpers/promise';\nimport { ObservabilitySet } from '../../public/types/db-events';\nimport {\n DBCore, DBCoreQueryRequest,\n DBCoreQueryResponse\n} from '../../public/types/dbcore';\nimport { Middleware } from '../../public/types/middleware';\nimport { applyOptimisticOps } from './apply-optimistic-ops';\nimport { cache } from './cache';\nimport { findCompatibleQuery } from './find-compatible-query';\nimport { isCachableContext } from './is-cachable-context';\nimport { isCachableRequest } from './is-cachable-request';\nimport { signalSubscribersLazily } from './signalSubscribers';\nimport { subscribeToCacheEntry } from './subscribe-cachentry';\n\nexport const cacheMiddleware: Middleware = {\n stack: 'dbcore',\n level: 0,\n name: 'Cache',\n create: (core) => {\n const dbName = core.schema.name;\n const coreMW: DBCore = {\n ...core,\n transaction: (stores, mode, options) => {\n const idbtrans = core.transaction(\n stores,\n mode,\n options\n ) as IDBTransaction & {\n mutatedParts?: ObservabilitySet;\n };\n // Maintain TblQueryCache.ops array when transactions commit or abort\n if (mode === 'readwrite') {\n const ac = new AbortController();\n const { signal } = ac;\n const endTransaction = (wasCommitted: boolean) => () => {\n ac.abort();\n if (mode === 'readwrite') {\n // Collect which subscribers to notify:\n const affectedSubscribers = new Set<()=>void>();\n\n // Go through all tables in transaction and check if they have any optimistic updates\n for (const storeName of stores) {\n const tblCache = cache[`idb://${dbName}/${storeName}`];\n const table = core.table(storeName);\n if (tblCache) {\n // Pick optimistic ops that are part of this transaction\n const ops = tblCache.optimisticOps.filter(\n (op) => op.trans === idbtrans\n );\n if (ops.length > 0) {\n // Remove them from the optimisticOps array\n tblCache.optimisticOps = tblCache.optimisticOps.filter(\n (op) => op.trans !== idbtrans\n );\n // Commit or abort the optimistic updates\n for (const entries of Object.values(\n tblCache.queries.query\n )) {\n for (const entry of entries.slice()) {\n if (\n entry.res != null && // if entry.promise but not entry.res, we're fine. Query will resume now and get the result.\n idbtrans.mutatedParts/* &&\n obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)*/\n ) {\n if (wasCommitted && !entry.dirty) {\n const freezeResults = Object.isFrozen(entry.res);\n const modRes = applyOptimisticOps(\n entry.res as any[],\n entry.req,\n ops,\n table,\n entry,\n freezeResults\n );\n if (entry.dirty) {\n // Found out at this point that the entry is dirty - not to rely on!\n delArrayItem(entries, entry);\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n } else if (modRes !== entry.res) {\n entry.res = modRes;\n // Update promise\n entry.promise = DexiePromise.resolve({result: modRes} satisfies DBCoreQueryResponse);\n \n // No need to notify subscribers. They already have this value.\n // We have just updated the value of the cache without having to\n // requery the database - because we know the result for this\n // query based on computing the operations and applying them\n // to the previous result.\n }\n } else {\n if (entry.dirty) {\n // If the entry is dirty we need to get rid of it so that\n // a new entry will be created when the query is run again.\n delArrayItem(entries, entry);\n }\n // If we're not committing, we need to notify subscribers that the\n // optimistic updates are no longer valid.\n entry.subscribers.forEach((requery) => affectedSubscribers.add(requery));\n }\n }\n }\n }\n }\n }\n }\n affectedSubscribers.forEach((requery) => requery());\n }\n };\n idbtrans.addEventListener('abort', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('error', endTransaction(false), {\n signal,\n });\n idbtrans.addEventListener('complete', endTransaction(true), {\n signal,\n });\n }\n return idbtrans;\n },\n table(tableName: string) {\n const downTable = core.table(tableName);\n const primKey = downTable.schema.primaryKey;\n const tableMW = {\n ...downTable,\n mutate(req) {\n if (\n primKey.outbound || // Non-inbound tables are harded to apply optimistic updates on because we can't know primary key of results\n PSD.trans.db._options.cache === 'disabled' // User has opted-out from caching\n ) {\n // Just forward the request to the core.\n return downTable.mutate(req);\n }\n // Find the TblQueryCache for this table:\n const tblCache = cache[`idb://${dbName}/${tableName}`];\n if (!tblCache) return downTable.mutate(req);\n\n const promise = downTable.mutate(req);\n if ((req.type === 'add' || req.type === 'put') && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(key => key == null))) {\n // There are some autoIncremented keys not set yet. Need to wait for completion before we can reliably enqueue the operation.\n // (or there are too many objects so we lazy out to avoid performance bottleneck for large bulk inserts)\n promise.then((res) => { // We need to extract result keys and generate cloned values with the keys set (so that applyOptimisticOps can work)\n // But we have a problem! The req.mutatedParts is still not complete so we have to actively add the keys to the unsignaledParts set manually.\n const reqWithResolvedKeys = {\n ...req,\n values: req.values.map((value, i) => {\n const valueWithKey = primKey.keyPath.includes('.')\n ? deepClone(value)\n : {\n ...value,\n };\n setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]);\n return valueWithKey;\n })\n };\n tblCache.optimisticOps.push(reqWithResolvedKeys);\n // Signal subscribers after the observability middleware has complemented req.mutatedParts with the new keys.\n // We must queue the task so that we get the req.mutatedParts updated by observability middleware first.\n // If we refactor the dependency between observability middleware and this middleware we might not need to queue the task.\n queueMicrotask(()=>signalSubscribersLazily(req.mutatedParts)); // Reason for double laziness: in user awaits put and then does another put, signal once.\n });\n } else {\n // Enque the operation immediately\n tblCache.optimisticOps.push(req);\n // Signal subscribers that there are mutated parts\n signalSubscribersLazily(req.mutatedParts);\n promise.catch(()=> {\n // In case the operation failed, we need to remove it from the optimisticOps array.\n delArrayItem(tblCache.optimisticOps, req);\n signalSubscribersLazily(req.mutatedParts); // Signal the rolling back of the operation.\n });\n }\n return promise;\n },\n query(req: DBCoreQueryRequest): Promise {\n if (!isCachableContext(PSD, downTable) || !isCachableRequest(\"query\", req)) return downTable.query(req);\n const freezeResults =\n (PSD as LiveQueryContext).trans.db._options.cache === 'immutable';\n const { requery, signal } = PSD as LiveQueryContext;\n let [cacheEntry, exactMatch, tblCache, container] =\n findCompatibleQuery(dbName, tableName, 'query', req);\n if (cacheEntry && exactMatch) {\n cacheEntry.obsSet = req.obsSet; // So that optimistic result is monitored.\n // How? - because observability-middleware will track result where optimistic\n // mutations are applied and record it in the cacheEntry.\n // TODO: CHANGE THIS! The difference is resultKeys only.\n // Wanted behavior:\n // * cacheEntry obsSet should represent the obsSet without optimistic updates (so it can be checked when merging ops in tx commit)\n // * cacheEntry optimisticObsSet should represent the obsSet with current optimistic updates. It should be updated when adding an op\n // by adding the primary keys of the put/add/delete operation to the set.\n // * observability-middleware should stop recording req.obsSet when a cache entry exact match is found because it won't be used anyway.\n // I'm thinking of merging observability-middleware with cache-middleware into one single middleware because the dependencies are too\n // tight between them.\n } else {\n // --> TODO here: If not exact match, check if we have a superset to extract\n // the data from.\n\n // No cached result found. We need to query the database and cache the result.\n const promise = downTable.query(req).then((res) => {\n // Freeze or clone results\n const result = res.result;\n cacheEntry.res = result;\n if (freezeResults) {\n // For performance reasons don't deep freeze.\n // Only freeze the top-level array and its items.\n // This is good enough to teach users that the result must be treated as immutable\n // without enforcing it recursively on the entire result (which is not even possible\n // for things like Date objects and typed arrays)\n for (let i = 0, l = result.length; i < l; ++i) {\n Object.freeze(result[i]);\n }\n Object.freeze(result);\n } else {\n // If not frozen, we need to clone the result to avoid user mutating the cache\n // When we do this, user's must feel conformable with the fact that the result\n // can be mutated deeply - user is not expected to have any respect for immutability.\n res.result = deepClone(result);\n }\n return res;\n }).catch(error => {\n // In case the query operation failed, we need to remove it from the cache\n // so that subsequent calls does not get the same error but re-evaluate\n // the query.\n if (container && cacheEntry) delArrayItem(container, cacheEntry);\n return Promise.reject(error);\n });\n cacheEntry = {\n obsSet: req.obsSet,\n promise,\n subscribers: new Set(),\n type: 'query',\n req,\n dirty: false,\n };\n if (container) {\n container.push(cacheEntry);\n } else {\n container = [cacheEntry];\n if (!tblCache) {\n tblCache = cache[`idb://${dbName}/${tableName}`] = {\n queries: {\n query: {},\n count: {},\n },\n objs: new Map(),\n optimisticOps: [],\n unsignaledParts: {}\n };\n }\n tblCache.queries.query[req.query.index.name || ''] = container;\n }\n }\n subscribeToCacheEntry(cacheEntry, container, requery, signal);\n return cacheEntry.promise.then((res: DBCoreQueryResponse) => {\n return {\n result: applyOptimisticOps(\n res.result,\n req,\n tblCache?.optimisticOps,\n downTable,\n cacheEntry,\n freezeResults\n ) as any[], // readonly any[]\n };\n });\n },\n };\n return tableMW;\n },\n };\n return coreMW;\n },\n};\n\n\n","import { type Dexie } from \"../classes/dexie\";\nimport { type Table } from \"../classes/table\";\nimport { type Transaction } from \"../classes/transaction\";\n\nexport function vipify(\n target: T,\n vipDb: Dexie\n): T {\n return new Proxy(target, {\n get (target, prop, receiver) {\n // The \"db\" prop of the table or transaction is the only one we need to\n // override. The rest of the props can be accessed from the original\n // object.\n if (prop === 'db') return vipDb;\n return Reflect.get(target, prop, receiver);\n }\n });\n}\n","// Import types from the public API\nimport { Dexie as IDexie } from \"../../public/types/dexie\";\nimport { DexieOptions, DexieConstructor } from \"../../public/types/dexie-constructor\";\nimport { DbEvents } from \"../../public/types/db-events\";\n//import { PromiseExtended, PromiseExtendedConstructor } from '../../public/types/promise-extended';\nimport { Table as ITable } from '../../public/types/table';\nimport { TableSchema } from \"../../public/types/table-schema\";\nimport { DbSchema } from '../../public/types/db-schema';\n\n// Internal imports\nimport { Table, TableConstructor, createTableConstructor } from \"../table\";\nimport { Collection, CollectionConstructor, createCollectionConstructor } from '../collection';\nimport { WhereClause } from '../where-clause/where-clause';\nimport { WhereClauseConstructor, createWhereClauseConstructor } from '../where-clause/where-clause-constructor';\nimport { Transaction } from '../transaction';\nimport { TransactionConstructor, createTransactionConstructor } from '../transaction/transaction-constructor';\nimport { Version } from \"../version/version\";\nimport { VersionConstructor, createVersionConstructor } from '../version/version-constructor';\n\n// Other imports...\nimport { DexieEventSet } from '../../public/types/dexie-event-set';\nimport { DexieExceptionClasses } from '../../public/types/errors';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\nimport { nop, promisableChain } from '../../functions/chaining-functions';\nimport Promise, { PSD, globalPSD } from '../../helpers/promise';\nimport { extend, override, keys, hasOwn } from '../../functions/utils';\nimport Events from '../../helpers/Events';\nimport { maxString, connections, READONLY, READWRITE } from '../../globals/constants';\nimport { getMaxKey } from '../../functions/quirks';\nimport { exceptions } from '../../errors';\nimport { lowerVersionFirst } from '../version/schema-helpers';\nimport { dexieOpen } from './dexie-open';\nimport { wrap } from '../../helpers/promise';\nimport { _onDatabaseDeleted } from '../../helpers/database-enumerator';\nimport { eventRejectHandler } from '../../functions/event-wrappers';\nimport { extractTransactionArgs, enterTransactionScope } from './transaction-helpers';\nimport { TransactionMode } from '../../public/types/transaction-mode';\nimport { rejection } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { DBCore } from '../../public/types/dbcore';\nimport { Middleware, DexieStacks } from '../../public/types/middleware';\nimport { virtualIndexMiddleware } from '../../dbcore/virtual-index-middleware';\nimport { hooksMiddleware } from '../../hooks/hooks-middleware';\nimport { IndexableType } from '../../public';\nimport { observabilityMiddleware } from '../../live-query/observability-middleware';\nimport { cacheExistingValuesMiddleware } from '../../dbcore/cache-existing-values-middleware';\nimport { cacheMiddleware } from \"../../live-query/cache/cache-middleware\";\nimport { vipify } from \"../../helpers/vipify\";\n\nexport interface DbReadyState {\n dbOpenError: any;\n isBeingOpened: boolean;\n onReadyBeingFired: undefined | Function[];\n openComplete: boolean;\n dbReadyResolve: () => void;\n dbReadyPromise: Promise;\n cancelOpen: (reason?: Error) => void;\n openCanceller: Promise & { _stackHolder?: Error };\n autoSchema: boolean;\n vcFired?: boolean;\n PR1398_maxLoop?: number;\n}\n\nexport class Dexie implements IDexie {\n _options: DexieOptions;\n _state: DbReadyState;\n _versions: Version[];\n _storeNames: string[];\n _deps: DexieDOMDependencies;\n _allTables: { [name: string]: Table; };\n _createTransaction: (this: Dexie, mode: IDBTransactionMode, storeNames: ArrayLike, dbschema: { [tableName: string]: TableSchema; }, parentTransaction?: Transaction) => Transaction;\n _dbSchema: { [tableName: string]: TableSchema; };\n _hasGetAll?: boolean;\n _maxKey: IndexableType;\n _fireOnBlocked: (ev: Event) => void;\n _middlewares: {[StackName in keyof DexieStacks]?: Middleware[]} = {};\n _vip?: boolean;\n _novip: Dexie;// db._novip is to escape to orig db from db.vip.\n core: DBCore;\n\n name: string;\n verno: number = 0;\n idbdb: IDBDatabase | null;\n vip: Dexie;\n on: DbEvents;\n\n Table: TableConstructor;\n WhereClause: WhereClauseConstructor;\n Collection: CollectionConstructor;\n Version: VersionConstructor;\n Transaction: TransactionConstructor;\n\n constructor(name: string, options?: DexieOptions) {\n const deps = (Dexie as any as DexieConstructor).dependencies;\n this._options = options = {\n // Default Options\n addons: (Dexie as any as DexieConstructor).addons, // Pick statically registered addons by default\n autoOpen: true, // Don't require db.open() explicitely.\n // Default DOM dependency implementations from static prop.\n indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to browser env.\n IDBKeyRange: deps.IDBKeyRange, // Backend IDBKeyRange api. Default to browser env.\n cache: 'cloned', // Default to cloned for backward compatibility. For best performance and least memory consumption use 'immutable'.\n ...options\n }; \n this._deps = {\n indexedDB: options.indexedDB as IDBFactory,\n IDBKeyRange: options.IDBKeyRange as typeof IDBKeyRange\n };\n const {\n addons,\n } = options;\n this._dbSchema = {};\n this._versions = [];\n this._storeNames = [];\n this._allTables = {};\n this.idbdb = null;\n this._novip = this;\n const state: DbReadyState = {\n dbOpenError: null,\n isBeingOpened: false,\n onReadyBeingFired: null,\n openComplete: false,\n dbReadyResolve: nop,\n dbReadyPromise: null as Promise,\n cancelOpen: nop,\n openCanceller: null as Promise,\n autoSchema: true,\n PR1398_maxLoop: 3\n };\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n this._state = state;\n this.name = name;\n this.on = Events(this, \"populate\", \"blocked\", \"versionchange\", \"close\", { ready: [promisableChain, nop] }) as DbEvents;\n this.on.ready.subscribe = override(this.on.ready.subscribe, subscribe => {\n return (subscriber, bSticky) => {\n (Dexie as any as DexieConstructor).vip(() => {\n const state = this._state;\n if (state.openComplete) {\n // Database already open. Call subscriber asap.\n if (!state.dbOpenError) Promise.resolve().then(subscriber);\n // bSticky: Also subscribe to future open sucesses (after close / reopen) \n if (bSticky) subscribe(subscriber);\n } else if (state.onReadyBeingFired) {\n // db.on('ready') subscribers are currently being executed and have not yet resolved or rejected\n state.onReadyBeingFired.push(subscriber);\n if (bSticky) subscribe(subscriber);\n } else {\n // Database not yet open. Subscribe to it.\n subscribe(subscriber);\n // If bSticky is falsy, make sure to unsubscribe subscriber when fired once.\n const db = this;\n if (!bSticky) subscribe(function unsubscribe() {\n db.on.ready.unsubscribe(subscriber);\n db.on.ready.unsubscribe(unsubscribe);\n });\n }\n });\n }\n });\n\n // Create derived classes bound to this instance of Dexie:\n this.Collection = createCollectionConstructor(this);\n this.Table = createTableConstructor(this);\n this.Transaction = createTransactionConstructor(this);\n this.Version = createVersionConstructor(this);\n this.WhereClause = createWhereClauseConstructor(this);\n\n // Default subscribers to \"versionchange\" and \"blocked\".\n // Can be overridden by custom handlers. If custom handlers return false, these default\n // behaviours will be prevented.\n this.on(\"versionchange\", ev => {\n // Default behavior for versionchange event is to close database connection.\n // Caller can override this behavior by doing db.on(\"versionchange\", function(){ return false; });\n // Let's not block the other window from making it's delete() or open() call.\n // NOTE! This event is never fired in IE,Edge or Safari.\n if (ev.newVersion > 0)\n console.warn(`Another connection wants to upgrade database '${this.name}'. Closing db now to resume the upgrade.`);\n else\n console.warn(`Another connection wants to delete database '${this.name}'. Closing db now to resume the delete request.`);\n this.close({disableAutoOpen: false});\n this._state.openComplete = false;\n // In many web applications, it would be recommended to force window.reload()\n // when this event occurs. To do that, subscribe to the versionchange event\n // and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)\n // The reason for this is that your current web app obviously has old schema code that needs\n // to be updated. Another window got a newer version of the app and needs to upgrade DB but\n // your window is blocking it unless we close it here.\n });\n this.on(\"blocked\", ev => {\n if (!ev.newVersion || ev.newVersion < ev.oldVersion)\n console.warn(`Dexie.delete('${this.name}') was blocked`);\n else\n console.warn(`Upgrade '${this.name}' blocked by other connection holding version ${ev.oldVersion / 10}`);\n });\n\n this._maxKey = getMaxKey(options.IDBKeyRange as typeof IDBKeyRange);\n\n this._createTransaction = (\n mode: IDBTransactionMode,\n storeNames: string[],\n dbschema: DbSchema,\n parentTransaction?: Transaction) => new this.Transaction(mode, storeNames, dbschema, this._options.chromeTransactionDurability, parentTransaction);\n\n this._fireOnBlocked = ev => {\n this.on(\"blocked\").fire(ev);\n // Workaround (not fully*) for missing \"versionchange\" event in IE,Edge and Safari:\n connections\n .filter(c => c.name === this.name && c !== this && !c._state.vcFired)\n .map(c => c.on(\"versionchange\").fire(ev));\n }\n\n // Default middlewares:\n this.use(cacheExistingValuesMiddleware);\n this.use(cacheMiddleware);\n this.use(observabilityMiddleware);\n this.use(virtualIndexMiddleware);\n this.use(hooksMiddleware);\n\n const vipDB = new Proxy(this, {\n get: (_, prop, receiver) => {\n if (prop === '_vip') return true;\n if (prop === 'table') return (tableName: string) => vipify(this.table(tableName), vipDB);\n const rv = Reflect.get(_, prop, receiver);\n if (rv instanceof Table) return vipify(rv, vipDB);\n if (prop === 'tables') return (rv as Table[]).map(t => vipify(t, vipDB));\n if (prop === '_createTransaction') return function() {\n const tx: Transaction = (rv as typeof this._createTransaction).apply(this, arguments);\n return vipify(tx, vipDB);\n }\n return rv;\n }\n });\n this.vip = vipDB;\n\n // Call each addon:\n addons.forEach(addon => addon(this));\n }\n\n version(versionNumber: number): Version {\n if (isNaN(versionNumber) || versionNumber < 0.1) throw new exceptions.Type(`Given version is not a positive number`);\n versionNumber = Math.round(versionNumber * 10) / 10;\n if (this.idbdb || this._state.isBeingOpened)\n throw new exceptions.Schema(\"Cannot add version when database is open\");\n this.verno = Math.max(this.verno, versionNumber);\n const versions = this._versions;\n var versionInstance = versions.filter(\n v => v._cfg.version === versionNumber)[0];\n if (versionInstance) return versionInstance;\n versionInstance = new this.Version(versionNumber);\n versions.push(versionInstance);\n versions.sort(lowerVersionFirst);\n versionInstance.stores({}); // Derive earlier schemas by default.\n // Disable autoschema mode, as at least one version is specified.\n this._state.autoSchema = false;\n return versionInstance;\n }\n\n _whenReady(fn: () => Promise): Promise {\n return (this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip)) ? fn() : new Promise((resolve, reject) => {\n if (this._state.openComplete) {\n // idbdb is falsy but openComplete is true. Must have been an exception durin open.\n // Don't wait for openComplete as it would lead to infinite loop.\n return reject(new exceptions.DatabaseClosed(this._state.dbOpenError));\n }\n if (!this._state.isBeingOpened) {\n if (!this._options.autoOpen) {\n reject(new exceptions.DatabaseClosed());\n return;\n }\n this.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.\n }\n this._state.dbReadyPromise.then(resolve, reject);\n }).then(fn);\n }\n\n use({stack, create, level, name}: Middleware): this {\n if (name) this.unuse({stack, name}); // Be able to replace existing middleware.\n const middlewares = this._middlewares[stack] || (this._middlewares[stack] = []);\n middlewares.push({stack, create, level: level == null ? 10 : level, name});\n middlewares.sort((a, b) => a.level - b.level);\n // Todo update db.core and db.tables...core ? Or should be expect this to have effect\n // only after next open()?\n return this;\n }\n\n unuse({stack, create}: Middleware<{stack: keyof DexieStacks}>): this;\n unuse({stack, name}: {stack: keyof DexieStacks, name: string}): this;\n unuse({stack, name, create}: {stack: keyof DexieStacks, name?: string, create?: Function}) {\n if (stack && this._middlewares[stack]) {\n this._middlewares[stack] = this._middlewares[stack].filter(mw =>\n create ? mw.create !== create : // Given middleware has a create method. Match that exactly.\n name ? mw.name !== name : // Given middleware spec \n false);\n }\n return this;\n }\n\n open() {\n return usePSD(\n globalPSD, // Enforce global scope here since db.open() can be part of a live query or transaction scope\n () => dexieOpen(this)\n );\n }\n\n _close(): void {\n const state = this._state;\n const idx = connections.indexOf(this);\n if (idx >= 0) connections.splice(idx, 1);\n if (this.idbdb) {\n try { this.idbdb.close(); } catch (e) { }\n this.idbdb = null;\n } \n // Reset dbReadyPromise promise:\n state.dbReadyPromise = new Promise(resolve => {\n state.dbReadyResolve = resolve;\n });\n state.openCanceller = new Promise((_, reject) => {\n state.cancelOpen = reject;\n });\n }\n\n close({disableAutoOpen} = {disableAutoOpen: true}): void {\n this._close();\n const state = this._state;\n if (disableAutoOpen) this._options.autoOpen = false;\n state.dbOpenError = new exceptions.DatabaseClosed();\n if (state.isBeingOpened)\n state.cancelOpen(state.dbOpenError);\n }\n\n delete(): Promise {\n const hasArguments = arguments.length > 0;\n const state = this._state;\n return new Promise((resolve, reject) => {\n const doDelete = () => {\n this.close({disableAutoOpen: false});\n var req = this._deps.indexedDB.deleteDatabase(this.name);\n req.onsuccess = wrap(() => {\n _onDatabaseDeleted(this._deps, this.name);\n resolve();\n });\n req.onerror = eventRejectHandler(reject);\n req.onblocked = this._fireOnBlocked;\n }\n\n if (hasArguments) throw new exceptions.InvalidArgument(\"Arguments not allowed in db.delete()\");\n if (state.isBeingOpened) {\n state.dbReadyPromise.then(doDelete);\n } else {\n doDelete();\n }\n });\n }\n\n backendDB() {\n return this.idbdb;\n }\n\n isOpen() {\n return this.idbdb !== null;\n }\n\n hasBeenClosed() {\n const dbOpenError = this._state.dbOpenError;\n return dbOpenError && (dbOpenError.name === 'DatabaseClosed');\n }\n\n hasFailed() {\n return this._state.dbOpenError !== null;\n }\n\n dynamicallyOpened() {\n return this._state.autoSchema;\n }\n\n get tables () {\n return keys(this._allTables).map(name => this._allTables[name]);\n }\n\n transaction(): Promise {\n const args = extractTransactionArgs.apply(this, arguments);\n return this._transaction.apply(this, args);\n }\n\n _transaction(mode: TransactionMode, tables: Array, scopeFunc: Function) {\n let parentTransaction = PSD.trans as Transaction | undefined;\n // Check if parent transactions is bound to this db instance, and if caller wants to reuse it\n if (!parentTransaction || parentTransaction.db !== this || mode.indexOf('!') !== -1) parentTransaction = null;\n const onlyIfCompatible = mode.indexOf('?') !== -1;\n mode = mode.replace('!', '').replace('?', '') as TransactionMode; // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.\n let idbMode: IDBTransactionMode,\n storeNames;\n\n try {\n //\n // Get storeNames from arguments. Either through given table instances, or through given table names.\n //\n storeNames = tables.map(table => {\n var storeName = table instanceof this.Table ? table.name : table;\n if (typeof storeName !== 'string') throw new TypeError(\"Invalid table argument to Dexie.transaction(). Only Table or String are allowed\");\n return storeName;\n });\n\n //\n // Resolve mode. Allow shortcuts \"r\" and \"rw\".\n //\n if (mode == \"r\" || mode === READONLY)\n idbMode = READONLY;\n else if (mode == \"rw\" || mode == READWRITE)\n idbMode = READWRITE;\n else\n throw new exceptions.InvalidArgument(\"Invalid transaction mode: \" + mode);\n\n if (parentTransaction) {\n // Basic checks\n if (parentTransaction.mode === READONLY && idbMode === READWRITE) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY\");\n }\n if (parentTransaction) {\n storeNames.forEach(storeName => {\n if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) {\n if (onlyIfCompatible) {\n // Spawn new transaction instead.\n parentTransaction = null; \n }\n else throw new exceptions.SubTransaction(\"Table \" + storeName +\n \" not included in parent transaction.\");\n }\n });\n }\n if (onlyIfCompatible && parentTransaction && !parentTransaction.active) {\n // '?' mode should not keep using an inactive transaction.\n parentTransaction = null;\n }\n }\n } catch (e) {\n return parentTransaction ?\n parentTransaction._promise(null, (_, reject) => {reject(e);}) :\n rejection (e);\n }\n // If this is a sub-transaction, lock the parent and then launch the sub-transaction.\n const enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc);\n return (parentTransaction ?\n parentTransaction._promise(idbMode, enterTransaction, \"lock\") :\n PSD.trans ?\n // no parent transaction despite PSD.trans exists. Make sure also\n // that the zone we create is not a sub-zone of current, because\n // Promise.follow() should not wait for it if so.\n usePSD(PSD.transless, ()=>this._whenReady(enterTransaction)) :\n this._whenReady (enterTransaction));\n }\n\n table(tableName: string): Table;\n table(tableName: string): ITable;\n table(tableName: string): Table {\n if (!hasOwn(this._allTables, tableName)) {\n throw new exceptions.InvalidTable(`Table ${tableName} does not exist`); }\n return this._allTables[tableName];\n }\n}\n","import {\n Observable as IObservable,\n Observer,\n Subscription,\n} from \"../../public/types/observable\";\n\nconst symbolObservable: typeof Symbol.observable =\n typeof Symbol !== \"undefined\" && \"observable\" in Symbol\n ? Symbol.observable\n : \"@@observable\" as any;\n\nexport class Observable implements IObservable {\n private _subscribe: (observer: Observer) => Subscription;\n hasValue?: ()=>boolean;\n getValue?: ()=>T;\n\n constructor(subscribe: (observer: Observer) => Subscription) {\n this._subscribe = subscribe;\n }\n\n subscribe(\n onNext?: ((value: T) => void) | null,\n onError?: ((error: any) => void) | null,\n onComplete?: (() => void) | null\n ): Subscription;\n subscribe(observer?: Observer | null): Subscription;\n subscribe(x?: any, error?: any, complete?: any): Subscription {\n return this._subscribe(\n !x || typeof x === \"function\" ? { next: x, error, complete } : x\n );\n }\n\n [symbolObservable]() {\n return this;\n }\n}\n","import { _global } from '../../globals/global';\nimport { DexieDOMDependencies } from '../../public/types/dexie-dom-dependencies';\n\nexport let domDeps: DexieDOMDependencies\n\ntry {\n domDeps = {\n // Required:\n indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,\n IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange\n };\n} catch (e) {\n domDeps = { indexedDB: null, IDBKeyRange: null };\n}\n","import { isAsyncFunction, keys, objectIsEmpty } from '../functions/utils';\nimport {\n globalEvents,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport {\n beginMicroTickScope,\n decrementExpectedAwaits,\n endMicroTickScope,\n incrementExpectedAwaits,\n newScope,\n PSD,\n usePSD,\n} from '../helpers/promise';\nimport { ObservabilitySet } from '../public/types/db-events';\nimport {\n Observable as IObservable,\n Subscription,\n} from '../public/types/observable';\nimport { Observable } from '../classes/observable/observable';\nimport { extendObservabilitySet } from './extend-observability-set';\nimport { rangesOverlap } from '../helpers/rangeset';\nimport { domDeps } from '../classes/dexie/dexie-dom-dependencies';\nimport { Transaction } from '../classes/transaction';\nimport { obsSetsOverlap } from './obs-sets-overlap';\n\nexport interface LiveQueryContext {\n subscr: ObservabilitySet;\n signal: AbortSignal;\n requery: () => void;\n trans: null | Transaction;\n querier: Function; // For debugging purposes and Error messages\n}\n\nexport function liveQuery(querier: () => T | Promise): IObservable {\n let hasValue = false;\n let currentValue: T;\n const observable = new Observable((observer) => {\n const scopeFuncIsAsync = isAsyncFunction(querier);\n function execute(ctx: LiveQueryContext) {\n const wasRootExec = beginMicroTickScope(); // Performance: Avoid starting a new microtick scope within the async context.\n try {\n if (scopeFuncIsAsync) {\n incrementExpectedAwaits();\n }\n const rv = newScope(querier, ctx);\n if (scopeFuncIsAsync) {\n (rv as Promise).finally(decrementExpectedAwaits);\n }\n return rv;\n } finally {\n wasRootExec && endMicroTickScope(); // Given that we created the microtick scope, we must also end it.\n }\n }\n\n let closed = false;\n let abortController: AbortController;\n\n let accumMuts: ObservabilitySet = {};\n let currentObs: ObservabilitySet = {};\n\n const subscription: Subscription = {\n get closed() {\n return closed;\n },\n unsubscribe: () => {\n if (closed) return;\n closed = true;\n if (abortController) abortController.abort();\n if (startedListening) globalEvents.storagemutated.unsubscribe(mutationListener);\n },\n };\n\n observer.start && observer.start(subscription); // https://github.com/tc39/proposal-observable\n\n let startedListening = false;\n\n function shouldNotify() {\n return obsSetsOverlap(currentObs, accumMuts);\n }\n\n const mutationListener = (parts: ObservabilitySet) => {\n extendObservabilitySet(accumMuts, parts);\n if (shouldNotify()) {\n doQuery();\n }\n };\n\n const doQuery = () => {\n if (\n closed || // closed - don't run!\n !domDeps.indexedDB) // SSR in sveltekit, nextjs etc\n {\n return;\n }\n accumMuts = {};\n const subscr: ObservabilitySet = {};\n // Abort signal fill three purposes:\n // 1. Abort the query if the observable is unsubscribed.\n // 2. Abort the query if a new query is made before the previous one has completed.\n // 3. For cached queries to know if they should remain in memory or could be enqued for being freed up.\n // (they will remain in memory for a short time and if noone needs them again, they will eventually be freed up)\n if (abortController) abortController.abort(); // Cancel previous query. Last query will be cancelled on unsubscribe().\n abortController = new AbortController();\n \n const ctx: LiveQueryContext = {\n subscr,\n signal: abortController.signal,\n requery: doQuery,\n querier,\n trans: null // Make the scope transactionless (don't reuse transaction from outer scope of the caller of subscribe())\n }\n const ret = execute(ctx);\n Promise.resolve(ret).then(\n (result) => {\n hasValue = true;\n currentValue = result;\n if (closed || ctx.signal.aborted) {\n // closed - no subscriber anymore.\n // signal.aborted - new query was made before this one completed and\n // the querier might have catched AbortError and return successful result.\n // If so, we should not rely in that result because we know we have aborted\n // this run, which means there's another run going on that will handle accumMuts\n // and we must not base currentObs on the half-baked subscr.\n return;\n }\n accumMuts = {};\n // Update what we are subscribing for based on this last run:\n currentObs = subscr;\n if (!objectIsEmpty(currentObs) && !startedListening) {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, mutationListener);\n startedListening = true;\n } \n observer.next && observer.next(result);\n },\n (err) => {\n hasValue = false;\n if (!['DatabaseClosedError', 'AbortError'].includes(err?.name)) {\n if (closed) return;\n observer.error && observer.error(err);\n }\n }\n );\n };\n\n doQuery();\n return subscription;\n });\n observable.hasValue = () => hasValue;\n observable.getValue = () => currentValue;\n return observable;\n}\n","import { Dexie as _Dexie } from './dexie';\nimport { _global } from '../../globals/global';\nimport { props, derive, extend, override, getByKeyPath, setByKeyPath, delByKeyPath, shallowClone, deepClone, asap } from '../../functions/utils';\nimport { getObjectDiff } from \"../../functions/get-object-diff\";\nimport { fullNameExceptions } from '../../errors';\nimport { DexieConstructor } from '../../public/types/dexie-constructor';\nimport { getDatabaseNames } from '../../helpers/database-enumerator';\nimport { PSD } from '../../helpers/promise';\nimport { usePSD } from '../../helpers/promise';\nimport { newScope } from '../../helpers/promise';\nimport { rejection } from '../../helpers/promise';\nimport { awaitIterator } from '../../helpers/yield-support';\nimport Promise from '../../helpers/promise';\nimport * as Debug from '../../helpers/debug';\nimport { dexieStackFrameFilter, minKey, connections, DEXIE_VERSION } from '../../globals/constants';\nimport Events from '../../helpers/Events';\nimport { exceptions } from '../../errors';\nimport { errnames } from '../../errors';\nimport { getMaxKey } from '../../functions/quirks';\nimport { vip } from './vip';\nimport { globalEvents } from '../../globals/global-events';\nimport { liveQuery } from '../../live-query/live-query';\nimport { extendObservabilitySet } from '../../live-query/extend-observability-set';\nimport { domDeps } from './dexie-dom-dependencies';\nimport { cmp } from '../../functions/cmp';\nimport { cache } from '../../live-query/cache/cache';\n\n/* (Dexie) is an instance of DexieConstructor, as defined in public/types/dexie-constructor.d.ts\n* (new Dexie()) is an instance of Dexie, as defined in public/types/dexie.d.ts\n* \n* Why we're doing this?\n\n* Because we've choosen to define the public Dexie API using a DexieConstructor interface\n* rather than declaring a class. On that interface, all static props are defined.\n* In practice, class Dexie's constructor implements DexieConstructor and all member props\n* are defined in interface Dexie. We could say, it's a typescript limitation of not being\n* able to define a static interface that forces us to do the cast below.\n*/\nconst Dexie = _Dexie as any as DexieConstructor;\n\n//\n// Set all static methods and properties onto Dexie:\n// \nprops(Dexie, {\n\n // Dexie.BulkError = class BulkError {...};\n // Dexie.XXXError = class XXXError {...};\n ...fullNameExceptions,\n\n //\n // Static delete() method.\n //\n delete(databaseName: string) {\n const db = new Dexie(databaseName, {addons: []});\n return db.delete();\n },\n\n //\n // Static exists() method.\n //\n exists(name: string) {\n return new Dexie(name, { addons: [] }).open().then(db => {\n db.close();\n return true;\n }).catch('NoSuchDatabaseError', () => false);\n },\n\n //\n // Static method for retrieving a list of all existing databases at current host.\n //\n getDatabaseNames(cb) {\n try {\n return getDatabaseNames(Dexie.dependencies).then(cb);\n } catch {\n return rejection(new exceptions.MissingAPI());\n }\n },\n\n /** @deprecated */\n defineClass() {\n function Class(content) {\n extend(this, content);\n }\n return Class;\n },\n\n ignoreTransaction(scopeFunc) {\n // In case caller is within a transaction but needs to create a separate transaction.\n // Example of usage:\n //\n // Let's say we have a logger function in our app. Other application-logic should be unaware of the\n // logger function and not need to include the 'logentries' table in all transaction it performs.\n // The logging should always be done in a separate transaction and not be dependant on the current\n // running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.\n //\n // Dexie.ignoreTransaction(function() {\n // db.logentries.add(newLogEntry);\n // });\n //\n // Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction\n // in current Promise-scope.\n //\n // An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an\n // API for this because\n // 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().\n // 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().\n // 3) setImmediate() is not supported in the ES standard.\n // 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.\n return PSD.trans ?\n usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.\n scopeFunc(); // No need to change scope because there is no ongoing transaction.\n },\n\n vip,\n\n async: function (generatorFn: Function) {\n return function () {\n try {\n var rv = awaitIterator(generatorFn.apply(this, arguments));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n };\n },\n\n spawn: function (generatorFn, args, thiz) {\n try {\n var rv = awaitIterator(generatorFn.apply(thiz, args || []));\n if (!rv || typeof rv.then !== 'function')\n return Promise.resolve(rv);\n return rv;\n } catch (e) {\n return rejection(e);\n }\n },\n\n // Dexie.currentTransaction property\n currentTransaction: {\n get: () => PSD.trans || null\n },\n\n waitFor: function (promiseOrFunction, optionalTimeout) {\n // If a function is provided, invoke it and pass the returning value to Transaction.waitFor()\n const promise = Promise.resolve(\n typeof promiseOrFunction === 'function' ?\n Dexie.ignoreTransaction(promiseOrFunction) :\n promiseOrFunction)\n .timeout(optionalTimeout || 60000); // Default the timeout to one minute. Caller may specify Infinity if required. \n\n // Run given promise on current transaction. If no current transaction, just return a Dexie promise based\n // on given value.\n return PSD.trans ?\n PSD.trans.waitFor(promise) :\n promise;\n },\n\n // Export our Promise implementation since it can be handy as a standalone Promise implementation\n Promise: Promise,\n\n // Dexie.debug proptery:\n // Dexie.debug = false\n // Dexie.debug = true\n // Dexie.debug = \"dexie\" - don't hide dexie's stack frames.\n debug: {\n get: () => Debug.debug,\n set: value => {\n Debug.setDebug(value, value === 'dexie' ? () => true : dexieStackFrameFilter);\n }\n },\n\n // Export our derive/extend/override methodology\n derive: derive, // Deprecate?\n extend: extend, // Deprecate?\n props: props,\n override: override, // Deprecate?\n // Export our Events() function - can be handy as a toolkit\n Events: Events,\n on: globalEvents,\n liveQuery,\n extendObservabilitySet,\n // Utilities\n getByKeyPath: getByKeyPath,\n setByKeyPath: setByKeyPath,\n delByKeyPath: delByKeyPath,\n shallowClone: shallowClone,\n deepClone: deepClone,\n getObjectDiff: getObjectDiff,\n cmp,\n asap: asap,\n //maxKey: new Dexie('',{addons:[]})._maxKey,\n minKey: minKey,\n // Addon registry\n addons: [],\n // Global DB connection list\n connections: connections,\n\n //MultiModifyError: exceptions.Modify, // Obsolete!\n errnames: errnames,\n\n // Export other static classes\n //IndexSpec: IndexSpec, Obsolete!\n //TableSchema: TableSchema, Obsolete!\n\n //\n // Dependencies\n //\n // These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.\n //\n // In node.js, however, these properties must be set \"manually\" before instansiating a new Dexie().\n // For node.js, you need to require indexeddb-js or similar and then set these deps.\n //\n dependencies: domDeps,\n cache,\n\n // API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.\n semVer: DEXIE_VERSION,\n version: DEXIE_VERSION.split('.')\n .map(n => parseInt(n))\n .reduce((p, c, i) => p + (c / Math.pow(10, i * 2))),\n\n // https://github.com/dfahlander/Dexie.js/issues/186\n // typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return\n // x.default. Workaround: Set Dexie.default = Dexie.\n // default: Dexie, // Commented because solved in index-umd.ts instead.\n // Make it possible to import {Dexie} (non-default import)\n // Reason 1: May switch to that in future.\n // Reason 2: We declare it both default and named exported in d.ts to make it possible\n // to let addons extend the Dexie interface with Typescript 2.1 (works only when explicitely\n // exporting the symbol, not just default exporting)\n // Dexie: Dexie // Commented because solved in index-umd.ts instead.\n});\n\nDexie.maxKey = getMaxKey(Dexie.dependencies.IDBKeyRange);\n","import { isIEOrEdge } from '../globals/constants';\nimport { globalEvents, DEXIE_STORAGE_MUTATED_EVENT_NAME, STORAGE_MUTATED_DOM_EVENT_NAME } from '../globals/global-events';\nimport { ObservabilitySet } from \"../public/types/db-events\";\nimport { signalSubscribersNow } from './cache/signalSubscribers';\n\nif (typeof dispatchEvent !== 'undefined' && typeof addEventListener !== 'undefined') {\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, updatedParts => {\n if (!propagatingLocally) {\n let event: CustomEvent;\n if (isIEOrEdge) {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, true, true, updatedParts);\n } else {\n event = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, {\n detail: updatedParts\n });\n }\n propagatingLocally = true;\n dispatchEvent(event);\n propagatingLocally = false;\n }\n });\n addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, ({detail}: CustomEvent) => {\n if (!propagatingLocally) {\n propagateLocally(detail);\n }\n });\n}\n\n/** Called from listeners to BroadcastChannel and DOM event to\n * propagate the event locally into dexie's storagemutated event\n * and invalidate cached queries.\n * \n * This function is only called when the event is not originating\n * from this same Dexie module - either from another redundant dexie import\n * or from a foreign tab or worker. That's why we need to invalidate\n * the cache when this happens.\n */\nexport function propagateLocally(updateParts: ObservabilitySet) {\n let wasMe = propagatingLocally;\n try {\n propagatingLocally = true;\n // Fire the \"storagemutated\" event.\n globalEvents.storagemutated.fire(updateParts);\n // Invalidate cached queries and signal subscribers to requery.\n signalSubscribersNow(updateParts, true);\n } finally {\n propagatingLocally = wasMe;\n }\n}\n\nexport let propagatingLocally = false;\n","import {\n globalEvents,\n STORAGE_MUTATED_DOM_EVENT_NAME,\n DEXIE_STORAGE_MUTATED_EVENT_NAME,\n} from '../globals/global-events';\nimport { propagateLocally, propagatingLocally } from './propagate-locally';\n\nif (typeof BroadcastChannel !== 'undefined') {\n const bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME);\n\n /**\n * The Node.js BroadcastChannel will prevent the node process from exiting\n * if the BroadcastChannel is not closed.\n * Therefore we have to call unref() which allows the process to finish\n * properly even when the BroadcastChannel is never closed.\n * @link https://nodejs.org/api/worker_threads.html#broadcastchannelunref\n * @link https://github.com/dexie/Dexie.js/pull/1576\n */\n if (typeof (bc as any).unref === 'function') {\n (bc as any).unref();\n }\n \n //\n // Propagate local changes to remote tabs, windows and workers via BroadcastChannel\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n if (!propagatingLocally) {\n bc.postMessage(changedParts);\n }\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n bc.onmessage = (ev) => {\n if (ev.data) propagateLocally(ev.data);\n };\n} else if (typeof self !== 'undefined' && typeof navigator !== 'undefined') {\n // DOM verified - when typeof self !== \"undefined\", we are a window or worker. Not a Node process.\n\n //\n // Propagate local changes to remote tabs/windows via storage event and service worker\n // via messages. We have this code here because of https://bugs.webkit.org/show_bug.cgi?id=161472.\n //\n globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, (changedParts) => {\n try {\n if (!propagatingLocally) {\n if (typeof localStorage !== 'undefined') {\n // We're a browsing window or tab. Propagate to other windows/tabs via storage event:\n localStorage.setItem(\n STORAGE_MUTATED_DOM_EVENT_NAME,\n JSON.stringify({\n trig: Math.random(),\n changedParts,\n })\n );\n }\n if (typeof self['clients'] === 'object') {\n // We're a service worker. Propagate to our browser clients.\n [...self['clients'].matchAll({ includeUncontrolled: true })].forEach(\n (client) =>\n client.postMessage({\n type: STORAGE_MUTATED_DOM_EVENT_NAME,\n changedParts,\n })\n );\n }\n }\n } catch {}\n });\n\n //\n // Propagate remote changes locally via storage event:\n //\n if (typeof addEventListener !== 'undefined') {\n addEventListener('storage', (ev: StorageEvent) => {\n if (ev.key === STORAGE_MUTATED_DOM_EVENT_NAME) {\n const data = JSON.parse(ev.newValue);\n if (data) propagateLocally(data.changedParts);\n }\n });\n }\n\n //\n // Propagate messages from service worker\n //\n const swContainer = self.document && navigator.serviceWorker; // self.document is to verify we're not the SW ourself\n if (swContainer) {\n // We're a browser window and want to propagate message from the SW:\n swContainer.addEventListener('message', propagateMessageLocally);\n }\n}\n\nfunction propagateMessageLocally({ data }: MessageEvent) {\n if (data && data.type === STORAGE_MUTATED_DOM_EVENT_NAME) {\n propagateLocally(data.changedParts);\n }\n}\n","import { Dexie } from './classes/dexie';\nimport { DexieConstructor } from './public/types/dexie-constructor';\nimport { DexiePromise } from './helpers/promise';\nimport { mapError } from './errors';\nimport * as Debug from './helpers/debug';\nimport { dexieStackFrameFilter } from './globals/constants';\n\n// Generate all static properties such as Dexie.maxKey etc\n// (implement interface DexieConstructor):\nimport './classes/dexie/dexie-static-props';\nimport './live-query/enable-broadcast';\nimport { liveQuery } from './live-query/live-query';\nimport { Entity } from './classes/entity/Entity';\nimport { cmp } from './functions/cmp';\n\n// Set rejectionMapper of DexiePromise so that it generally tries to map\n// DOMErrors and DOMExceptions to a DexieError instance with same name but with\n// async stack support and with a prototypal inheritance from DexieError and Error.\n// of Map DOMErrors and DOMExceptions to corresponding Dexie errors.\nDexiePromise.rejectionMapper = mapError;\n\n// Let the async stack filter focus on app code and filter away frames from dexie.min.js:\nDebug.setDebug(Debug.debug, dexieStackFrameFilter);\n\nexport { RangeSet, mergeRanges, rangesOverlap } from \"./helpers/rangeset\";\nexport { Dexie, liveQuery }; // Comply with public/index.d.ts.\nexport { Entity };\nexport { cmp };\nexport default Dexie;\n"],"names":["asap","Promise","Dexie","Debug.debug","Debug.getErrorWithStack","safari14Workaround","_Dexie","Debug.setDebug"],"mappings":";;;;;;;;;;;;;AACO,MAAM,OAAO,GAChB,OAAO,UAAU,KAAK,WAAW,GAAG,UAAU;IAC9C,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI;QAClC,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM;YACtC,MAAM;;ACJH,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;AACzB,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;AACrC,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,OAAO,EAAC;IAInD,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC;CAC7B;SAGe,MAAM,CAAoC,GAAM,EAAE,SAAY;IAC1E,IAAI,OAAO,SAAS,KAAK,QAAQ;QAAE,OAAO,GAAY,CAAC;IACvD,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,GAAY,CAAC;AACxB,CAAC;AAEM,MAAM,QAAQ,GAAG,MAAM,CAAC,cAAc,CAAC;AACvC,MAAM,OAAO,GAAG,EAAE,CAAC,cAAc,CAAC;SACzB,MAAM,CAAC,GAAG,EAAE,IAAI;IAC5B,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AACnC,CAAC;SAEe,KAAK,CAAE,KAAK,EAAE,SAAS;IACnC,IAAI,OAAO,SAA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,EAAE,IAAI,EAAgB;IACrD,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,8BAA8B,EAAE;QACxD,gBAAgB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;KACrC;AACH;;AC9EA,YAAY,CAAC,eAAe,GAAG,QAAQ,CAAC;AAGxCO,QAAc,CAACJ,KAAW,EAAE,qBAAqB,CAAC;;;;"} \ No newline at end of file diff --git a/test/bundle.js b/test/bundle.js new file mode 100644 index 000000000..e52bed5e6 --- /dev/null +++ b/test/bundle.js @@ -0,0 +1,13390 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('dexie'), require('QUnit')) : + typeof define === 'function' && define.amd ? define(['dexie', 'QUnit'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Dexie, global.QUnit)); +})(this, (function (Dexie, QUnit) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var Dexie__default = /*#__PURE__*/_interopDefaultLegacy(Dexie); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics$1 = function(d, b) { + extendStatics$1 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics$1(d, b); + }; + + function __extends$1(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics$1(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + 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) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, 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 }; + } + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + } + + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + + function fillArrayBuffer(ab, val) { + var view = new Uint8Array(ab); + for (var i = 0; i < view.byteLength; ++i) { + view[i] = val; + } + } + QUnit.module('cmp'); + var cmp$1 = Dexie__default["default"].cmp; + QUnit.test('it should support indexable types', function () { + var e_1, _a; + // numbers + QUnit.ok(cmp$1(1, 1) === 0, 'Equal numbers should return 0'); + QUnit.ok(cmp$1(1, 2) === -1, 'Less than numbers should return -1'); + QUnit.ok(cmp$1(-1, -2000) === 1, 'Greater than numbers should return 1'); + // strings + QUnit.ok(cmp$1('A', 'A') === 0, 'Equal strings should return 0'); + QUnit.ok(cmp$1('A', 'B') === -1, 'Less than strings should return -1'); + QUnit.ok(cmp$1('C', 'A') === 1, 'Greater than strings should return 1'); + // Dates + QUnit.ok(cmp$1(new Date(1), new Date(1)) === 0, 'Equal dates should return 0'); + QUnit.ok(cmp$1(new Date(1), new Date(2)) === -1, 'Less than dates should return -1'); + QUnit.ok(cmp$1(new Date(1000), new Date(500)) === 1, 'Greater than dates should return 1'); + // Arrays + QUnit.ok(cmp$1([1, 2, '3'], [1, 2, '3']) === 0, 'Equal arrays should return 0'); + QUnit.ok(cmp$1([-1], [1]) === -1, 'Less than arrays should return -1'); + QUnit.ok(cmp$1([1], [-1]) === 1, 'Greater than arrays should return 1'); + QUnit.ok(cmp$1([1], [1, 0]) === -1, 'If second array is longer with same leading entries, return -1'); + QUnit.ok(cmp$1([1, 0], [1]) === 1, 'If first array is longer with same leading entries, return 1'); + QUnit.ok(cmp$1([1], [0, 0]) === 1, 'If first array is shorter but has greater leading entries, return 1'); + QUnit.ok(cmp$1([0, 0], [1]) === -1, 'If second array is shorter but has greater leading entries, return -1'); + /* Binary types + | DataView + | Uint8ClampedArray + | Uint8Array + | Int8Array + | Uint16Array + | Int16Array + | Uint32Array + | Int32Array + | Float32Array + | Float64Array; + */ + var viewTypes = [ + 'DataView', + 'Uint8ClampedArray', + 'Uint8Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Int32Array', + 'Float32Array', + 'Float64Array', + ] + .map(function (typeName) { return [typeName, self[typeName]]; }) + .filter(function (_a) { + var _b = __read(_a, 2); _b[0]; var ctor = _b[1]; + return !!ctor; + }); // Don't try to test types not supported by the browser + var zeroes1 = new ArrayBuffer(16); + var zeroes2 = new ArrayBuffer(16); + var ones = new ArrayBuffer(16); + fillArrayBuffer(zeroes1, 0); + fillArrayBuffer(zeroes2, 0); + fillArrayBuffer(ones, 1); + try { + for (var viewTypes_1 = __values(viewTypes), viewTypes_1_1 = viewTypes_1.next(); !viewTypes_1_1.done; viewTypes_1_1 = viewTypes_1.next()) { + var _b = __read(viewTypes_1_1.value, 2), typeName = _b[0], ArrayBufferView = _b[1]; + // Equals + var v1 = new ArrayBufferView(zeroes1); + var v2 = new ArrayBufferView(zeroes2); + QUnit.ok(cmp$1(v1, v2) === 0, "Equal ".concat(typeName, "s should return 0")); + // Less than + v1 = new ArrayBufferView(zeroes1); + v2 = new ArrayBufferView(ones); + QUnit.ok(cmp$1(v1, v2) === -1, "Less than ".concat(typeName, "s should return -1")); + // Less than + v1 = new ArrayBufferView(ones); + v2 = new ArrayBufferView(zeroes1); + QUnit.ok(cmp$1(v1, v2) === 1, "Greater than ".concat(typeName, "s should return 1")); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (viewTypes_1_1 && !viewTypes_1_1.done && (_a = viewTypes_1.return)) _a.call(viewTypes_1); + } + finally { if (e_1) throw e_1.error; } + } + }); + QUnit.test("it should respect IndexedDB's type order", function () { + var zoo = [ + 'meow', + 1, + new Date(), + Infinity, + -Infinity, + new ArrayBuffer(1), + [[]], + ]; + var _a = __read(zoo.sort(cmp$1), 7), minusInfinity = _a[0], num = _a[1], infinity = _a[2], date = _a[3], string = _a[4], binary = _a[5], array = _a[6]; + QUnit.equal(minusInfinity, -Infinity, 'Minus infinity is sorted first'); + QUnit.equal(num, 1, 'Numbers are sorted second'); + QUnit.equal(infinity, Infinity, 'Infinity is sorted third'); + QUnit.ok(date instanceof Date, 'Date is sorted fourth'); + QUnit.ok(typeof string === 'string', 'strings are sorted fifth'); + QUnit.ok(binary instanceof ArrayBuffer, 'binaries are sorted sixth'); + QUnit.ok(Array.isArray(array), 'Arrays are sorted seventh'); + }); + QUnit.test('it should return NaN on invalid types', function () { + QUnit.ok(isNaN(cmp$1(1, { foo: 'bar' })), 'Comparing a number against an object returns NaN (would throw in indexedDB)'); + QUnit.ok(isNaN(cmp$1({ foo: 'bar' }, 1)), 'Comparing an object against a number returns NaN also'); + }); + QUnit.test('it should treat different binary types as if they were equal', function () { + var e_2, _a; + var viewTypes = [ + 'DataView', + 'Uint8ClampedArray', + 'Uint8Array', + 'Int8Array', + 'Uint16Array', + 'Uint32Array', + 'Int32Array', + 'Float32Array', + 'Float64Array', + ] + .map(function (typeName) { return [typeName, self[typeName]]; }) + .filter(function (_a) { + var _b = __read(_a, 2); _b[0]; var ctor = _b[1]; + return !!ctor; + }); // Don't try to test types not supported by the browser + var zeroes1 = new ArrayBuffer(16); + var zeroes2 = new ArrayBuffer(16); + fillArrayBuffer(zeroes1, 0); + fillArrayBuffer(zeroes2, 0); + try { + for (var viewTypes_2 = __values(viewTypes), viewTypes_2_1 = viewTypes_2.next(); !viewTypes_2_1.done; viewTypes_2_1 = viewTypes_2.next()) { + var _b = __read(viewTypes_2_1.value, 2), typeName = _b[0], ArrayBufferView = _b[1]; + var v1 = new ArrayBufferView(zeroes1); + QUnit.ok(cmp$1(v1, zeroes1) === 0, "Comparing ".concat(typeName, " with ArrayBuffer should return 0 if they have identical data")); + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (viewTypes_2_1 && !viewTypes_2_1.done && (_a = viewTypes_2.return)) _a.call(viewTypes_2); + } + finally { if (e_2) throw e_2.error; } + } + }); + QUnit.test('it should return NaN if comparing arrays where any item or sub array item includes an invalid key', function () { + QUnit.ok(cmp$1([1, [[2, "3"]]], [1, [[2, "3"]]]) === 0, "It can deep compare arrays with valid keys (equals)"); + QUnit.ok(cmp$1([1, [[2, "3"]]], [1, [[2, 3]]]) === 1, "It can deep compare arrays with valid keys (greater than)"); + QUnit.ok(isNaN(cmp$1([1, [[2, 3]]], [1, [[{ foo: "bar" }, 3]]])), "It returns NaN when any item in the any of the arrays are invalid keys"); + }); + + // 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__default["default"].debug = window.location.search.indexOf('longstacks') !== -1 ? 'dexie' : false; + if (window.location.search.indexOf('longstacks=tests') !== -1) + Dexie__default["default"].debug = true; // Don't include stuff from dexie.js. + var no_optimize = window.no_optimize || window.location.search.indexOf('dontoptimize') !== -1; + var ArrayBuffer$1 = window.ArrayBuffer; + function stringify(idbKey) { + var res = '' + (idbKey && idbKey.constructor && idbKey.constructor === ArrayBuffer$1 ? + new Uint8Array(idbKey) : idbKey); + return res; + } + function resetDatabase(db) { + /// + var Promise = Dexie__default["default"].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__default["default"].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__default["default"].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 isChrome = !!window.chrome; + var hasPolyfillIE = [].slice.call(document.getElementsByTagName("script")).some(function (s) { return s.src.indexOf("idb-iegap") !== -1; }); + var isSafari = typeof navigator !== 'undefined' && + /Safari\//.test(navigator.userAgent) && + !/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent); + function supports(features) { + return features.split('+').reduce(function (result, feature) { + switch (feature.toLowerCase()) { + case "compound": + return result && Array.isArray(Dexie__default["default"].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__default["default"].maxKey) && indexedDB.cmp(new Uint8Array([1]), new Uint8Array([1])) === 0; + } + catch (e) { + return false; + } + case "domevents": + return typeof window === 'object' && window.addEventListener; + 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__default["default"].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__default["default"].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$b = new Dexie__default["default"]("TestDBTable"); + db$b.version(1).stores({ + users: "++id,first,last,&username,*&email,*pets", + folks: "++,first,last", + items: "id", + schema: "" // Test issue #1039 + }); + db$b.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String], + }); + var idOfFirstUser = 0, idOfLastUser = 0; + db$b.on("populate", function (trans) { + db$b.users.add({ first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }).then(function (id) { + idOfFirstUser = id; + }); + db$b.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$b).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + promisedTest("Issue #841 - put() ignores date changes", function () { return __awaiter(void 0, void 0, void 0, function () { + var updateAssertions, date1, date2, first1, first2, id, obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + updateAssertions = function (mods) { + QUnit.equal(mods.first, first2, "first value should be ".concat(first2, " but is ").concat(mods.first)); + QUnit.equal(!!mods.date, true, "date should be included in modifications"); + if (mods.date) { + QUnit.equal(mods.date.getTime(), date2.getTime(), "date should be ".concat(date2, " but is ").concat(mods.date)); + } + }; + db$b.folks.hook("updating", updateAssertions); + date1 = new Date("2019-05-03"); + date2 = new Date("2020-01-01"); + first1 = "Foo1"; + first2 = "Foo2"; + QUnit.ok(date1.getTime() !== date2.getTime(), "Just verifying input data so that date1 !== date2"); + QUnit.ok(first1 != first2, "first1 different first2"); + return [4 /*yield*/, db$b.folks.add({ first: first1, last: "Bar", date: date1 })]; + case 1: + id = _a.sent(); + return [4 /*yield*/, db$b.folks.get(id)]; + case 2: + obj = _a.sent(); + QUnit.equal(obj.date.getTime(), date1.getTime(), "Date should first equal date1"); + QUnit.equal(obj.first, first1, "first should be '".concat(first1, "'")); + obj.first = first2; + obj.date = date2; + return [4 /*yield*/, db$b.folks.put(obj, id)]; + case 3: + _a.sent(); + return [4 /*yield*/, db$b.folks.get(id)]; + case 4: + obj = _a.sent(); + QUnit.equal(obj.first, first2, "first should have been successfully updated to '".concat(first2, "'")); + QUnit.equal(obj.date.getTime(), date2.getTime(), "Date should have been successfully updated to be date2"); + db$b.folks.hook("updating").unsubscribe(updateAssertions); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #966 - put() with dotted field in update hook", function () { return __awaiter(void 0, void 0, void 0, function () { + var updateAssertions, id, obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + updateAssertions = function (mods) { + QUnit.equal(mods["nested.field"], "value", "mods.nested.field should contain 'value'"); + QUnit.equal(mods.nested, undefined, "mods.nested field should be empty"); + return __assign({}, mods); + }; + db$b.folks.hook("updating", updateAssertions); + return [4 /*yield*/, db$b.folks.add({ first: "first", last: "last" })]; + case 1: + id = _a.sent(); + return [4 /*yield*/, db$b.folks.put({ first: "first", last: "last", "nested.field": "value" }, id)]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.folks.get(id)]; + case 3: + obj = _a.sent(); + QUnit.equal(obj["nested.field"], "value", "obj.nested.field should have been successfully updated to 'value'"); + QUnit.equal(obj.nested, undefined, "obj.nested field should have remained undefined"); + db$b.folks.hook("updating").unsubscribe(updateAssertions); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("update array property", function () { return __awaiter(void 0, void 0, void 0, function () { + var obj; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.items.put({ id: 1, foo: [{ bar: 123 }] })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$b.items.update(1, { foo: [{ bar: 222 }] })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.items.get(1)]; + case 3: + obj = _a.sent(); + QUnit.equal(JSON.stringify(obj.foo), JSON.stringify([{ bar: 222 }]), "foo har been updated to the new array"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Verify #1130 doesn't break contract of hook('updating')", function () { return __awaiter(void 0, void 0, void 0, function () { + var updateHook, id, foo; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + updateHook = function (mods) { + return { "address.postalCode": 111 }; + }; + _a.label = 1; + case 1: + _a.trys.push([1, , 5, 6]); + return [4 /*yield*/, db$b.folks.add({ + first: "Foo", + last: "Bar", + address: { + city: "Stockholm", + street: "Folkungagatan" + } + })]; + case 2: + id = _a.sent(); + db$b.folks.hook("updating", updateHook); + return [4 /*yield*/, db$b.folks.update(id, { + "address.streetNo": 23 + })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$b.folks.get(id)]; + case 4: + foo = _a.sent(); + QUnit.equal(foo.address.city, "Stockholm", "Correct city Stockholm"); + QUnit.equal(foo.address.street, "Folkungagatan", "Correct street Folkungagatan"); + QUnit.equal(foo.address.streetNo, 23, "Correct streetNo: 23"); + QUnit.equal(foo.address.postalCode, 111, "Hooks should have added postal code"); + return [3 /*break*/, 6]; + case 5: + db$b.folks.hook("updating").unsubscribe(updateHook); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("get", 4, function () { + db$b.table("users").get(idOfFirstUser).then(function (obj) { + QUnit.equal(obj.first, "David", "Got the first object"); + return db$b.users.get(idOfLastUser); + }).then(function (obj) { + QUnit.equal(obj.first, "Karl", "Got the second object"); + return db$b.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$b.transaction("r", db$b.users, function () { + db$b.users.where("username").equals("kceder").first(function (user) { + QUnit.equal(user.first, "Karl", "where().equals()"); + }), + db$b.users.where("id").above(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 1, "where().above()"); + }), + db$b.users.where("id").aboveOrEqual(idOfFirstUser).toArray(function (a) { + QUnit.ok(a.length == 2, "where().aboveOrEqual()"); + }), + db$b.users.where("id").below(idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().below().count()"); + }), + db$b.users.where("id").below(idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().below().count() should be zero"); + }), + db$b.users.where("id").belowOrEqual(idOfFirstUser).count(function (count) { + QUnit.ok(count == 1, "where().belowOrEqual()"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfFirstUser).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 1)"); + }), + db$b.users.where("id").between(0, Infinity).count(function (count) { + QUnit.ok(count == 2, "where().between(0, Infinity)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfFirstUser, true, true).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 1, true, true)"); + }), + db$b.users.where("id").between(1, -1, true, true).count(function (count) { + QUnit.ok(count == 0, "where().between(1, -1, true, true)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfLastUser).count(function (count) { + QUnit.ok(count == 1, "where().between(1, 2)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfLastUser, true, true).count(function (count) { + QUnit.ok(count == 2, "where().between(1, 2, true, true)"); + }), + db$b.users.where("id").between(idOfFirstUser, idOfLastUser, false, false).count(function (count) { + QUnit.ok(count == 0, "where().between(1, 2, false, false)"); + }); + db$b.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$b.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$b.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$b.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$b.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$b.users.where("last").anyOf("Faadersköld").toArray(function (a) { + QUnit.equal(a.length, 1, "in() returned expected number of items"); + }); + if (supports("multiEntry")) { + db$b.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$b.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$b.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$b.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$b.transaction("rw", db$b.users, function () { + // Modify first found user with a helloMessage + db$b.users.orderBy("first").reverse().limit(1).modify(function (user) { + user.helloMessage = "Hello " + user.first; + }); + // Check that the modification went fine: + db$b.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$b.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$b.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$b.transaction("rw", db$b.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db$b.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$b.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$b.users.put(user).then(function (id) { + QUnit.equal(id, currentId, "Still got same id because we update same object"); + }); + db$b.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$b.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$b.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$b.users.put(user).then(function (id) { + QUnit.equal(id, userId, "Still got same id because we update same object"); + return db$b.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); + }); + promisedTest("bulkUpdate", function () { return __awaiter(void 0, void 0, void 0, function () { + var allItems, expected; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.items.bulkAdd([ + { id: 1, foo: { bar: 1 } }, + { id: 2, foo: { bar: 2 } }, + { id: 3, foo: { bar: 3 } } + ])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$b.items.bulkUpdate([ + { key: 1, changes: { "foo.bar": 101 } }, + { key: 2, changes: { "foo.bar": 102, "foo.baz": "x" } }, + { key: 4, changes: { "foo.bar": 104 } }, + ])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.items.toArray()]; + case 3: + allItems = _a.sent(); + expected = [ + { id: 1, foo: { bar: 101 } }, + { id: 2, foo: { bar: 102, baz: "x" } }, + { id: 3, foo: { bar: 3 } } + ]; + deepEqual$1(allItems, expected, "2 items updated as expected. nonexisting item not updated."); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("bulkUpdate without actual changes (check it doesn't bail out)", function () { return __awaiter(void 0, void 0, void 0, function () { + var dbCoreMutateCalls, allItems, expected; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbCoreMutateCalls = []; + db$b.use({ + stack: 'dbcore', + name: 'temp-logger', + create: function (downDb) { return (__assign(__assign({}, downDb), { table: function (tableName) { + var downTable = downDb.table(tableName); + return __assign(__assign({}, downTable), { mutate: function (req) { + if (tableName === 'items') { + dbCoreMutateCalls.push(req); + } + return downTable.mutate(req); + } }); + } })); } + }); + db$b.close(); + return [4 /*yield*/, db$b.open()]; + case 1: + _a.sent(); // Apply the middleware + _a.label = 2; + case 2: + _a.trys.push([2, , 5, 7]); + // Clear the log (in case another middleware or addon did something in db ready in integration tests) + dbCoreMutateCalls.splice(0, dbCoreMutateCalls.length); + QUnit.equal(dbCoreMutateCalls.length, 0, 'No mutate calls yet'); + return [4 /*yield*/, db$b.items.bulkUpdate([ + { key: 'nonexist1', changes: { 'foo.bar': 101 } }, + { key: 'nonexist2', changes: { 'foo.bar': 102 } }, + { key: 'nonexist3', changes: { 'foo.bar': 103 } } + ])]; + case 3: + _a.sent(); + QUnit.equal(dbCoreMutateCalls.length, 1, 'One mutate call has taken place'); + deepEqualPartial(dbCoreMutateCalls, [ + { + type: 'put', + values: [], + criteria: undefined, + changeSpec: undefined, + updates: { + keys: ['nonexist1', 'nonexist2', 'nonexist3'], + changeSpecs: [ + { 'foo.bar': 101 }, + { 'foo.bar': 102 }, + { 'foo.bar': 103 } + ], + }, + }, + ], 'The mutate call was a put call and contained the intended updates for consistent sync addons to consume'); + return [4 /*yield*/, db$b.items.toArray()]; + case 4: + allItems = _a.sent(); + expected = []; + deepEqual$1(allItems, expected, 'Nonexisting item not updated.'); + return [3 /*break*/, 7]; + case 5: + // Cleanup temporary middleware: + db$b.unuse({ stack: 'dbcore', name: 'temp-logger' }); + db$b.close(); + return [4 /*yield*/, db$b.open()]; + case 6: + _a.sent(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); }); + promisedTest("bulkUpdate with failure", function () { return __awaiter(void 0, void 0, void 0, function () { + var users, error_1, failurePositions, failurePosition, failure, allItems, expected; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isSafari) { + // Avoid bug https://bugs.webkit.org/show_bug.cgi?id=247053 + QUnit.ok(true, "Avoiding Safari issue https://bugs.webkit.org/show_bug.cgi?id=247053"); + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, 4, , 5]); + return [4 /*yield*/, db$b.users.toArray()]; + case 2: + users = _a.sent(); + deepEqualPartial(users, [ + { first: "David", username: "dfahlander" }, + { first: "Karl", username: "kceder" } + ], "We have the expected users to begin with"); + return [4 /*yield*/, db$b.users.bulkUpdate([ + { key: "nonexisting", changes: { username: "xyz" } }, + { key: idOfFirstUser, changes: { username: "kceder" } }, + { key: idOfFirstUser + 1, changes: { first: "Baz" } } // Shall succeed + ])]; + case 3: + _a.sent(); + throw new Error("Should not have succeeded"); + case 4: + error_1 = _a.sent(); + QUnit.equal(error_1.failures.length, 1, "Should be 1 failure"); + failurePositions = Object.keys(error_1.failuresByPos); + QUnit.equal(failurePositions.length, 1, "failuresByPos should have one key only (array with holes)"); + failurePosition = failurePositions[0]; + QUnit.equal(failurePosition, 1, "The failure should have occurred at position 1"); + failure = error_1.failuresByPos[failurePosition]; + QUnit.ok(failure != null, "There was a failure"); + return [3 /*break*/, 5]; + case 5: return [4 /*yield*/, db$b.users.toArray()]; + case 6: + allItems = _a.sent(); + expected = [ + { first: "David", username: "dfahlander" }, + { first: "Baz", username: "kceder" } + ]; + deepEqualPartial(allItems, expected, "The end result in a non-transactional bulkUpdate() should be that non-failing entries succeeded to update"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("bulkUpdate with failure (transactional)", function () { return __awaiter(void 0, void 0, void 0, function () { + var error_2, failurePositions, failurePosition, failure, allItems, expected; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db$b.transaction('rw', db$b.users, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.bulkUpdate([ + { key: "nonexisting", changes: { username: "xyz" } }, + { key: idOfFirstUser, changes: { username: "kceder" } }, + { key: idOfFirstUser + 1, changes: { "foo.bar": 102 } } // Shall succeed + ])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + throw new Error("Should not have succeeded"); + case 2: + error_2 = _a.sent(); + QUnit.equal(error_2.failures.length, 1, "Should be 1 failure"); + failurePositions = Object.keys(error_2.failuresByPos); + QUnit.equal(failurePositions.length, 1, "failuresByPos should have one key only (array with holes)"); + failurePosition = failurePositions[0]; + QUnit.equal(failurePosition, 1, "The failure should have occurred at position 1"); + failure = error_2.failuresByPos[failurePosition]; + QUnit.ok(failure != null && failure instanceof Error, "There was a failure and it was an error"); + return [3 /*break*/, 3]; + case 3: return [4 /*yield*/, db$b.users.toArray()]; + case 4: + allItems = _a.sent(); + expected = [ + { first: "David", username: "dfahlander" }, + { first: "Karl", username: "kceder" } + ]; + deepEqualPartial(allItems, expected, "The end result in a transactional bulkUpdate() should be that no entries succeeeded to update if not catching error within transaction"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("bulkUpdate with failure (transactional with catch)", function () { return __awaiter(void 0, void 0, void 0, function () { + var allItems, expected; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isSafari) { + // Avoid bug https://bugs.webkit.org/show_bug.cgi?id=247053 + QUnit.ok(true, "Avoiding Safari issue https://bugs.webkit.org/show_bug.cgi?id=247053"); + return [2 /*return*/]; + } + return [4 /*yield*/, db$b.transaction('rw', db$b.users, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, , 3]); + return [4 /*yield*/, db$b.users.bulkUpdate([ + { key: "nonexisting", changes: { username: "xyz" } }, + { key: idOfFirstUser, changes: { username: "kceder" } }, + { key: idOfFirstUser + 1, changes: { "foo.bar": 102 } } // Shall succeed + ])]; + case 1: + _b.sent(); + return [3 /*break*/, 3]; + case 2: + _b.sent(); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$b.users.toArray()]; + case 2: + allItems = _a.sent(); + expected = [ + { first: "David", last: "Fahlander", username: "dfahlander" }, + { first: "Karl", last: "Faadersköld", username: "kceder", foo: { bar: 102 } } + ]; + deepEqualPartial(allItems, expected, "The end result in a transactional bulkUpdate() (with catch inside transaction) should be that non-failing entries succeeded to update"); + return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("add", function () { + db$b.transaction("rw", db$b.users, function () { + var newUser = { first: "Åke", last: "Persbrant", username: "aper", email: ["aper@persbrant.net"] }; + db$b.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$b.users.where("username").equals("aper").first(function (user) { + QUnit.equal(user.last, "Persbrant", "The correct item was actually added"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + spawnedTest("bulkAdd", function () { + var highestKey, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.add({ username: "fsdkljfd", email: ["fjkljslk"] })]; + case 1: + highestKey = _a.sent(); + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + return [4 /*yield*/, db$b.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db$b.users.bulkAdd([ + { first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, + { first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] } + ])]; + case 3: + result = _a.sent(); + QUnit.equal(result, highestKey + 2, "Result of bulkAdd() operation was equal to highestKey + 2"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-all-results", function () { + var dbBulkAddAll, highestKey, allKeys, expectedKeys, allKeys2, expectedKeys2, allKeys3, lastKey, lastKey, lastKey; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbBulkAddAll = new Dexie__default["default"]("TestDBTableBulkAddAllResults"); + dbBulkAddAll.version(1).stores({ + dudes: "++,first,last" + }); + return [4 /*yield*/, dbBulkAddAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 1: + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1", find: "bulkAddAll" }, + { first: "Åke2", last: "Persbrant2", find: "bulkAddAll" } + ], { allKeys: true })]; + case 2: + allKeys = _a.sent(); + expectedKeys = [highestKey + 1, highestKey + 2]; + deepEqual$1(allKeys, expectedKeys, "Result of bulkAdd(objects, { allKeys: true }) operation was equal to [highestKey + 1, highestKey + 2]"); + return [4 /*yield*/, dbBulkAddAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 3: + // should be able to get all keys with options object as third argument + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1", find: "bulkAddAll" }, + { first: "Åke2", last: "Persbrant2", find: "bulkAddAll" } + ], undefined, { allKeys: true })]; + case 4: + allKeys2 = _a.sent(); + expectedKeys2 = [highestKey + 1, highestKey + 2]; + deepEqual$1(allKeys2, expectedKeys2, "Result of bulkAdd(objects, undefined, { allKeys: true }) operation was equal to [highestKey + 1, highestKey + 2]"); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['sd5fs2df', 'dasfsd3fs7df'], { allKeys: true })]; + case 5: + allKeys3 = _a.sent(); + deepEqual$1(allKeys3, ['sd5fs2df', 'dasfsd3fs7df'], "Result of bulkAdd(objects, ['sd5fs2df', 'dasfsd3fs7df'], { allKeys: true }) operation was equal to ['sd5fs2df', 'dasfsd3fs7df']"); + return [4 /*yield*/, dbBulkAddAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 6: + // should return last key with 1 argument and options: { allKeys: false } + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], { allKeys: false })]; + case 7: + lastKey = _a.sent(); + QUnit.equal(lastKey, highestKey + 2, "Result of bulkAdd(objects, { allKeys: false }) operation was equal to highestKey + 2"); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false })]; + case 8: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'b33vn3fytn', "Result of bulkAdd(objects, ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false }) operation was equal to 'b33vn3fytn'"); + return [4 /*yield*/, dbBulkAddAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['dfgd2vdfh4d', 'ty1jxdbd9'])]; + case 9: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'ty1jxdbd9', "Result of bulkAdd(objects, ['dfgd2vdfh4d', 'ty1jxdbd9']) operation was equal to 'ty1jxdbd9'"); + return [4 /*yield*/, dbBulkAddAll.delete()]; + case 10: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-catching errors", function () { + var _a, newUsersX, e_1, _b, _c, newUsersY, e_2, _d, newUsersZ, _e; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: return [4 /*yield*/, db$b.transaction("rw", db$b.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$b.users.bulkAdd(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie__default["default"].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$b.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-added"); + }); + })]; + case 1: + _f.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.users.where("username").startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_f.sent(), 3, "Previous transaction committed"]); + newUsersX = [ + { first: "Xke1", last: "Persbrant1", username: "xper1", email: ["xper1@persbrant.net"] }, + { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, + { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, + { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] } + ]; + _f.label = 3; + case 3: + _f.trys.push([3, 5, , 6]); + return [4 /*yield*/, db$b.transaction("rw", db$b.users, function () { + db$b.users.bulkAdd(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + })]; + case 4: + _f.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 6]; + case 5: + e_1 = _f.sent(); + QUnit.ok(true, "Got: " + e_1); + return [3 /*break*/, 6]; + case 6: + _b = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('xper').count()]; + case 7: + _b.apply(void 0, [_f.sent(), 0, "0 users! Good, means that previous transaction did not commit"]); + return [4 /*yield*/, db$b.users.bulkAdd(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + })]; + case 8: + _f.sent(); + _c = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('xper').count()]; + case 9: + _c.apply(void 0, [_f.sent(), 3, "3 users! Good - means that previous operation catched and therefore committed"]); + newUsersY = [ + { first: "Yke1", last: "Persbrant1", username: "yper1", email: ["yper1@persbrant.net"] }, + { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, + { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, + { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] } + ]; + _f.label = 10; + case 10: + _f.trys.push([10, 12, , 13]); + return [4 /*yield*/, db$b.users.bulkAdd(newUsersY)]; + case 11: + _f.sent(); + return [3 /*break*/, 13]; + case 12: + e_2 = _f.sent(); + QUnit.ok(true, "Got: " + e_2); + return [3 /*break*/, 13]; + case 13: + _d = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('yper').count()]; + case 14: + _d.apply(void 0, [_f.sent(), 3, "3 users! Good - means that previous operation catched (via try..yield..catch this time, and therefore committed"]); + newUsersZ = [ + { first: "Zke1", last: "Persbrant1", username: "zper1", email: ["zper1@persbrant.net"] }, + { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, + { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, + { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] } + ]; + return [4 /*yield*/, db$b.transaction('rw', db$b.users, function () { + var e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db$b.users.bulkAdd(newUsersZ)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_3 = _a.sent(); + throw e_3; + case 3: return [2 /*return*/]; + } + }); + }).catch(Dexie__default["default"].BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('zper').count()]; + case 16: + _e.apply(void 0, [_f.sent(), 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-non-inbound-autoincrement", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, db$b.folks.bulkAdd([ + { first: "Foo", last: "Bar" }, + { first: "Foo", last: "Bar2" }, + { first: "Foo", last: "Bar3" }, + { first: "Foo", last: "Bar4" } + ])]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.folks.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_c.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db$b.folks.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_c.sent(), 1, "Shoudl be 1 Bar"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkAdd-catch sub transaction", function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, db$b.transaction('rw', db$b.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$b.transaction('rw', db$b.users, function () { + db$b.users.bulkAdd(newUsers); + }).then(function () { + QUnit.ok(false, "Should not succeed with all these operations"); + }).catch(function (e) { + QUnit.equal(e.failures.length, 1, "Should get one failure"); + }); + }).catch(function (e) { + QUnit.ok(true, "Outer transaction aborted due to inner transaction abort. This is ok: " + e); + })]; + case 1: + _b.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_b.sent(), 0, "0 users! Good, means that inner transaction did not commit"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("Issue #1280 - add() with auto-incrementing ID and CryptoKey", function () { + var generatedKey, db, objToAdd, id, storedObj; + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!((_a = self === null || self === void 0 ? void 0 : self.crypto) === null || _a === void 0 ? void 0 : _a.subtle)) { + QUnit.ok(true, "This browser doesnt have WebCrypto"); + return [2 /*return*/]; + } + return [4 /*yield*/, self.crypto.subtle.generateKey({ + name: "RSA-OAEP", + modulusLength: 1024, + publicExponent: new Uint8Array([1, 0, 1]), + hash: "SHA-256", + }, true, ["encrypt", "decrypt"])]; + case 1: + generatedKey = _b.sent(); + return [4 /*yield*/, Dexie__default["default"].delete("MyDatabaseToStoreCryptoKeys")]; + case 2: + _b.sent(); + db = new Dexie__default["default"]("MyDatabaseToStoreCryptoKeys"); + db.version(1).stores({ + keys: "++id", + }); + objToAdd = { key: generatedKey.privateKey }; + QUnit.ok(generatedKey.privateKey instanceof CryptoKey, "The CryptoKey object was generated correctly"); + return [4 /*yield*/, db.keys.add(objToAdd)]; + case 3: + id = _b.sent(); + QUnit.ok(id != null, "The id we got was not nullish"); + return [4 /*yield*/, db.keys.get(id)]; + case 4: + storedObj = _b.sent(); + QUnit.ok(storedObj.key instanceof CryptoKey, "The CryptoKey object exists in storage"); + // Verify that update works + return [4 /*yield*/, db.keys.update(id, { someOtherProp: 'x' })]; + case 5: + // Verify that update works + _b.sent(); + return [4 /*yield*/, db.keys.get(id)]; + case 6: + storedObj = _b.sent(); + QUnit.ok(storedObj.key instanceof CryptoKey, "The CryptoKey object is still a CryptoKey"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut", function () { + var highestKey, existingFirstUserToReplace, result, ourAddedUsers, replacedDfahlander; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.add({ username: "fsdkljfd", email: ["fjkljslk"] })]; + case 1: + highestKey = _a.sent(); + QUnit.ok(true, "Highest key was: " + highestKey); + // Delete test item. + return [4 /*yield*/, db$b.users.delete(highestKey)]; + case 2: + // Delete test item. + _a.sent(); + QUnit.ok(true, "Deleted test item"); + return [4 /*yield*/, db$b.users.get(idOfFirstUser)]; + case 3: + existingFirstUserToReplace = _a.sent(); + QUnit.equal(existingFirstUserToReplace.username, "dfahlander", "Existing user should be dfahlander"); + return [4 /*yield*/, db$b.users.bulkPut([ + { first: "Åke1", last: "Persbrant1", username: "aper1", email: ["aper1@persbrant.net"] }, + { id: idOfFirstUser, first: "Åke2", last: "Persbrant2", username: "aper2", email: ["aper2@persbrant.net"] }, + { first: "Åke3", last: "Persbrant3", username: "aper3", email: ["aper3@persbrant.net"] } + ])]; + case 4: + result = _a.sent(); + QUnit.equal(result, highestKey + 2, "Result of bulkPut() operation was equal to highestKey + 2"); + return [4 /*yield*/, db$b.users.where('username').startsWith("aper").toArray()]; + case 5: + ourAddedUsers = _a.sent(); + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, db$b.users.get(idOfFirstUser)]; + case 6: + replacedDfahlander = _a.sent(); + QUnit.equal(replacedDfahlander.username, "aper2", "dfahlander Should now be aper2 instead"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-all-results", function () { + var dbBulkPutAll, highestKey, allKeys, ourAddedUsers, replacedRecord, allKeys2, ourAddedUsers2, replacedRecord2, allKeys3, ourAddedUsers3, replacedRecord3, lastKey, lastKey, lastKey; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbBulkPutAll = new Dexie__default["default"]("TestDBTableBulkPutAllResults"); + dbBulkPutAll.version(1).stores({ + users: "++id,first,last,find", + mates: "++id,first,last,find", + dudes: "++,first,last,find", + }); + return [4 /*yield*/, dbBulkPutAll.users.add({ first: "fsdkljfd", last: "fjkljslk", find: "bulkPutAll" })]; + case 1: + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.users.bulkPut([ + { first: "Åke1", last: "Persbrant1", find: "bulkPutAll" }, + { id: highestKey, first: "Åke2", last: "Persbrant2", find: "bulkPutAll" }, + { first: "Åke3", last: "Persbrant3", find: "bulkPutAll" } + ], { allKeys: true })]; + case 2: + allKeys = _a.sent(); + deepEqual$1(allKeys, [highestKey + 1, highestKey, highestKey + 2], "Result of bulkAdd(objects, { allKeys: true }) operation was equal to [highestKey + 1, highestKey, highestKey + 2]"); + return [4 /*yield*/, dbBulkPutAll.users.where('find').startsWith("bulkPutAll").toArray()]; + case 3: + ourAddedUsers = _a.sent(); + QUnit.equal(ourAddedUsers.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, dbBulkPutAll.users.get(highestKey)]; + case 4: + replacedRecord = _a.sent(); + QUnit.equal(replacedRecord.last, "Persbrant2", "fjkljslk should now be Persbrant2 instead"); + return [4 /*yield*/, dbBulkPutAll.mates.add({ first: "fsdkljfd", last: "fjkljslk", find: "bulkPutAll" })]; + case 5: + // should be able to get all keys with options object as third argument (mates) + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.mates.bulkPut([ + { first: "Åke1", last: "Persbrant1", find: "bulkPutAll" }, + { id: highestKey, first: "Åke2", last: "Persbrant2", find: "bulkPutAll" }, + { first: "Åke3", last: "Persbrant3", find: "bulkPutAll" } + ], undefined, { allKeys: true })]; + case 6: + allKeys2 = _a.sent(); + deepEqual$1(allKeys2, [highestKey + 1, highestKey, highestKey + 2], "Result of bulkPut(objects, undefined, { allKeys: true }) operation was equal to [highestKey + 1, highestKey, highestKey + 2]"); + return [4 /*yield*/, dbBulkPutAll.mates.where('find').startsWith("bulkPutAll").toArray()]; + case 7: + ourAddedUsers2 = _a.sent(); + QUnit.equal(ourAddedUsers2.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, dbBulkPutAll.mates.get(highestKey)]; + case 8: + replacedRecord2 = _a.sent(); + QUnit.equal(replacedRecord2.last, "Persbrant2", "fjkljslk should now be Persbrant2 instead"); + return [4 /*yield*/, dbBulkPutAll.dudes.add({ first: "fsdkljfd", last: "fjkljslk", find: "bulkPutAll" })]; + case 9: + // should be able to get all keys with options object as third argument with keys array (dudes) + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkPut([ + { first: "Åke1", last: "Persbrant1", find: "bulkPutAll" }, + { id: highestKey, first: "Åke2", last: "Persbrant2", find: "bulkPutAll" }, + { first: "Åke3", last: "Persbrant3", find: "bulkPutAll" } + ], ['sd5fs2df', highestKey, 'dasfsd3fs7df'], { allKeys: true })]; + case 10: + allKeys3 = _a.sent(); + deepEqual$1(allKeys3, ['sd5fs2df', highestKey, 'dasfsd3fs7df'], "Result of bulkPut(objects, ['sd5fs2df', highestKey, 'dasfsd3fs7df'], { allKeys: true }) operation was equal to ['sd5fs2df', highestKey, 'dasfsd3fs7df']"); + return [4 /*yield*/, dbBulkPutAll.dudes.where('find').startsWith("bulkPutAll").toArray()]; + case 11: + ourAddedUsers3 = _a.sent(); + QUnit.equal(ourAddedUsers3.length, 3, "Should have put 3 users there (two additions and one replaced"); + return [4 /*yield*/, dbBulkPutAll.dudes.get(highestKey)]; + case 12: + replacedRecord3 = _a.sent(); + QUnit.equal(replacedRecord3.last, "Persbrant2", "fjkljslk should now be Persbrant2 instead"); + return [4 /*yield*/, dbBulkPutAll.dudes.add({ username: "fsdkljfd", email: "fjkljslk", find: "bulkAddAll" })]; + case 13: + // should return last key with 1 argument and options: { allKeys: false } + highestKey = _a.sent(); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], { allKeys: false })]; + case 14: + lastKey = _a.sent(); + QUnit.equal(lastKey, highestKey + 2, "Result of bulkAdd(objects, { allKeys: false }) operation was equal to highestKey + 2"); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false })]; + case 15: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'b33vn3fytn', "Result of bulkAdd(objects, ['cv4btr45fbrt', 'b33vn3fytn'], { allKeys: false }) operation was equal to 'b33vn3fytn'"); + return [4 /*yield*/, dbBulkPutAll.dudes.bulkAdd([ + { first: "Åke1", last: "Persbrant1" }, + { first: "Åke2", last: "Persbrant2" } + ], ['dfgd2vdfh4d', 'ty1jxdbd9'])]; + case 16: + lastKey = _a.sent(); + QUnit.equal(lastKey, 'ty1jxdbd9', "Result of bulkAdd(objects, ['dfgd2vdfh4d', 'ty1jxdbd9']) operation was equal to 'ty1jxdbd9'"); + return [4 /*yield*/, dbBulkPutAll.delete()]; + case 17: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut with overlapping objects", function () { + var theOne; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.bulkPut([{ + id: "sdjls83", + first: "Daveious" + }, { + id: "sdjls83", + last: "Olvono" + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$b.users.get("sdjls83")]; + case 2: + theOne = _a.sent(); + QUnit.equal(theOne.last, "Olvono", "Last item is the one inserted"); + QUnit.ok(theOne.first === undefined, "Object doesnt have a first property"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-catching errors", function () { + var _a, newUsersX, e_4, _b, _c, newUsersY, e_5, _d, newUsersZ, _e; + return __generator(this, function (_f) { + switch (_f.label) { + case 0: return [4 /*yield*/, db$b.transaction("rw", db$b.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$b.users.bulkPut(newUsers).then(function () { + QUnit.ok(false, "Should not resolve when one operation failed"); + }).catch(Dexie__default["default"].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$b.users.where("username").startsWith("aper").count(function (count) { + QUnit.equal(count, 3, "Got three matches now when users are bulk-putted"); + }); + })]; + case 1: + _f.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.users.where("username").startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_f.sent(), 3, "Previous transaction committed"]); + newUsersX = [ + { first: "Xke1", last: "Persbrant1", username: "xper1", email: ["xper1@persbrant.net"] }, + { id: idOfLastUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, + { first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, + { id: idOfFirstUser, first: "Xke2", last: "Persbrant2", username: "xper2", email: ["xper2@persbrant.net"] }, + { first: "Xke3", last: "Persbrant3", username: "xper3", email: ["xper3@persbrant.net"] } + ]; + _f.label = 3; + case 3: + _f.trys.push([3, 5, , 6]); + return [4 /*yield*/, db$b.transaction("rw", db$b.users, function () { + db$b.users.bulkPut(newUsersX).then(function () { + QUnit.ok(false, "Should not resolve"); + }); + })]; + case 4: + _f.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 6]; + case 5: + e_4 = _f.sent(); + QUnit.ok(true, "Got: " + e_4); + return [3 /*break*/, 6]; + case 6: + _b = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('xper').count()]; + case 7: + _b.apply(void 0, [_f.sent(), 0, "0 users! Good, means that previous transaction did not commit"]); + return [4 /*yield*/, db$b.users.bulkPut(newUsersX).catch(function (e) { + QUnit.ok(true, "Got error. Catching it should make the successors work."); + })]; + case 8: + _f.sent(); + _c = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('xper').count()]; + case 9: + _c.apply(void 0, [_f.sent(), 3, + "Should count to 3 users because previous operation was catched and therefore should have been committed"]); + newUsersY = [ + { first: "Yke1", last: "Persbrant1", username: "yper1", email: ["yper1@persbrant.net"] }, + { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, + { id: idOfFirstUser, first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, + { first: "Yke2", last: "Persbrant2", username: "yper2", email: ["yper2@persbrant.net"] }, + { first: "Yke3", last: "Persbrant3", username: "yper3", email: ["yper3@persbrant.net"] } + ]; + _f.label = 10; + case 10: + _f.trys.push([10, 12, , 13]); + return [4 /*yield*/, db$b.users.bulkPut(newUsersY)]; + case 11: + _f.sent(); + return [3 /*break*/, 13]; + case 12: + e_5 = _f.sent(); + QUnit.ok(true, "Got: " + e_5); + return [3 /*break*/, 13]; + case 13: + _d = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('yper').count()]; + case 14: + _d.apply(void 0, [_f.sent(), 3, + "Should count to 3 users because previous previous operation catched (via try..yield..catch this time, and therefore should have been committed"]); + newUsersZ = [ + { first: "Zke1", last: "Persbrant1", username: "zper1", email: ["zper1@persbrant.net"] }, + { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, + { first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, + { id: idOfLastUser, first: "Zke2", last: "Persbrant2", username: "zper2", email: ["zper2@persbrant.net"] }, + { first: "Zke3", last: "Persbrant3", username: "zper3", email: ["zper3@persbrant.net"] } + ]; + return [4 /*yield*/, db$b.transaction('rw', db$b.users, function () { + var e_6; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db$b.users.bulkPut(newUsersZ)]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_6 = _a.sent(); + throw e_6; + case 3: return [2 /*return*/]; + } + }); + }).catch(Dexie__default["default"].BulkError, function (e) { + QUnit.ok(true, "Got rethrown BulkError: " + e.stack); + })]; + case 15: + _f.sent(); + _e = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('zper').count()]; + case 16: + _e.apply(void 0, [_f.sent(), 0, "0 users! Good - means that previous operation rethrown (via try..yield..catch--throw this time, and therefore not committed"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-non-inbound-autoincrement", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, db$b.folks.bulkPut([ + { first: "Foo", last: "Bar" }, + { first: "Foo", last: "Bar2" }, + { first: "Foo", last: "Bar3" }, + { first: "Foo", last: "Bar4" } + ])]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.folks.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_c.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db$b.folks.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_c.sent(), 1, "Should be 1 Bar"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut - mixed inbound autoIncrement", function () { + var lastId, _a, _b, newLastId, _c, _d, foo2s; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: return [4 /*yield*/, db$b.users.bulkPut([ + { first: "Foo", last: "Bar" }, + { first: "Foo", last: "Bar2" }, + { first: "Foo", last: "Bar3" }, + { first: "Foo", last: "Bar4" } + ])]; + case 1: + lastId = _e.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.users.where('first').equals('Foo').count()]; + case 2: + _a.apply(void 0, [_e.sent(), 4, "Should be 4 Foos"]); + _b = QUnit.equal; + return [4 /*yield*/, db$b.users.where('last').equals('Bar').count()]; + case 3: + _b.apply(void 0, [_e.sent(), 1, "Should be 1 Bar"]); + return [4 /*yield*/, db$b.users.bulkPut([ + { id: lastId - 3, first: "Foo2", last: "BarA" }, + { first: "Foo2", last: "BarB" }, + { id: lastId - 1, first: "Foo2", last: "BarC" }, + { first: "Foo2", last: "BarD" } // Will create + ])]; + case 4: + newLastId = _e.sent(); + QUnit.equal(newLastId, lastId + 2, "Should have incremented last ID twice now"); + _c = QUnit.equal; + return [4 /*yield*/, db$b.users.where('first').equals('Foo').count()]; + case 5: + _c.apply(void 0, [_e.sent(), 2, "Should be 2 Foos now"]); + _d = QUnit.equal; + return [4 /*yield*/, db$b.users.where('first').equals('Foo2').count()]; + case 6: + _d.apply(void 0, [_e.sent(), 4, "Should be 4 Foo2s now"]); + return [4 /*yield*/, db$b.users.where('first').equals('Foo2').toArray()]; + case 7: + foo2s = _e.sent(); + QUnit.equal(foo2s[0].last, "BarA", "BarA should be first (updated previous ID)"); + QUnit.equal(foo2s[1].last, "BarC", "BarC should be second (updated previous ID"); + QUnit.equal(foo2s[2].last, "BarB", "BarB should be third (got new key)"); + QUnit.equal(foo2s[3].last, "BarD", "BarD should be forth (got new key)"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkPut-catch sub transaction", function () { + var _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, db$b.transaction('rw', db$b.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$b.transaction('rw', db$b.users, function () { + db$b.users.bulkPut(newUsers); + }).then(function () { + QUnit.ok(false, "Should not succeed with all these operations"); + }).catch(function (e) { + QUnit.equal(e.failures.length, 1, "Should get one failure"); + }); + }).catch(function (e) { + QUnit.ok(true, "Outer transaction aborted due to inner transaction abort. This is ok: " + e); + })]; + case 1: + _b.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$b.users.where('username').startsWith('aper').count()]; + case 2: + _a.apply(void 0, [_b.sent(), 0, "0 users! Good, means that inner transaction did not commit"]); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkDelete", function () { + var userKeys, userCount; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.orderBy('id').keys()]; + case 1: + userKeys = _a.sent(); + QUnit.ok(userKeys.length > 0, "User keys found: " + userKeys.join(',')); + return [4 /*yield*/, db$b.users.bulkDelete(userKeys)]; + case 2: + _a.sent(); + return [4 /*yield*/, db$b.users.count()]; + case 3: + userCount = _a.sent(); + QUnit.equal(userCount, 0, "Should be no users there now"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkDelete - nonexisting keys", function () { + var userKeys, _a, userCount; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = ["nonexisting1", "nonexisting2"]; + return [4 /*yield*/, db$b.users.orderBy(':id').lastKey()]; + case 1: + userKeys = _a.concat([_b.sent()]); + return [4 /*yield*/, db$b.users.bulkDelete(userKeys)]; + case 2: + _b.sent(); + return [4 /*yield*/, db$b.users.count()]; + case 3: + userCount = _b.sent(); + QUnit.equal(userCount, 1, "Should be one user there now. (the other should have been deleted)"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("bulkDelete-faulty-key", function () { + var userKeys; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + userKeys = [{ faulty: "ohyes" }]; + return [4 /*yield*/, db$b.users.bulkDelete(userKeys).then(function () { + QUnit.ok(false, "Should not succeed"); + }).catch('DataError', function (e) { + QUnit.ok(true, "Should get error: " + e); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("delete", function () { + // Without transaction + db$b.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }).then(function () { + db$b.users.delete(1).then(function () { + db$b.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$b.transaction("rw", db$b.users, function () { + db$b.users.get(idOfFirstUser, function (user) { + notEqual(user, null, "User with id 1 exists"); + }); + db$b.users.delete(idOfFirstUser); + db$b.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$b.users.count().then(function (count) { + numUsers = count; + QUnit.ok(true, "Number of users before delete: " + count); + }).then(function () { + return db$b.users.delete("nonexisting key"); + }).then(function () { + QUnit.ok(true, "Success even though nothing was deleted"); + }).then(function () { + return db$b.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$b.transaction("rw", "users", function () { + db$b.users.count(function (count) { + QUnit.equal(count, 2, "There are 2 items in database before clearing it"); + }); + db$b.users.clear(); + db$b.users.count(function (count) { + QUnit.equal(count, 0, "There are 0 items in database after it has been cleared"); + }); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(QUnit.start); + }); + spawnedTest("failReadonly", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.transaction('r', 'users', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.bulkAdd([{ first: "Foo", last: "Bar" }])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('ReadOnlyError', function (e) { + QUnit.ok(true, "Got ReadOnlyError: " + e.stack); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("failNotIncludedStore", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.transaction('rw', 'folks', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$b.users.bulkAdd([{ first: "Foo", last: "Bar" }])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }).then(function () { + QUnit.ok(false, "Should not happen"); + }).catch('NotFoundError', function (e) { + QUnit.ok(true, "Got NotFoundError: " + e.stack); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("failNotIncludedStoreTrans", function () { + db$b.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); + }); + // Must use this rather than QUnit's deepEqual() because that one fails on Safari when run via karma-browserstack-launcher + function deepEqual$1(actual, expected, description) { + QUnit.equal(JSON.stringify(actual, null, 2), JSON.stringify(expected, null, 2), description); + } + function stripObj(obj, props) { + var e_7, _a; + var rv = {}; + try { + for (var _b = __values(props.slice().sort()), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + rv[key] = obj[key]; + } + } + catch (e_7_1) { e_7 = { error: e_7_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_7) throw e_7.error; } + } + return rv; + } + function sortObj(obj) { + return stripObj(obj, Object.keys(obj)); + } + function deepEqualPartial(actual, expected, description) { + if (Array.isArray(actual)) { + return deepEqual$1(actual.map(function (a, idx) { return stripObj(a, Object.keys(expected[idx])); }), expected.map(sortObj), description); + } + return deepEqual$1(stripObj(actual, Object.keys(expected)), sortObj(expected), description); + } + promisedTest("bulkGet()", function () { return __awaiter(void 0, void 0, void 0, function () { + var bulkData, i, keys, retrieved, _a, u1, u2, u3, u4; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + bulkData = []; + for (i = 0; i < 400; ++i) { + bulkData.push({ id: i, first: "Foo" + i, last: "Bar" + i }); + } + QUnit.ok("Putting ".concat(bulkData.length, " users into the table")); + return [4 /*yield*/, db$b.users.bulkPut(bulkData)]; + case 1: + _b.sent(); + QUnit.ok("Done putting users. Now getting them using bulkGet()"); + keys = bulkData.map(function (_a) { + var id = _a.id; + return id; + }); + return [4 /*yield*/, db$b.users.bulkGet(keys)]; + case 2: + retrieved = _b.sent(); + deepEqual$1(retrieved, bulkData, "Put and retrieved should be the same"); + QUnit.ok("Now validating that is should be possible to request nonexisting keys but yet get all results in the order of the given keys"); + return [4 /*yield*/, db$b.users.bulkGet(["x", "y", 100, "z"])]; + case 3: + _a = __read.apply(void 0, [_b.sent(), 4]), u1 = _a[0], u2 = _a[1], u3 = _a[2], u4 = _a[3]; + QUnit.ok(u1 === undefined, "First result should be undefined, as there where no object with that key"); + QUnit.ok(u2 === undefined, "Second objects -''-"); + QUnit.ok(u3 && u3.first === 'Foo100', "Third should be Foo100"); + QUnit.ok(u4 === undefined, "Forth should be undefined"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("bulkError by pos", function () { return __awaiter(void 0, void 0, void 0, function () { + var bulkError_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, db$b.users.bulkAdd([ + { first: "foo1", last: "bar1", username: "foobar" }, + { first: "foo2", last: "bar2", username: "foobar" }, + { first: "foo3", last: "bar3", username: "foobar3" }, + ])]; + case 1: + _a.sent(); + QUnit.ok(false, "Should not succeed"); + return [3 /*break*/, 3]; + case 2: + bulkError_1 = _a.sent(); + QUnit.ok(bulkError_1 instanceof Dexie__default["default"].BulkError, "Got BulkError"); + QUnit.equal(bulkError_1.failures.length, 1, "Got one failure"); + QUnit.ok(!!bulkError_1.failures[0], "failures[0] is one Error"); + QUnit.ok(bulkError_1.failures[1] === undefined, "failures[1] is undefined"); + QUnit.equal(Object.keys(bulkError_1.failuresByPos).length, 1, "Got one key in failuresByPos"); + QUnit.equal(Object.keys(bulkError_1.failuresByPos)[0], 1, "Failure in position 1"); + QUnit.ok(bulkError_1.failuresByPos[0] === undefined, "failuresByPos[0] is undefined"); + QUnit.ok(!!bulkError_1.failuresByPos[1], "failuresByPos[1] is one Error"); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); }); + + module("chrome-transaction-durability", { + setup: function () { + }, + teardown: function () { + } + }); + QUnit.asyncTest("Transaction should use relaxed durability if specified", function () { + if (!isChrome) { + QUnit.ok(true, "This browser does not support Chrome transaction durability"); + QUnit.start(); + return; + } + var db = setupDb('relaxed'); + db.transaction('rw', db.users, function (trans) { + if (trans.idbtrans.durability === void 0) { + QUnit.ok(true, "This version of Chromium does not support transaction durability"); + } + else { + QUnit.ok(trans.idbtrans.durability === 'relaxed', "Transaction has relaxed durability"); + } + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }); + }); + QUnit.asyncTest("Transaction should use strict durability if specified", function () { + if (!isChrome) { + QUnit.ok(true, "This browser does not support Chrome transaction durability"); + QUnit.start(); + return; + } + var db = setupDb('strict'); + db.transaction('rw', db.users, function (trans) { + if (trans.idbtrans.durability === void 0) { + QUnit.ok(true, "This version of Chromium does not support transaction durability"); + } + else { + QUnit.ok(trans.idbtrans.durability === 'strict', "Transaction has strict durability"); + } + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }); + }); + QUnit.asyncTest("Transaction should use default durability if not specified", function () { + if (!isChrome) { + QUnit.ok(true, "This browser does not support Chrome transaction durability"); + QUnit.start(); + return; + } + var db = setupDb(); + db.transaction('rw', db.users, function (trans) { + if (trans.idbtrans.durability === void 0) { + QUnit.ok(true, "This version of Chromium does not support transaction durability"); + } + else { + QUnit.ok(trans.idbtrans.durability === 'default', "Transaction has default durability"); + } + }).catch(function (err) { + QUnit.ok(false, err); + }).finally(function () { + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }); + }); + var setupDb = function (chromeTransactionDurability) { + var db = new Dexie__default["default"]("TestDBTrans", { chromeTransactionDurability: chromeTransactionDurability }); + db.version(1).stores({ + users: "username", + }); + return db; + }; + + var db$a = new Dexie__default["default"]("TestDBCollection"); + db$a.version(1).stores({ users: "id,first,last,[foo+bar],&username,*&email,*pets" }); + db$a.users.defineClass({ + id: Number, + first: String, + last: String, + username: String, + email: [String], + pets: [String], + }); + db$a.on("populate", function () { + db$a.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$a.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$a).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + spawnedTest("and with values", function () { + var array; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$a.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]) + .and(function (user) { return user.username === "dfahlander"; }) + .toArray()]; + case 1: + array = _a.sent(); + QUnit.equal(array.length, 1, "Should find one user with given criteria"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("and with keys", function () { + var keys; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$a.users.where("last").inAnyRange([["a", "g"], ["A", "G"]]) + .and(function (user) { return user.username === "dfahlander"; }) + .keys()]; + case 1: + keys = _a.sent(); + QUnit.equal(keys.length, 1, "Should find one user with given criteria"); + return [2 /*return*/]; + } + }); + }); + spawnedTest("and with delete", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$a.users.orderBy('username') + .and(function (u) { return QUnit.ok(!!u, "User should exist here"); }) + .delete()]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("each", 3, function () { + var array = []; + db$a.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$a.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$a.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$a.transaction("r", db$a.users, function () { + db$a.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$a.users.orderBy("last").limit(10).toArray(function (a) { + QUnit.equal(a.length, 2, "Array length is 2"); + }); + db$a.users.orderBy("last").limit(0).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$a.users.orderBy("last").limit(-1).toArray(function (a) { + QUnit.equal(a.length, 0, "Array length is 0"); + }); + db$a.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$a.transaction("rw", db$a.users, function () { + for (var i = 0; i < 10; ++i) { + db$a.users.add({ id: 3 + i, first: "First" + i, last: "Last" + i, username: "user" + i, email: ["user" + i + "@abc.se"] }); + } + // Using algorithm + count() + db$a.users.where("first").startsWithIgnoreCase("first").count(function (count) { + QUnit.equal(count, 10, "Counting all 10"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").limit(5).count(function (count) { + QUnit.equal(count, 5, "algorithm + count(): limit(5).count()"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).count()"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "algorithm + count(): offset(6).limit(4)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "algorithm + count(): offset(7).limit(4)"); + }); + db$a.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$a.users.where("first").startsWithIgnoreCase("first").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "algorithm + toArray(): limit(5)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "algorithm + toArray(): offset(6).limit(4)"); + }); + db$a.users.where("first").startsWithIgnoreCase("first").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "algorithm + toArray(): offset(7).limit(4)"); + }); + db$a.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$a.users.where("first").startsWith("First").count(function (count) { + QUnit.equal(count, 10, "IDBKeyRange + count() - count all 10"); + }); + db$a.users.where("first").startsWith("First").limit(5).count(function (count) { + QUnit.equal(count, 5, "IDBKeyRange + count(): limit(5)"); + }); + db$a.users.where("first").startsWith("First").offset(7).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7)"); + }); + db$a.users.where("first").startsWith("First").offset(6).limit(4).count(function (count) { + QUnit.equal(count, 4, "IDBKeyRange + count(): offset(6)"); + }); + db$a.users.where("first").startsWith("First").offset(7).limit(4).count(function (count) { + QUnit.equal(count, 3, "IDBKeyRange + count(): offset(7).limit(4)"); + }); + db$a.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$a.users.where("first").startsWith("First").limit(5).toArray(function (a) { + QUnit.equal(a.length, 5, "IDBKeyRange + toArray(): limit(5)"); + }); + db$a.users.where("first").startsWith("First").offset(7).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7)"); + }); + db$a.users.where("first").startsWith("First").offset(6).limit(4).toArray(function (a) { + QUnit.equal(a.length, 4, "IDBKeyRange + toArray(): offset(6).limit(4)"); + }); + db$a.users.where("first").startsWith("First").offset(7).limit(4).toArray(function (a) { + QUnit.equal(a.length, 3, "IDBKeyRange + toArray(): offset(7).limit(4)"); + }); + db$a.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$a.users.orderBy("last").first(function (karlCeder) { + QUnit.equal(karlCeder.first, "Karl", "Got Karl"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("last", function () { + db$a.users.orderBy("last").last(function (david) { + QUnit.equal(david.first, "David", "Got David"); + }).finally(QUnit.start); + }); + QUnit.asyncTest("and", 2, function () { + db$a.transaction("r", db$a.users, function () { + db$a.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$a.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$a.transaction("r", db$a.users, function () { + db$a.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$a.transaction("r", db$a.users, function () { + db$a.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$a.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$a.transaction("rw", db$a.users, function () { + var currentTime = new Date(); + db$a.users.toCollection().modify({ + lastUpdated: currentTime + }).then(function (count) { + QUnit.equal(count, 2, "Promise supplied the number of modifications made"); + }); + db$a.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$a.transaction("rw", db$a.users, function () { + var currentTime = new Date(); + db$a.users.toCollection().modify(function (user) { + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$a.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$a.transaction("rw", db$a.users, function () { + var currentTime = new Date(); + db$a.users.toCollection().modify(function (user) { + user.id = 1; + user.fullName = user.first + " " + user.last; + user.lastUpdated = currentTime; + }); + db$a.users.toArray(function (a) { + QUnit.ok(false, "Should not come here, beacuse we should get error when setting all primkey to 1"); + }); + }).catch(Dexie__default["default"].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); + }); + promisedTest("modify-primary-key", function () { return __awaiter(void 0, void 0, void 0, function () { + var res, user88; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$a.users.add({ id: 87, first: "Olle" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$a.users.where({ id: 87 }).modify(function (user) { return user.id = 88; })]; + case 2: + res = _a.sent(); + QUnit.ok(res, "Successfully modified the primary key of a user"); + return [4 /*yield*/, db$a.users.get(88)]; + case 3: + user88 = _a.sent(); + QUnit.ok(!!user88, "Should be able to retrieve user 88 using db.users.get(88)"); + QUnit.equal(user88.first, "Olle", "Retrieved user should be David"); + return [2 /*return*/]; + } + }); + }); }); + // + // Issue #594 (A Safari issue) + // + promisedTest("modify-with-where(issue-594)", function () { return __awaiter(void 0, void 0, void 0, function () { + var numDavids, numModifications, davids; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db$a.users.add({ id: 3, first: "David", last: "Fahlander2", username: "dfahlander2", email: ["david2@awarica.com"], pets: [] }); + db$a.users.add({ id: 4, first: "David", last: "Fahlander3", username: "dfahlander3", email: ["david3@awarica.com"], pets: [] }); + return [4 /*yield*/, db$a.users.where('first').equals("David").toArray()]; + case 1: + numDavids = (_a.sent()).length; + QUnit.equal(numDavids, 3, "There should be 3 Davids"); + return [4 /*yield*/, db$a.users.where('first').equals("David").modify(function (object) { object.anotherProperty = 'test'; })]; + case 2: + numModifications = _a.sent(); + QUnit.equal(numModifications, 3, "There should have been 3 modifications"); + return [4 /*yield*/, db$a.users.where({ first: 'David' }).toArray()]; + case 3: + davids = _a.sent(); + QUnit.ok(davids.every(function (david) { return david.anotherProperty === 'test'; }), "All Davids where modified indeed"); + return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("delete", 2, function () { + db$a.users.orderBy("id").delete().then(function (count) { + QUnit.equal(count, 2, "All two records deleted"); + return db$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$a.users.where("first").equalsIgnoreCase("david").delete().then(function (deleteCount) { + QUnit.equal(deleteCount, 2, "Two items deleted (Both davids)"); + }); + db$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "dAvid", last: "Helenius", username: "dahel" }); + db$a.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$a.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", 3, function () { + db$a.users.orderBy("first").keys(function (a) { + QUnit.equal(a.length, 2, "There should be two results"); + 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", 7, function () { + db$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "David", last: "Helenius", username: "dahel" }); + db$a.users.orderBy("first").keys(function (a) { + QUnit.equal(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$a.users.orderBy("first").uniqueKeys(function (a) { + QUnit.equal(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", 3, function () { + db$a.users.orderBy("last").primaryKeys(function (a) { + QUnit.equal(a.length, 2, "There should be two results"); + 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", 3, function () { + db$a.users.orderBy("first").primaryKeys(function (a) { + QUnit.equal(a.length, 2, "There should be two results"); + 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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "Ylva", last: "Fahlander", username: "yfahlander" }); + var a = []; + db$a.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$a.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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "Apan", last: "Japan", username: "apanjapan" }); + db$a.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$a.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$a.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__default["default"]("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 }); + } + var seed = 1; + function pseudoRandom() { + var x = Math.sin(seed++) * 10000; + return x - Math.floor(x); + } + function randomString(count) { + var ms = []; + for (var i = 0; i < count; ++i) { + ms.push(String.fromCharCode(32 + Math.floor(pseudoRandom() * 95))); + } + 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$a.transaction("rw", db$a.users, function () { + db$a.users.add({ id: 3, first: "Apa1", username: "apa1" }); + db$a.users.add({ id: 4, first: "Apa2", username: "apa2" }); + db$a.users.add({ id: 5, first: "Apa3", username: "apa3" }); + // Checking that it stops immediately when first item is the stop item: + db$a.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$a.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$a.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$a.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$a.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$a.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$a.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$a.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$a.transaction('r', db$a.users, function () { + db$a.users.each(function (user) { + db$a.users.where('id').equals(user.id).first(function (usr) { + return db$a.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); + }); + promisedTest("Issue 1381: Collection.filter().primaryKeys() on virtual index", function () { return __awaiter(void 0, void 0, void 0, function () { + var ids; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("compound")) { + QUnit.ok(true, "Skipping this test as the browser does not support compound indexes"); + return [2 /*return*/]; + } + // The original repro: https://jsitor.com/qPJXVESEcb failed when using Collection.delete(). + // Debugging it led me to that there is a general problem with virtual cursor's primaryKey property. + // So that's what we're testing here: + return [4 /*yield*/, db$a.users.add({ id: 1000, foo: "A", bar: "B" })]; + case 1: + // The original repro: https://jsitor.com/qPJXVESEcb failed when using Collection.delete(). + // Debugging it led me to that there is a general problem with virtual cursor's primaryKey property. + // So that's what we're testing here: + _a.sent(); + return [4 /*yield*/, db$a.users.where({ foo: "A" }).filter(function (x) { return true; }).primaryKeys()]; + case 2: + ids = _a.sent(); + QUnit.ok(ids.length === 1, "Theres one id there"); + QUnit.equal(ids[0], 1000, "The ID is 1000"); + return [2 /*return*/]; + } + }); + }); }); + + Dexie__default["default"].async; + var db$9 = new Dexie__default["default"]("TestDBWhereClause"); + db$9.version(2).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+age]", + multiMulti: "id,*tags,*categories" + }); + var Folder = db$9.folders.defineClass({ + id: Number, + path: String, + description: String + }); + var File = db$9.files.defineClass({ + id: Number, + filename: String, + extension: String, + folderId: Number + }); + File.prototype.getFullPath = function () { + var file = this; + return db$9.folders.get(this.folderId, function (folder) { + return folder.path + "/" + file.filename + (file.extension || ""); + }); + }; + Folder.prototype.getFiles = function () { + return db$9.files.where('folderId').equals(this.id).toArray(); + }; + var Chart = db$9.chart.defineClass({ + patno: Number, + row: Number, + col: Number, + sym: Number + }); + Chart.prototype.save = function () { + return db$9.chart.put(this); + }; + var firstFolderId = 0; + db$9.on("populate", function () { + var folders = db$9.table("folders"); + var files = db$9.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) { + }); + 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) { + return files.add({ filename: "hello-there", extension: ".exe", folderId: id }); + }).then(function (id) { + }); + }); + QUnit.module("WhereClause", { + setup: function () { + QUnit.stop(); + resetDatabase(db$9).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + spawnedTest('Issue#31 Compound Index with anyOf', function () { + var items; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports('compound')) + return [2 /*return*/, QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")]; + return [4 /*yield*/, db$9.people.bulkAdd([{ + name: 0, + number: 0, + tag: "A" + }, { + name: -1, + number: 0, + tag: "B" + }, { + name: -2, + number: 0, + tag: "C" + }, { + name: -3, + number: 0, + tag: "D" + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.people + .where('[name+number]') + .anyOf([[-2, 0], [-3, 0]]) // https://github.com/dfahlander/Dexie.js/issues/31 + .toArray()]; + case 2: + items = _a.sent(); + QUnit.equal(items.length, 2, "It should contain 2 items."); + QUnit.equal(items[0].tag, "D", "First we should get D"); + QUnit.equal(items[1].tag, "C", "then we should get C"); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("startsWithAnyOf()", function () { + function runTheTests(mippler) { + /// + // + // Basic Flow: + // + return mippler(db$9.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$9.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__default["default"].Promise.all(mippler(db$9.folders.where('path').startsWithAnyOf([])).count(), // Empty + mippler(db$9.folders.where('path').startsWithAnyOf('/var', '/var', '/var')).count(), // Duplicates + mippler(db$9.folders.where('path').startsWithAnyOf('')).count(), // Empty string should match all + mippler(db$9.folders).count(), mippler(db$9.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$9.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$9.transaction('r', db$9.folders, db$9.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$9.transaction("r", db$9.files, db$9.folders, function () { + db$9.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$9.files.put({ id: 9000, filename: "new file 1", folderId: firstFolderId }); + db$9.files.put({ id: 10000, filename: "new file 2", folderId: firstFolderId }); + db$9.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$9.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$9.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$9.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$9.transaction("rw", db$9.files, function () { + fileArray.forEach(function (file) { + db$9.files.add(file); + }); + db$9.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$9.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$9.transaction("rw", db$9.files, function () { + fileArray.forEach(function (file) { + db$9.files.add(file); + }); + db$9.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__default["default"].dependencies.indexedDB === idbModules.shimIndexedDB) { + // Using indexedDBShim. + QUnit.ok(false, "This test would hang with IndexedDBShim as of 2015-05-07"); + QUnit.start(); + return; + } + db$9.transaction("rw", db$9.files, function () { + db$9.files.clear(); + db$9.files.add({ filename: "Hello-there-", folderId: 1 }); + db$9.files.add({ filename: "hello-there-", folderId: 1 }); + db$9.files.add({ filename: "hello-there-everyone", folderId: 1 }); + db$9.files.add({ filename: "hello-there-everyone-of-you!", folderId: 1 }); + // Ascending + db$9.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$9.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$9.transaction("r", db$9.folders, function () { + db$9.folders.count(function (count) { + QUnit.ok(true, "Number of folders in database: " + count); + db$9.folders.where("path").startsWithIgnoreCase("/").toArray(function (a) { + QUnit.equal(a.length, count, "Got all folder objects because all of them starts with '/'"); + }); + }); + db$9.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$9.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$9.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$9.transaction("r", db$9.files, function () { + db$9.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$9.transaction('rw', db$9.people, function () { + db$9.people.add({ name: "Santaclaus", number: 123 }); + db$9.people.add({ name: "Santaclaus", number: 124 }); + db$9.people.add({ name: "Santaclaus2", number: 1 }); + return db$9.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$9.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$9.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$9.transaction("rw", db$9.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$9.chart.bulkAdd(chart); + }).then(function () { + var grid = [], x1 = 91, x2 = 130; + return db$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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", + //"/var/bin" + ], 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$9.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", + //"/var/bin" + ], 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$9.transaction('rw', db$9.friends, function () { + db$9.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$9.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$9.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$9.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$9.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$9.transaction('r', db$9.folders, db$9.files, function () { + db$9.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$9.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$9.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$9.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$9.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$9.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__default["default"].Promise.all(mippler(db$9.folders.where('path').startsWithAnyOfIgnoreCase([])).count(), // Empty + mippler(db$9.folders.where('path').startsWithAnyOfIgnoreCase('/var', '/var', '/var')).count(), // Duplicates + mippler(db$9.folders.where('path').startsWithAnyOfIgnoreCase('')).count(), // Empty string should match all + mippler(db$9.folders).count(), mippler(db$9.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$9.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$9.transaction('r', db$9.folders, db$9.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(void 0, 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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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$9.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("where({notIndexed: value}) should not return emtpy result", function () { return __awaiter(void 0, void 0, void 0, function () { + var chaplin, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$9.chaps.add({ name: "Chaplin", number: 1, age: 134, notIndexed: 'foo' })]; + case 1: + _a.sent(); + _a.label = 2; + case 2: + _a.trys.push([2, 4, , 5]); + return [4 /*yield*/, db$9.chaps.where({ name: "Chaplin", notIndexed: "foo" }).first()]; + case 3: + chaplin = _a.sent(); + if (!chaplin) { + QUnit.ok(false, "Got empty result when data exists matching the query. If we're not using an index we should not get an empty result but an error."); + } + else { + QUnit.ok(chaplin, "Ok, so we got a result even though 'notIndexed' is not indexed at all. " + + "This is not expected but ok if the result would be valid"); + QUnit.equal(chaplin.name, "Chaplin", "Got the correct data Chaplin!"); + } + return [3 /*break*/, 5]; + case 4: + e_1 = _a.sent(); + QUnit.ok(true, "Got error: \"".concat(e_1, "\" because 'notIndexed' is not indexed at all. This is also ok.")); + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); }); + promisedTest("orderBy(['idx1','idx2'])", function () { return __awaiter(void 0, 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$9.files.add({ filename: "hello", extension: ".bat" }); + return [4 /*yield*/, db$9.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*/]; + } + }); + }); }); + promisedTest("Issue #696 - Query on multiple multi-entry indexes doesn't seem to work", function () { return __awaiter(void 0, void 0, void 0, function () { + var cat_a, cat_a_tag_a; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("multientry")) { + QUnit.ok(true, "No support for multiEntry in browser. Skippping."); + return [2 /*return*/]; + } + return [4 /*yield*/, db$9.multiMulti.bulkAdd([ + { id: 1, name: "Foo", age: 42, categories: ['cat_a', 'cat_b'], tags: ['tag_a', 'tag_b'] }, + { id: 2, name: "Bar", age: 32, categories: ['cat_b', 'cat_c'], tags: ['tag_b', 'tag_c'] } + ])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.multiMulti.where({ categories: 'cat_a' }).distinct().toArray()]; + case 2: + cat_a = _a.sent(); + QUnit.equal(cat_a.length, 1, "Should get one item"); + return [4 /*yield*/, db$9.multiMulti.where({ 'categories': 'cat_a', 'tags': 'tag_a' }) + .distinct() + .toArray()]; + case 3: + cat_a_tag_a = _a.sent(); + QUnit.equal(cat_a_tag_a.length, 1, "Should get one item here as well"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Virtual Index", function () { return __awaiter(void 0, void 0, void 0, function () { + var davids, mambosNumber5, daves; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports('compound')) + return [2 /*return*/, QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")]; + return [4 /*yield*/, db$9.chaps.bulkAdd([{ + name: "David", + number: 2, + age: 29 + }, { + name: "David", + number: 3, + age: 39 + }, { + name: "David", + number: 1, + age: 49 + }, { + name: "Mambo", + number: 5, + age: 55 + }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.chaps.where({ name: "David" }).toArray()]; + case 2: + davids = _a.sent(); + QUnit.equal(davids.length, 3, "There should be 3 Davids in the result"); + return [4 /*yield*/, db$9.chaps.where({ name: "Mambo", number: 5 }).toArray()]; + case 3: + mambosNumber5 = _a.sent(); + QUnit.equal(mambosNumber5.length, 1, "There should be 1 Mambo no 5 in the result"); + return [4 /*yield*/, db$9.chaps.where('name').equalsIgnoreCase('david').toArray()]; + case 4: + daves = _a.sent(); + QUnit.equal(JSON.stringify(daves.map(function (_a) { + var name = _a.name, number = _a.number; + return ({ name: name, number: number }); + }), null, 2), JSON.stringify([ + { name: "David", number: 1 }, + { name: "David", number: 2 }, + { name: "David", number: 3 } + ], null, 2), "equalsIgnoreCase() should work with virtual indexes"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("WhereClause.equals(invalid key)", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$9.files.where("filename").equals(null).first().then(function () { + QUnit.ok(false, "db.files.where('filename').equals(null) must fail but it didnt!"); + }).catch(function (error) { + QUnit.ok(true, "db.files.where('filename').equals(null) failed as expected (with ".concat(error, ")")); + })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$9.files.where("filename").equals(undefined).first().then(function () { + QUnit.ok(false, "db.files.where('filename').equals(undefined) must fail but it didnt!"); + }).catch(function (error) { + QUnit.ok(true, "db.files.where('filename').equals(undefined) failed as expected (with ".concat(error, ")")); + })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$9.files.where("filename").equals(function () { }).first().then(function () { + QUnit.ok(false, "db.files.where('filename').equals(function(){}) must fail but it didnt!"); + }).catch(function (error) { + QUnit.ok(true, "db.files.where('filename').equals(function(){}) failed as expected (with ".concat(error, ")")); + })]; + case 3: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var db$8 = new Dexie__default["default"]("TestDBTrans"); + db$8.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + QUnit.module("transaction", { + setup: function () { + QUnit.stop(); + resetDatabase(db$8).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + var NativePromise$2 = window.Promise; + QUnit.asyncTest("Transaction should work when returning native Promise in transaction scope", function () { + if (!NativePromise$2) { + QUnit.ok(true, "Current Browser doesn't have a native Promise"); + return QUnit.start(); + } + db$8.transaction('rw', db$8.users, function (trans) { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "First argument to transaction callback should be the transaction instance itself"); + return NativePromise$2.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + }).then(function () { + return db$8.users.add({ username: "barfoo" }); // Will only work on Chrome, Opera and Edge as of Oktober 6, 2016. + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Dexie.currentTransaction should persted through the native promise!"); + return db$8.users.count(); + }); + }).then(function (count) { + QUnit.ok(true, "User count: ".concat(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: ".concat(e.stack || e)); + }).finally(QUnit.start); + }); + QUnit.asyncTest("empty transaction block", function () { + db$8.transaction('rw', db$8.users, db$8.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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "arne" }); + return db$8.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__default["default"].currentTransaction != null, "Current Transaction must be set"); + }); + }).then(function () { + QUnit.ok(Dexie__default["default"].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$8.pets.add({ kind: "dog" }).then(function () { + return db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "arne" }); + return db$8.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$8.transaction('rw', db$8.users, function () { + db$8.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$8.transaction('r', db$8.users, function () { + db$8.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$8.transaction('rw', db$8.users, function () { + return new Dexie__default["default"].Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie__default["default"].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$8.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$8.transaction('rw', db$8.users, function () { + // First make an operation so that transaction is internally created (this is the thing differing from the previous test case + return db$8.users.add({ username: "arne" }).then(function () { + // Create a custom promise that will use setTimeout() so that IDB transaction will commit + return new Dexie__default["default"].Promise(function (resolve, reject) { + // Notify log when transaction completes too early + Dexie__default["default"].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$8.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$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + QUnit.ok(parentTrans._reculock > 0, "Parent transaction is locked"); + db$8.users.add(user); + pets.forEach(function (pet) { + db$8.pets.add(pet).then(function (petId) { + return db$8.petsPerUser.add({ user: user.username, pet: petId }); + }); + }); + }).then(function () { + return db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: user.username + "2" }); + return "hello..."; + }); + }); + } + db$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + var trans = Dexie__default["default"].currentTransaction; + parentTrans = Dexie__default["default"].currentTransaction; + QUnit.ok(trans._reculock === 0, "Main transaction not locked yet"); + addUser({ username: "user1" }, [{ kind: "dog" }, { kind: "cat" }]).then(function () { + db$8.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$8.users.get("someoneelse", function (someone) { + QUnit.ok(!someone, "Someoneelse not yet added"); + }); + db$8.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__default["default"].currentTransaction == null, "Dexie.currentTransaction is null"); + db$8.users.count(function (count) { + QUnit.equal(count, 5, "There are five users in db"); + }); + db$8.pets.count(function (count) { + QUnit.equal(count, 3, "There are three pets in db"); + }); + db$8.petsPerUser.count(function (count) { + QUnit.equal(count, 3, "There are three pets-to-user relations"); + }); + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == null, "Dexie.currentTransaction is null"); + // Start an outer transaction + return db$8.transaction('rw', db$8.users, function () { + // Do an add operation + db$8.users.add({ username: "sune" }); //.then(function () { + // Start an inner transaction + db$8.transaction('rw', db$8.users, function () { + // Do an add-operation that will result in ConstraintError: + db$8.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$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + db$8.users.add({ username: "ojsan" }); + db$8.transaction('rw', db$8.users, db$8.pets, function () { + db$8.users.add({ username: "ojsan2" }); + db$8.users.toCollection().delete(); + db$8.transaction('r', db$8.users, function () { + db$8.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie__default["default"].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__default["default"].Promise.resolve().then(function () { + return db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "bertil" }); + db$8.transaction('rw', db$8.users, db$8.pets, function () { + db$8.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$8.transaction('r', db$8.users, db$8.pets, function () { + db$8.users.toArray(); + db$8.transaction('rw', db$8.users, db$8.pets, function () { + db$8.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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "bertil" }); + db$8.transaction('rw!', db$8.users, db$8.pets, function () { + db$8.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__default["default"].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$8.transaction('r', db$8.users, db$8.pets, function () { + db$8.users.toArray(); + db$8.transaction('rw!', db$8.users, db$8.pets, function () { + db$8.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__default["default"]("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.delete() + .then(function () { return db2.open(); }) + .then(function () { return db$8.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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "bertil" }); + db$8.transaction('rw?', db$8.users, db$8.pets, function () { + db$8.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__default["default"].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$8.transaction('r', db$8.users, db$8.pets, function () { + db$8.users.toArray(); + db$8.transaction('rw?', db$8.users, db$8.pets, function () { + db$8.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__default["default"]("TestDB2"); + db2.version(1).stores({ + users: "username", + pets: "++id,kind", + petsPerUser: "++,user,pet" + }); + db2.open(); + db$8.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$8.transaction('rw', db$8.users, db$8.pets, db$8.petsPerUser, function () { + db$8.users.add({ username: "ojsan" }); + db$8.transaction('rw?', db$8.users, db$8.pets, function () { + db$8.users.add({ username: "ojsan2" }); + db$8.users.toCollection().delete(); + db$8.transaction('r?', db$8.users, function () { + db$8.users.toArray(function (usersArray) { + QUnit.equal(usersArray.length, 0, "All users should be deleted"); + Dexie__default["default"].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__default["default"]("logger"); + logDb.version(1).stores({ + log: "++,time,type,message" + }); + var lastLogAddPromise; + logDb.open().then(function () { + return db$8.transaction('rw', db$8.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$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + QUnit.ok(true, "Now adding Gunnar in parent transaction"); + db$8.users.add({ username: "Gunnar" }).then(function () { + QUnit.ok(true, "First add on parent transaction finished. Now adding another object in parent transaction."); + db$8.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$8.transaction('rw', db$8.users, function () { + QUnit.ok(true, "Entered sub transaction"); + return db$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + QUnit.ok(true, "Entered parent transaction"); + var trans = Dexie__default["default"].currentTransaction; + return db$8.transaction('rw', db$8.users, function () { + QUnit.ok(true, "Entered sub transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction !== trans, "We are not in parent transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction.parent === trans, "...but in a sub transaction"); + return Dexie__default["default"].Promise.resolve(3); + }).then(function (result) { + QUnit.equal(result, 3, "Got 3"); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Now we are in parent transaction"); + db$8.users.add({ username: "Gunnar" }); + return db$8.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__default["default"].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$8.transaction('rw', db$8.users, db$8.pets, function () { + console.log("Entering small child"); + return db$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + console.log("Entering middle child"); + return db$8.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$8.transaction('rw', db$8.users, db$8.pets, function () { + console.log("Entering root transaction"); + return db$8.transaction('rw', db$8.users, db$8.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__default["default"].currentTransaction, "There is no ongoing transaction"); + db$8.transaction('rw', db$8.pets, function () { + var rootLevelTransaction = Dexie__default["default"].currentTransaction; + QUnit.ok(true, "Entered root transaction scope"); + return db$8.transaction('rw', db$8.pets, function () { + QUnit.ok(true, "Entered sub scope"); + var level2Transaction = Dexie__default["default"].currentTransaction; + QUnit.ok(level2Transaction.parent === rootLevelTransaction, "Level2 transaction's parent is the root level transaction"); + return db$8.transaction('rw', db$8.pets, function () { + QUnit.ok(true, "Entered sub of sub scope"); + var innermostTransaction = Dexie__default["default"].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__default["default"].Promise.resolve().then(function () { + QUnit.ok(true, "Sub of sub scope: Promise.resolve().then() called"); + QUnit.ok(!!Dexie__default["default"].currentTransaction, "There is an ongoing transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return db$8.pets.add({ + id: 123, + value: 'val' + }).then(function (resultId) { + QUnit.ok(true, "Sub of sub scope: add() resolved"); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(resultId).then(function (res) { + return Dexie__default["default"].Promise.resolve(res); + }); + }).then(function (resultId) { + QUnit.ok(true, "Sub if sub scope: Promise.resolve() after add() resolve"); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(resultId); + }); + }).then(function () { + QUnit.ok(true, "sub of sub scope chaining further in promise chains..."); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(db$8.pets.get(123)); + }).then(function (pet) { + QUnit.ok(true, "sub of sub scope chaining further in promise chains 2..."); + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction, "Still in innermost transaction"); + return Dexie__default["default"].Promise.resolve(pet.id); + }); + }).then(function (resultId) { + QUnit.ok(true, "Innermost transaction completed"); + QUnit.ok(Dexie__default["default"].currentTransaction == level2Transaction, "We should now be executing within level 2 sub transaction"); + return Dexie__default["default"].Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.ok(Dexie__default["default"].currentTransaction == level2Transaction, "We should still be executing within level 2 sub transaction"); + return Dexie__default["default"].Promise.resolve(resultId); + }).then(function (resultId) { + QUnit.equal(resultId, 123, "Result was 123 as expected"); + }).then(function () { + return db$8.transaction('rw', db$8.pets, function () { + var innermostTransaction2 = Dexie__default["default"].currentTransaction; + QUnit.ok(innermostTransaction2.parent == level2Transaction, "Another 3rd level transaction has parent set to our level2 transaction"); + return db$8.pets.add({ + id: 321, + value: 'val' + }).then(function (resultId2) { + return Dexie__default["default"].Promise.resolve(resultId2); + }).then(function (resultId2) { + QUnit.ok(Dexie__default["default"].currentTransaction === innermostTransaction2, "We're still in the innermostTransaction (second one)"); + return Dexie__default["default"].Promise.resolve(resultId2).then(function (x) { + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction === level2Transaction, "We should still be executing within level 2 sub transaction"); + return "finalResult"; + }); + }); + }).then(function (x) { + QUnit.ok(Dexie__default["default"].currentTransaction === rootLevelTransaction, "Now we're at the root level transaction and can do some more stuff here"); + return db$8.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__default["default"].currentTransaction, "No ongoing transaction now"); + QUnit.ok(true, "done"); + }).catch(function (error) { + QUnit.ok(false, error.stack); + }).finally(QUnit.start); + QUnit.ok(!Dexie__default["default"].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$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "erictheviking", color: "blue" }).then(function () { + db$8.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$8.users.put({ username: "erictheviking", color: "red" }); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + QUnit.asyncTest("Dexie.currentTransaction in CRUD hooks", 83 /* If fails on num assertions, it's ok to change to expected if all looks fine */, function () { + function CurrentTransChecker(scope, trans) { + return function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Dexie.currentTransaction correct in " + scope); + }; + } + function onCreating(primKey, obj, transaction) { + QUnit.ok(!!Dexie__default["default"].currentTransaction, "Dexie.currentTransaction should exist in creating"); + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction, "Dexie.currentTransaction should exist in reading"); + return obj; + } + function onUpdating(modifications, primKey, obj, transaction) { + QUnit.ok(Dexie__default["default"].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__default["default"].currentTransaction === transaction, "Dexie.currentTransaction correct in deleting"); + this.onsuccess = CurrentTransChecker("deleting.onsuccess", transaction); + } + db$8.users.hook.creating.subscribe(onCreating); + db$8.users.hook.reading.subscribe(onReading); + db$8.users.hook.updating.subscribe(onUpdating); + db$8.users.hook.deleting.subscribe(onDeleting); + function doTheTests() { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.users.add({ username: "monkey1" })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$8.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$8.users.bulkAdd([{ username: "monkey1" }, { username: "monkey2" }]) + .then(function () { return QUnit.ok(false, "Should get error on one of the adds"); }) + .catch(Dexie__default["default"].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$8.users.where("username").equals("monkey1").modify({ + name: "Monkey 1" + })]; + case 4: + _a.sent(); + return [4 /*yield*/, db$8.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 to an already existing primary key"); + })]; + case 5: + _a.sent(); + QUnit.ok(true, "Will now be modifying primary key of monkey1..."); + return [4 /*yield*/, db$8.users.where("username").equals("monkey1").modify(function (user) { + user.username = "monkey88"; // trigger updating.onerror + }).then(function (res) { + QUnit.ok(true, "Should succeed modifying primary key to non-existing primary key, resulting in deletion and creation: " + res); + }).catch(function (ex) { + QUnit.ok(false, "Should succeed modifying primary key to non-existing primary key, resulting in deletion and creation: " + ex); + })]; + case 6: + _a.sent(); + QUnit.ok(true, "Will now modify monkey88 back to monkey1 again..."); + return [4 /*yield*/, db$8.users.where({ username: "monkey88" }).modify({ username: "monkey1" })]; + case 7: + _a.sent(); + return [4 /*yield*/, db$8.users.toArray()]; + case 8: + _a.sent(); + return [4 /*yield*/, db$8.users.delete("monkey2")]; + case 9: + _a.sent(); + return [4 /*yield*/, db$8.users.delete("monkey1")]; + case 10: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + } + doTheTests().then(function () { + var _this = this; + QUnit.ok(true, "Now in an explicit transaction block..."); + return db$8.transaction('rw', db$8.users, function () { return __awaiter(_this, void 0, void 0, function () { + return __generator(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$8.users.hook.creating.unsubscribe(onCreating); + db$8.users.hook.reading.unsubscribe(onReading); + db$8.users.hook.updating.unsubscribe(onUpdating); + db$8.users.hook.deleting.unsubscribe(onDeleting); + QUnit.start(); + }); + }); + function sleep(ms) { + return new Promise(function (resolve) { return setTimeout(resolve, ms); }); + } + promisedTest("waitFor()", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.transaction('rw', db$8.users, function (trans) { return __awaiter(void 0, void 0, void 0, function () { + var result; + return __generator(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:".concat(trans._spinCount)); + // With timeout + return [4 /*yield*/, Dexie__default["default"].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__default["default"].waitFor(function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Dexie__default["default"].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__default["default"].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:".concat(trans._spinCount)); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Zone info should still be correct"); + // Subtransaction + return [4 /*yield*/, db$8.transaction('r', db$8.users, function (subTrans) { + var count; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(subTrans !== trans, "Should be in a sub transaction"); + QUnit.ok(Dexie__default["default"].currentTransaction === subTrans, "Should be in a sub transaction"); + return [4 /*yield*/, trans.users.count()]; + case 1: + count = _a.sent(); + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + return [4 /*yield*/, subTrans.waitFor(sleep(10))]; + case 2: + _a.sent(); + QUnit.ok(true, "Should be able to call waitFor() on sub transaction"); + return [4 /*yield*/, trans.users.count()]; + case 3: + count = _a.sent(); + QUnit.ok(true, "Should be able to operate on sub transaction. User count = " + count); + return [2 /*return*/]; + } + }); + })]; + case 8: + // Subtransaction + _a.sent(); + // Calling waitFor multiple times in parallell + return [4 /*yield*/, Promise.all([ + trans.waitFor(sleep(10)), + trans.waitFor(sleep(10)), + trans.waitFor(sleep(10)) + ])]; + case 9: + // Calling waitFor multiple times in parallell + _a.sent(); + QUnit.ok(true, "Could wait for several tasks in parallell"); + return [4 /*yield*/, trans.users.get("testingtesting")]; + case 10: + result = _a.sent(); + QUnit.ok(result && result.username === "testingtesting", "Should still be able to operate on the transaction"); + return [2 /*return*/]; + } + }); + }); }).then(function () { return QUnit.ok(true, "Transaction committed"); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Dexie.waitFor() outside transaction", function () { return __awaiter(void 0, void 0, void 0, function () { + var result, codeExecuted; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].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__default["default"].waitFor(function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(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(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$8.transaction('r', db$8.users, function () { return __awaiter(void 0, void 0, void 0, function () { + var err_1; + return __generator(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__default["default"].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(void 0, void 0, void 0, function () { + var resolve, reject, p, log; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + p = new Promise(function (res, rej) { resolve = res; reject = rej; }); + log = []; + return [4 /*yield*/, db$8.transaction('r', db$8.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__default["default"].ignoreTransaction(function () { + return new Dexie__default["default"].Promise(function (resolve) { return setTimeout(resolve, 50); }).then(function () { + return db$8.pets.put({ kind: "dog" }); + }).then(function () { + return db$8.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: ".concat(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__default["default"].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(void 0, void 0, void 0, function () { + var resolve, reject, p, log; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + p = new Promise(function (res, rej) { resolve = res; reject = rej; }); + log = []; + return [4 /*yield*/, db$8.transaction('r', db$8.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$8.transaction('rw!', db$8.pets, function () { + return db$8.pets.put({ kind: "dog" }).then(function () { + return db$8.pets.count(); + }).then(function (numPets) { + QUnit.ok(true, "num pets: ".concat(numPets)); + }).then(function () { + return Dexie__default["default"].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*/]; + } + }); + }); }); + QUnit.asyncTest("abort will rollback previous writes", function () { + db$8.transaction('rw', db$8.users, function () { + db$8.users.add({ username: "james", color: "red" }); + Dexie__default["default"].currentTransaction.abort(); + }).catch(function () { + QUnit.ok(true, "transaction done"); + }).then(function () { + return db$8.users.get('james'); + }).then(function (user) { + QUnit.ok(user == null, "should not written if transaction aborted"); + }) + .finally(QUnit.start); + }); + + var async$3 = Dexie__default["default"].async; + QUnit.module("open", { + setup: function () { + QUnit.stop(); + Dexie__default["default"].delete("TestDB").then(function () { + QUnit.start(); + }).catch(function (e) { + QUnit.ok(false, "Could not delete database"); + }); + }, + teardown: function () { + QUnit.stop(); + Dexie__default["default"].delete("TestDB").then(QUnit.start); + } + }); + var timeout = async$3(function (promise, ms) { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.race([promise, new Promise(function (resolve, reject) { return setTimeout(function () { return reject("timeout"); }, ms); })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("multiple db should not block each other", function () { + var db1, db2, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("versionchange")) { + QUnit.ok(true, "SKIPPED - versionchange UNSUPPORTED"); + return [2 /*return*/]; + } + db1 = new Dexie__default["default"]("TestDB"), db2 = new Dexie__default["default"]("TestDB"); + db1.version(1).stores({ + foo: 'bar' + }); + db2.version(1).stores({ + foo: 'bar' + }); + return [4 /*yield*/, db1.open()]; + case 1: + _a.sent(); + QUnit.ok(true, "db1 should open"); + return [4 /*yield*/, db2.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "db2 should open"); + _a.label = 3; + case 3: + _a.trys.push([3, 5, , 6]); + return [4 /*yield*/, timeout(db1.delete(), 1500)]; + case 4: + _a.sent(); + QUnit.ok(true, "Succeeded to delete db1 while db2 was open"); + return [3 /*break*/, 6]; + case 5: + e_1 = _a.sent(); + db1.close(); + db2.close(); + QUnit.ok(false, "Could not delete db1 - " + e_1); + return [3 /*break*/, 6]; + case 6: return [2 /*return*/]; + } + }); + }); + spawnedTest("Using db on node should be rejected with MissingAPIError", function () { + var db, e_2, e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie__default["default"]('TestDB', { + indexedDB: undefined, + IDBKeyRange: undefined + }); + db.version(1).stores({ foo: 'bar' }); + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, db.foo.toArray()]; + case 2: + _a.sent(); + QUnit.ok(false, "Should not get any result because API is missing."); + return [3 /*break*/, 4]; + case 3: + e_2 = _a.sent(); + QUnit.ok(e_2 instanceof Dexie__default["default"].MissingAPIError, "Should get MissingAPIError. Got: " + e_2.name); + return [3 /*break*/, 4]; + case 4: + _a.trys.push([4, 6, , 7]); + return [4 /*yield*/, db.open()]; + case 5: + _a.sent(); + return [3 /*break*/, 7]; + case 6: + e_3 = _a.sent(); + QUnit.ok(e_3 instanceof Dexie__default["default"].MissingAPIError, "Should get MissingAPIError. Got: " + e_3.name); + return [3 /*break*/, 7]; + case 7: return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("open, add and query data without transaction", 6, function () { + var db = new Dexie__default["default"]("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__default["default"]("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__default["default"]("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__default["default"].NoSuchDatabaseError, function (err) { + // An error happened. Database did not exist. + QUnit.ok(true, "Database did not exist"); + db = new Dexie__default["default"]("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__default["default"]("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__default["default"].Observable ? 1 : 10, function () { + if (Dexie__default["default"].Observable) { + QUnit.ok(true, "Dexie.Observable currently not compatible with this mode"); + return QUnit.start(); + } + var db = new Dexie__default["default"]("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__default["default"]("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__default["default"]("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__default["default"].getDatabaseNames(function (names) { + defaultDatabases = [].slice.call(names, 0); + QUnit.ok(true, "Current databases: " + (defaultDatabases.length ? defaultDatabases.join(',') : "(none)")); + db1 = new Dexie__default["default"]("TestDB1"); + db1.version(1).stores({}); + return db1.open(); + }).then(function () { + // One DB created + QUnit.ok(true, "TestDB1 successfully created"); + return Dexie__default["default"].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__default["default"]("TestDB2"); + db2.version(1).stores({}); + return db2.open(); + }).then(function () { + QUnit.ok(true, "TestDB2 successfully created"); + return Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].exists("nonexistingDB"); + }).then(function (exists) { + QUnit.ok(!exists, "'nonexistingDB' should not exist indeed"); + return Dexie__default["default"].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__default["default"].Promise.resolve()).finally(function () { + (db2 ? db2.delete() : Dexie__default["default"].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 if (!self.Promise) self.Promise = Dexie.Promise;\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__default["default"]("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__default["default"].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__default["default"]("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__default["default"].exists("TestDB").then(function (result) { + QUnit.equal(result, false, "Should not exist yet"); + db = new Dexie__default["default"]("TestDB"); + db.version(1).stores({ + some: "schema" + }); + return db.open(); + }).then(function () { + return Dexie__default["default"].exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should exist now and has another open connection."); + db.close(); + return Dexie__default["default"].exists("TestDB"); + }).then(function (result) { + QUnit.equal(result, true, "Should still exist"); + return Dexie__default["default"].delete("TestDB"); + }).then(function () { + return Dexie__default["default"].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__default["default"]("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__default["default"].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__default["default"].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__default["default"].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__default["default"]("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__default["default"].DatabaseClosedError, "Should catch DatabaseClosedError"); + return db.open(); + }).then(function () { + console.log("The call to db.open() completed"); + return db.foo.toArray(); + }).then(function (res) { + QUnit.equal(res.length, 0, "Database re-opened and I got a result from my query"); + }).catch(function (e) { + QUnit.ok(false, e); + }).finally(function () { + db.delete().catch(function (e) { return console.error(e); }).finally(QUnit.start); + }); + }); + spawnedTest("db.open several times", 2, function () { + var db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie__default["default"]("TestDB"); + db.version(1).stores({ foo: "id" }); + db.on('populate', function () { throw "Failed in populate"; }); + db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + }); + return [4 /*yield*/, db.open().then(function () { + QUnit.ok(false, "Should not succeed to open"); + }).catch(function (err) { + QUnit.ok(true, "Got error: " + (err.stack || err)); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("#306 db.on('ready') subscriber should be called also if db is already open", function () { + var db = new Dexie__default["default"]("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(void 0, void 0, void 0, function () { + var db, first, second, third; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie__default["default"]('TestDB'); + db.version(1).stores({ foobar: 'id' }); + first = false, second = false, third = false; + // first is registered before open + db.on('ready', function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(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__default["default"].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*/]; + } + }); + }); }); + promisedTest("Should be possible to open a vip DB", function () { return __awaiter(void 0, void 0, void 0, function () { + var db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].delete('TestDB')]; + case 1: + _a.sent(); + db = new Dexie__default["default"]('TestDB'); + db.version(1).stores({ foobar: 'id' }); + return [4 /*yield*/, db.vip.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "Could open viped db"); + return [4 /*yield*/, db.vip.foobar.toArray()]; + case 3: + _a.sent(); + QUnit.ok(true, "Could query viped db"); + return [4 /*yield*/, db.foobar.toArray()]; + case 4: + _a.sent(); + QUnit.ok(true, "Could query non-viped db after opening it through vip mode"); + db.vip.close(); + // Try testing it dynamically + db = new Dexie__default["default"]('TestDB'); + return [4 /*yield*/, db.vip.open()]; + case 5: + _a.sent(); + QUnit.ok(true, "Could open viped db dynamically"); + return [4 /*yield*/, db.vip.table('foobar').toArray()]; + case 6: + _a.sent(); + QUnit.ok(true, "Could query dynamically opened viped db"); + return [2 /*return*/]; + } + }); + }); }); + + var db$7 = new Dexie__default["default"]("TestYieldDb"); + var async$2 = Dexie__default["default"].async; + var spawn = Dexie__default["default"].spawn; + db$7.version(1).stores({ + friends: '++id,name,*groups', + pets: '++id,name' + }); + QUnit.module("yield", { + setup: function () { + QUnit.stop(); + resetDatabase(db$7).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + QUnit.asyncTest("db.transaction() with yield", async$2(function () { + var finallyWasReached, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + finallyWasReached = false; + _a.label = 1; + case 1: + _a.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, db$7.transaction('rw', 'friends', 'pets', function () { + var catId, dogId, gurra, gurrasPets; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.pets.add({ name: "Tito", kind: "cat" })]; + case 1: + catId = _a.sent(); + return [4 /*yield*/, db$7.pets.add({ name: "Josephina", kind: "dog" })]; + case 2: + dogId = _a.sent(); + // Add a friend who owns the pets + db$7.friends.add({ name: "Gurra G", pets: [catId, dogId] }); + return [4 /*yield*/, db$7.friends.where('name').equals("Gurra G").first()]; + case 3: + gurra = _a.sent(); + QUnit.ok(!!gurra, "Gurra could be found with yield"); + return [4 /*yield*/, db$7.pets.where('id').anyOf(gurra.pets).toArray()]; + case 4: + gurrasPets = _a.sent(); + QUnit.equal(gurrasPets.length, 2, "Gurras all two pets could be retrieved via yield"); + QUnit.equal(gurrasPets[0].kind, "cat", "Gurras first pet is a cat"); + QUnit.equal(gurrasPets[1].kind, "dog", "Gurras second pet is a dog"); + return [2 /*return*/]; + } + }); + })]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: + e_1 = _a.sent(); + QUnit.ok(false, "Caught error: " + e_1); + return [3 /*break*/, 5]; + case 4: + finallyWasReached = true; + return [7 /*endfinally*/]; + case 5: + QUnit.ok(finallyWasReached, "finally was reached"); + QUnit.start(); + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Catching indexedDB error event", 2, async$2(function () { + var e_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 4]; + case 3: + e_2 = _a.sent(); + QUnit.equal(e_2.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + return [3 /*break*/, 4]; + case 4: + QUnit.start(); + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Catching error prevents transaction from aborting", 5, async$2(function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, , 4, 5]); + return [4 /*yield*/, db$7.transaction('rw', 'pets', function () { + var e_3; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 4]; + case 3: + e_3 = _a.sent(); + QUnit.equal(e_3.name, "ConstraintError", "Caught indexedDB DOMError event ConstraintError"); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + })]; + case 1: + _c.sent(); + QUnit.ok(true, "Should come here - transaction committed because we caught the error"); + _a = QUnit.ok; + return [4 /*yield*/, db$7.pets.get(1)]; + case 2: + _a.apply(void 0, [(_c.sent()), "A pet with ID 1 exists in DB"]); + _b = QUnit.equal; + return [4 /*yield*/, db$7.pets.get(1)]; + case 3: + _b.apply(void 0, [(_c.sent()).name, "Tidi", "It was Tidi in the first position"]); + return [3 /*break*/, 5]; + case 4: + QUnit.start(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Transaction not committing when not catching error event", 4, async$2(function () { + var e_4, _a; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, 4, 5]); + return [4 /*yield*/, db$7.transaction('rw', 'pets', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Tidi", kind: "Honeybadger" })]; + case 1: + _a.sent(); + QUnit.ok(true, "Should come so far"); + return [4 /*yield*/, db$7.pets.add({ id: 1, name: "Todoo", kind: "Snake" })]; + case 2: + _a.sent(); // Should generate an IDB error event! + QUnit.ok(false, "Should not come here"); + return [2 /*return*/]; + } + }); + })]; + case 1: + _b.sent(); + QUnit.ok(false, "Should not come here"); + return [3 /*break*/, 5]; + case 2: + e_4 = _b.sent(); + QUnit.ok(true, "Transaction should fail"); + QUnit.equal(e_4.name, "ConstraintError", "Error caught was a ConstraintError!"); + _a = QUnit.equal; + return [4 /*yield*/, db$7.pets.count()]; + case 3: + _a.apply(void 0, [(_b.sent()), 0, "Pets table should still be empty because transaction failed"]); + return [3 /*break*/, 5]; + case 4: + QUnit.start(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding a non-promise", async$2(function () { + var x; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, 3]; + case 1: + x = _a.sent(); + QUnit.equal(x, 3, "Could yield a non-promise"); + return [3 /*break*/, 4]; + case 2: + _a.sent(); + QUnit.ok(false, "Yielding a non-Thenable wasn't be allowed"); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an array with a mix of values and thenables", async$2(function () { + var results; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, Dexie__default["default"].Promise.resolve(3)]]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return [3 /*break*/, 4]; + case 2: + _a.sent(); + QUnit.ok(false, "Got exception when trying to do yield an array of mixed values/promises"); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an array of non-promises only", async$2(function () { + var results, e_7; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, [1, 2, 3]]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return [3 /*break*/, 4]; + case 2: + e_7 = _a.sent(); + QUnit.ok(false, e_7); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an empty array", async$2(function () { + var results, e_8; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, []]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 0, "Yielded array is of size 0"); + return [3 /*break*/, 4]; + case 2: + e_8 = _a.sent(); + QUnit.ok(false, e_8); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Should allow yielding an array of different kind of any kind of promise", function () { + spawn(function () { + var results; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, [Promise.resolve(1), Dexie__default["default"].Promise.resolve(2), Promise.resolve(3)]]; + case 1: + results = _a.sent(); + QUnit.equal(results.length, 3, "Yielded array is of size 3"); + QUnit.equal(results[0], 1, "First value is 1"); + QUnit.equal(results[1], 2, "Second value is 2"); + QUnit.equal(results[2], 3, "Third value is 3"); + return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Throw after yield 1", function () { + spawn(function () { + var e_9; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, Promise.resolve(3)]; + case 1: + _a.sent(); + QUnit.ok(true, "yielded a value"); + throw "error"; + case 2: + e_9 = _a.sent(); + QUnit.ok(e_9 === "error", "Catched exception: " + e_9); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Throw after yield 2", function () { + Promise.resolve(spawn(function () { + var e_10; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, 3]; + case 1: + _a.sent(); + QUnit.ok(true, "yielded a value"); + throw "error"; + case 2: + e_10 = _a.sent(); + QUnit.ok(e_10 === "error", "Catched exception: " + e_10); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 4]; + } + }); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Throw before yield", function () { + Promise.resolve(spawn(function () { + return __generator(this, function (_a) { + try { + throw "error"; + } + catch (e) { + QUnit.ok(e === "error", "Catched exception: " + e); + } + return [2 /*return*/, 4]; + }); + })).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Catch rejected promise", function () { + spawn(function () { + var e_11; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, new Promise(function (resolve, reject) { reject("fault fault!"); })]; + case 1: + _a.sent(); + QUnit.ok(false, "Shouldn't come here"); + return [3 /*break*/, 3]; + case 2: + e_11 = _a.sent(); + QUnit.ok(e_11 === "fault fault!", "Catched exception: " + e_11); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Catch rejected promise in an array", function () { + spawn(function () { + var e_12; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, [1, 2, new Promise(function (resolve, reject) { reject("fault fault!"); }), 4]]; + case 1: + _a.sent(); + QUnit.ok(false, "Shouldn't come here"); + return [3 /*break*/, 3]; + case 2: + e_12 = _a.sent(); + QUnit.ok(e_12 === "fault fault!", "Catched exception: " + e_12); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, 4]; + } + }); + }).then(function (x) { + QUnit.equal(x, 4, "Finally got the value 4"); + }).catch(function (e) { + QUnit.ok(false, "Something is rotten in the state of Denmark: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Should allow returning a promise", function () { + spawn(function () { + return __generator(this, function (_a) { + return [2 /*return*/, Promise.resolve(3)]; + }); + }).then(function (result) { + QUnit.equal(result, 3, "Returning a directly should also be allowed"); + }).catch(function (e) { + QUnit.ok(false, e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Should be able to do 'return yield Promise.resolve(x);'", function () { + spawn(function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve(3)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }).then(function () { + QUnit.ok(true, "Should be able to do 'return yield Promise.resolve(x);'"); + }).catch(function (e) { + QUnit.ok(false, "Error occurred: " + e); + }).then(QUnit.start); + }); + QUnit.asyncTest("Arrow functions and let", async$2(function () { + var x, y; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, [1, 2, Promise.resolve(3)]]; + case 1: + x = _a.sent(); + y = x.map(function (a) { return a - 1; }); + QUnit.equal(y[0], 0); + QUnit.equal(y[1], 1); + QUnit.equal(y[2], 2); + QUnit.start(); + return [2 /*return*/]; + } + }); + })); + QUnit.asyncTest("Calling sub async function", async$2(function () { + var addFriend, deleteFriends, foo, bar, numDeleted, e_13; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + addFriend = async$2(function addFriend(friend) { + var friendId; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.friends.add(friend)]; + case 1: + friendId = _a.sent(); + return [4 /*yield*/, db$7.friends.get(friendId)]; + case 2: return [2 /*return*/, _a.sent()]; + } + }); + }); + deleteFriends = async$2(function deleteFriends() { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$7.friends.where('name').anyOf("Foo", "Bar").delete()]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); + _a.label = 1; + case 1: + _a.trys.push([1, 5, 6, 7]); + return [4 /*yield*/, addFriend({ name: "Foo" })]; + case 2: + foo = _a.sent(); + return [4 /*yield*/, addFriend({ name: "Bar" })]; + case 3: + bar = _a.sent(); + QUnit.ok(foo.name == "Foo", "Foo got its name"); + QUnit.ok(bar.name == "Bar", "Bar got its name"); + return [4 /*yield*/, deleteFriends()]; + case 4: + numDeleted = _a.sent(); + QUnit.ok(true, numDeleted + " friends successfully deleted"); + return [3 /*break*/, 7]; + case 5: + e_13 = _a.sent(); + QUnit.ok(false, e_13); + return [3 /*break*/, 7]; + case 6: + QUnit.start(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + })); + + var _global = typeof globalThis !== 'undefined' ? globalThis : + typeof self !== 'undefined' ? self : + typeof window !== 'undefined' ? window : + global; + + var keys = Object.keys; + var isArray$1 = Array.isArray; + if (typeof Promise !== 'undefined' && !_global.Promise) { + // In jsdom, this it can be the case that Promise is not put on the global object. + // If so, we need to patch the global object for the rest of the code to work as expected. + // Other dexie code expects Promise to be on the global object (like normal browser environments) + _global.Promise = Promise; + } + 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)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(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); + var proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); + } + 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 intrinsicTypeNames = "Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey" + .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]; }); + var intrinsicTypes = new Set(intrinsicTypeNames.map(function (t) { return _global[t]; })); + var circularRefs = null; + /** Deep clone an object or array. + * + * + * @param any + * @returns + */ + function deepClone(any) { + circularRefs = new WeakMap(); + var rv = innerDeepClone(any); + circularRefs = null; + return rv; + } + function innerDeepClone(x) { + if (!x || typeof x !== 'object') + return x; + var rv = circularRefs.get(x); // Resolve circular references + if (rv) + return rv; + if (isArray$1(x)) { + rv = []; + circularRefs.set(x, rv); + for (var i = 0, l = x.length; i < l; ++i) { + rv.push(innerDeepClone(x[i])); + } + } + else if (intrinsicTypes.has(x.constructor)) { + // For performance, we're less strict than structuredClone - we're only + // cloning arrays and custom objects. + // Typed arrays, Dates etc are not cloned. + rv = x; + } + else { + // We're nicer to custom classes than what structuredClone() is - + // we preserve the proto of each object. + var proto = getProto(x); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs.set(x, rv); + for (var prop in x) { + if (hasOwn(x, prop)) { + rv[prop] = innerDeepClone(x[prop]); + } + } + } + return rv; + } + var toString = {}.toString; + function toStringTag(o) { + return toString.call(o).slice(8, -1); + } + // If first argument is iterable or array-like, return it as an array + var iteratorSymbol = typeof Symbol !== 'undefined' ? + Symbol.iterator : + '@@iterator'; + var getIteratorOf = typeof iteratorSymbol === "symbol" ? 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$1(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$1() { } + function mirror(val) { return val; } + function callBoth(on1, on2) { + return function () { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; + } + + // By default, debug will be true only if platform is a web platform and its page is served from localhost. + // When debug = true, error's stacks will contain asyncronic long stacks. + var debug = typeof location !== 'undefined' && + // By default, use debug mode if served from localhost. + /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); + var libraryFilter = function () { return true; }; + var NEEDS_THROW_FOR_STACK = !new Error("").stack; + function getErrorWithStack() { + 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", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" + }; + // + // 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: " + Object.keys(failures) + .map(function (key) { return failures[key].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; + this.message = getMultiErrorMessage(msg, failures); + } + derive(ModifyError).from(DexieError); + function BulkError(msg, failures) { + this._e = getErrorWithStack(); + this.name = "BulkError"; + this.failures = Object.keys(failures).map(function (pos) { return failures[pos]; }); + this.failuresByPos = failures; + this.message = getMultiErrorMessage(msg, this.failures); + } + derive(BulkError).from(DexieError); + // + // + // Dynamically generate error names and exception classes based + // on the names in errorList. + // + // + // Map of {ErrorName -> ErrorName + "Error"} + 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 = "".concat(msgOrInner).concat(!inner ? '' : '\n ' + inner); + this.inner = inner || null; + } + else if (typeof msgOrInner === 'object') { + this.message = "".concat(msgOrInner.name, " ").concat(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; + idbDomErrorNames.reduce(function (obj, name) { + obj[name + "Error"] = exceptions[name]; + return obj; + }, {}); + var fullNameExceptions = errorList.reduce(function (obj, name) { + if (["Syntax", "Type", "Range"].indexOf(name) === -1) + obj[name + "Error"] = exceptions[name]; + return obj; + }, {}); + fullNameExceptions.ModifyError = ModifyError; + fullNameExceptions.DexieError = DexieError; + fullNameExceptions.BulkError = BulkError; + + /* + * Copyright (c) 2014-2017 David Fahlander + * Apache License Version 2.0, January 2004, http://www.apache.org/licenses/LICENSE-2.0 + */ + // + // Promise and Zone (PSD) for Dexie library + // + // I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by + // https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation. + // + // In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another + // tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use + // another strategy now that simplifies everything a lot: to always execute callbacks in a new micro-task, but have an own micro-task + // engine that is indexedDB compliant across all browsers. + // Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible. + // Also with inspiration from bluebird, asyncronic stacks in debug mode. + // + // Specific non-standard features of this Promise class: + // * Custom zone support (a.k.a. PSD) with ability to keep zones also when using native promises as well as + // native async / await. + // * Promise.follow() method built upon the custom zone engine, that allows user to track all promises created from current stack frame + // and below + all promises that those promises creates or awaits. + // * Detect any unhandled promise in a PSD-scope (PSD.onunhandled). + // + // David Fahlander, https://github.com/dfahlander + // + // Just a pointer that only this module knows about. + // Used in Promise constructor to emulate a private constructor. + var INTERNAL = {}; + // Async stacks (long stacks) must not grow infinitely. + var LONG_STACKS_CLIP_LIMIT = 100, + // When calling error.stack or promise.stack, limit the number of asyncronic stacks to print out. + MAX_LONG_STACKS = 20, ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === 'undefined' ? + [] : + (function () { + var globalP = Promise.resolve(); + if (typeof crypto === 'undefined' || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + // Generate a native promise (as window.Promise may have been patched) + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [ + nativeP, + getProto(nativeP), + globalP + ]; + })(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; + var NativePromise$1 = 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. + */ + function schedulePhysicalTick() { + queueMicrotask(physicalTick); + } + // 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 = function (callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } + }; + var isOutsideMicroTick = true, // True when NOT in a virtual microTick. + needsNewPhysicalTick = true, // True when a push to microtickQueue must also schedulePhysicalTick() + unhandledErrors = [], // Rejected promises that has occured. Used for triggering 'unhandledrejection'. + rejectingErrors = [], // Tracks if errors are being re-rejected during onRejected callback. + currentFulfiller = null, rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions + var globalPSD = { + id: 'global', + global: true, + ref: 0, + unhandleds: [], + onunhandled: nop$1, + pgp: false, + env: {}, + finalize: nop$1 + }; + var PSD = globalPSD; + var microtickQueue = []; // Callbacks to call in this or next physical tick. + var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick. + var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick. + function DexiePromise(fn) { + if (typeof this !== 'object') + throw new TypeError('Promises must be constructed via new'); + this._listeners = []; + // 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); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function (resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); + }); + debug && linkToPreviousPromise(rv, this); + return rv; + } + then.prototype = INTERNAL; // For idempotense, see setter below. + return then; + }, + // Be idempotent and allow another framework (such as zone.js or another instance of a Dexie.Promise module) to replace Promise.prototype.then + // and when that framework wants to restore the original property, we must identify that and restore the original property descriptor. + set: function (value) { + setProp(this, 'then', value && value.prototype === INTERNAL ? + thenProp : // Restore to original property descriptor. + { + get: function () { + return value; // Getter returning provided value (behaves like value is just changed) + }, + set: thenProp.set // Keep a setter that is prepared to restore original. + }); + } + }; + props(DexiePromise.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 DexiePromise(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(DexiePromise.prototype, Symbol.toStringTag, 'Dexie.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(DexiePromise, { + all: function () { + var values = getArrayOf.apply(null, arguments) // Supports iterables, implicit arguments and array-like. + .map(onPossibleParallellAsync); // Handle parallell async/awaits + return new DexiePromise(function (resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function (a, i) { return DexiePromise.resolve(a).then(function (x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); }); + }); + }, + resolve: function (value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === 'function') + return new DexiePromise(function (resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + linkToPreviousPromise(rv, currentFulfiller); + return rv; + }, + reject: PromiseReject, + race: function () { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + values.map(function (value) { return DexiePromise.resolve(value).then(resolve, reject); }); + }); + }, + PSD: { + get: function () { return PSD; }, + set: function (value) { return PSD = value; } + }, + totalEchoes: { get: function () { return totalEchoes; } }, + //task: {get: ()=>task}, + newPSD: newScope, + usePSD: usePSD, + scheduler: { + get: function () { return asap; }, + set: function (value) { asap = value; } + }, + rejectionMapper: { + get: function () { return rejectionMapper; }, + set: function (value) { rejectionMapper = value; } // Map reject failures + }, + follow: function (fn, zoneProps) { + return new DexiePromise(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); + }); + } + }); + if (NativePromise$1) { + if (NativePromise$1.allSettled) + setProp(DexiePromise, "allSettled", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return results[i] = { status: "fulfilled", value: value }; }, function (reason) { return results[i] = { status: "rejected", reason: reason }; }) + .then(function () { return --remaining || resolve(results); }); }); + }); + }); + if (NativePromise$1.any && typeof AggregateError !== 'undefined') + setProp(DexiePromise, "any", function () { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function (resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function (p, i) { return DexiePromise.resolve(p).then(function (value) { return resolve(value); }, function (failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); }); + }); + }); + } + /** + * 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 DexiePromise ? + 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(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(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) { // Prohibit infinite Promise loops to get an infinite long memory consuming "tail". + promise._prev = prev; + promise._numPrev = numPrev; + } + } + /* The callback to schedule with queueMicrotask(). + It runs a virtual microtick and executes any callback registered in microtickQueue. + */ + function physicalTick() { + usePSD(globalPSD, function () { + // Make sure to reset the async context to globalPSD before + // executing any of the microtick subscribers. + 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(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 DexiePromise(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, 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: DexiePromise, + PromiseProp: { value: DexiePromise, configurable: true, writable: true }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject, + nthen: getPatchedPromiseThen(globalEnv.nthen, psd), + gthen: getPatchedPromiseThen(globalEnv.gthen, psd) // global then + } : {}; + if (props) + extend(psd, props); + // 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() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; // Will reset echoes to 0 if awaits is 0. + return true; + } + if (('' + nativePromiseThen).indexOf('[native code]') === -1) { + // If the native promise' prototype is patched, we cannot rely on zone echoing. + // Disable that here: + incrementExpectedAwaits = decrementExpectedAwaits = nop$1; + } + // Call from Promise.all() and Promise.race() + function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise$1) { + incrementExpectedAwaits(); + return possiblePromise.then(function (x) { + decrementExpectedAwaits(); + return x; + }, function (e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; + } + function zoneEnterEcho(targetZone) { + ++totalEchoes; + //console.log("Total echoes ", 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. + queueMicrotask(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_1 = 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_1.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_1.all = targetEnv.all; + GlobalPromise_1.race = targetEnv.race; + GlobalPromise_1.resolve = targetEnv.resolve; + GlobalPromise_1.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise_1.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise_1.any = targetEnv.any; + } + } + } + function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + 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 nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { + 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); + if (cleanup) + queueMicrotask(decrementExpectedAwaits); + } + }; + } + function getPatchedPromiseThen(origThen, zone) { + return function (onResolved, onRejected) { + return origThen.call(this, nativeAwaitCompatibleWrap(onResolved, zone), nativeAwaitCompatibleWrap(onRejected, zone)); + }; + } + var rejection = DexiePromise.reject; + + var _resolve = NativePromise$1.resolve.bind(NativePromise$1); + var _then = NativePromise$1.prototype.then; + var IdbPromiseIncompatibleError = /** @class */ (function (_super) { + __extends$1(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(this, void 0, void 0, function () { + var db; + var _this = this; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + db = new Dexie__default["default"]("idbPromiseCompatTest"); + db.version(1).stores({ foo: 'bar' }); + return [4 /*yield*/, db.delete()]; + case 1: + _a.sent(); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + return [4 /*yield*/, db.transaction('r', db.foo, function () { return __awaiter(_this, void 0, void 0, function () { + var p, i, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db.foo.count()]; + case 1: + _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: + _a.sent(); + db.close(); + throw new IdbPromiseIncompatibleError(); + case 6: return [2 /*return*/]; + } + }); + }); })]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + } + + var idbAndPromiseCompatible; + var hasNativeAsyncFunctions = false; + try { + hasNativeAsyncFunctions = !!new Function("return (async ()=>{})();")().then; + } + catch (e) { } + var db$6 = new Dexie__default["default"]("TestDBTranx"); + db$6.version(1).stores({ + items: "id" + }); + QUnit.module("asyncawait", { + setup: function (assert) { + // Execute this promise when needed: + if (idbAndPromiseCompatible === undefined) { + // Initialize this promise. + idbAndPromiseCompatible = isIdbAndPromiseCompatible(); + } + var done = assert.async(); + resetDatabase(db$6).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$6.transaction('rw', db$6.items, function (trans) { + return window.Promise.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$6.items.add({ id: "foobar" }); + }).then(function () { + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == trans, "Transaction scopes should persist through Promise.resolve()"); + return db$6.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: ".concat(e.stack || e)); + }).finally(done); + }); + QUnit.test("Should be able to use native async await", function (assert) { + var done = assert.async(); + Dexie__default["default"].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__default["default"], db$6); + }).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: ".concat(e.stack || e)); + else + QUnit.ok(true, "This browser does not support native async functions"); + }).then(done); + }); + QUnit.test("Should be able to use native async await from upgrade handler (issue #612)", function (assert) { + var done = assert.async(); + Dexie__default["default"].Promise.resolve(idbAndPromiseCompatible).then(function () { + var f = new Function('ok', 'equal', 'Dexie', "\n return Dexie.delete('issue612').then(async ()=>{\n const log = [];\n const db = new Dexie('issue612');\n db.version(1).stores({foo: 'id'});\n await db.open();\n await db.foo.add({id: 1, name: \"Foo Bar\"});\n db.close();\n db.version(2).stores({foo: 'id, firstName, lastName'}).upgrade(async tx => {\n log.push(\"2:1\");\n await tx.foo.toCollection().modify(x => {\n const [firstName, lastName] = x.name.split(' ');\n x.firstName = firstName;\n x.lastName = lastName;\n ++x.v\n });\n log.push(\"2:2\");\n });\n db.version(3).upgrade(async tx => {\n log.push(\"3:1\");\n await tx.foo.toArray();\n log.push(\"3:2\");\n });\n await db.open();\n const count = await db.foo.where({firstName: 'Foo'}).count();\n equal(count, 1, \"Should find base on the upgraded index\");\n equal(log.join(','), \"2:1,2:2,3:1,3:2\", \"Execution order of upgraders should be correct\");\n db.close();\n });"); + return f(QUnit.ok, QUnit.equal, Dexie__default["default"]); + }).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: ".concat(e.stack || e)); + else + QUnit.ok(true, "This browser does not support native async functions"); + }).then(function () { + return Dexie__default["default"].delete("issue612"); + }).then(done); + }); + var NativePromise = (function () { + try { + return new Function("return (async ()=>{})().constructor")(); + } + catch (e) { + return window.Promise; + } + })(); + QUnit.test("Must not leak PSD zone", function (assert) { + return __awaiter(this, void 0, void 0, function () { + var done, compatiblity, F; + return __generator(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__default["default"], db$6).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(this, void 0, void 0, function () { + var done; + return __generator(this, function (_a) { + done = assert.async(); + QUnit.ok(Dexie__default["default"].currentTransaction === null, "Should not have an ongoing transaction to start with"); + db$6.transaction('rw', db$6.items, function () { + var trans = Dexie__default["default"].currentTransaction; + QUnit.ok(trans !== null, "Should have a current transaction"); + var otherZonePromise; + Dexie__default["default"].ignoreTransaction(function () { + QUnit.ok(Dexie__default["default"].currentTransaction == null, "No Transaction in this zone"); + function promiseFlow() { + return NativePromise.resolve().then(function () { + if (Dexie__default["default"].currentTransaction !== null) + QUnit.ok(false, "PSD zone leaked"); + return new NativePromise(function (resolve) { return NativePromise.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$6.items.get(1).then(function () { + return idbAndPromiseCompatible; + }).then(function () { + QUnit.ok(Dexie__default["default"].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__default["default"], trans, NativePromise, db$6); + }).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: ".concat(e.stack || e)); + else + QUnit.ok(true, "This browser does not support native async functions"); + }).then(function () { + // NativePromise + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still same transaction 2"); + return Promise.resolve(); + }).then(function () { + // window.Promise + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still same transaction 3"); + return Dexie__default["default"].Promise.resolve(); + }).then(function () { + // Dexie.Promise + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still same transaction 4"); + return otherZonePromise; // wait for the foreign zone promise to complete. + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still same transaction 5"); + }); + }).catch(function (e) { + QUnit.ok(false, "Error: ".concat(e.stack || e)); + }).then(done); + return [2 /*return*/]; + }); + }); + }); + QUnit.test("Should be able to await Promise.all()", function (assert) { return __awaiter(void 0, void 0, void 0, function () { + var done, compatible; + return __generator(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__default["default"], db$6) + .catch(function (e) { + QUnit.ok(false, e.stack || e); + }).then(done); + return [2 /*return*/]; + } + }); + }); }); + spawnedTest("Should use Promise.all where applicable", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$6.transaction('rw', db$6.items, function () { + var all; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.resolve(3)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$6.items.bulkAdd([{ id: 'a' }, { id: 'b' }])]; + case 2: + _a.sent(); + return [4 /*yield*/, Promise.all([db$6.items.get('a'), db$6.items.get('b')])]; + case 3: + all = _a.sent(); + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + return [4 /*yield*/, Promise.all([db$6.items.get('a'), db$6.items.get('b')])]; + case 4: + all = _a.sent(); + QUnit.equal(all.length, 2); + QUnit.equal(all[0].id, 'a'); + QUnit.equal(all[1].id, 'b'); + return [2 /*return*/]; + } + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("Even when keeping a reference to global Promise, still maintain PSD zone states", function () { + var Promise; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + Promise = window.Promise; + return [4 /*yield*/, db$6.transaction('rw', db$6.items, function () { + var trans = Dexie__default["default"].currentTransaction; + QUnit.ok(trans !== null, "Have a transaction"); + return Promise.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still have the same current transaction."); + return Promise.resolve().then(function () { return Promise.resolve(); }); + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Still have the same current transaction after multiple global.Promise.resolve() calls"); + }); + })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("Sub Transactions with async await", function () { + var compatible, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, idbAndPromiseCompatible.catch(function () { return false; })]; + case 1: + compatible = _a.sent(); + if (!compatible) { + QUnit.ok(true, "Promise and IndexedDB is incompatible on this browser. Native async await fails \"by design\" for indexedDB transactions"); + return [2 /*return*/]; + } + return [4 /*yield*/, new Function('equal', 'ok', 'Dexie', 'db', "return (async ()=>{\n await db.items.bulkAdd([{id: 1}, {id:2}, {id: 3}]);\n let result = await db.transaction('rw', db.items, async ()=>{\n let items = await db.items.toArray();\n let numItems = await db.transaction('r', db.items, async ()=>{\n equal(await db.items.count(), await db.items.count(), \"Two awaits of count should equal\");\n equal(await db.items.count(), 3, \"Should be 3 items\");\n return await db.items.count();\n });\n let numItems2 = await db.transaction('r', db.items, async ()=>{\n equal(await db.items.count(), await db.items.count(), \"Two awaits of count should equal\");\n equal(await db.items.count(), 3, \"Should be 3 items\");\n return await db.items.count();\n });\n equal (numItems, numItems2, \"The total two inner transactions should be possible to run after each other\");\n return numItems;\n });\n equal (result, 3, \"Result should be 3\");\n })();")(QUnit.equal, QUnit.ok, Dexie__default["default"], db$6)]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + QUnit.ok(e_1.name === 'SyntaxError', "No support for native async functions in this browser"); + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); + }); + promisedTest("Should patch global Promise within transaction scopes but leave them intact outside", function () { return __awaiter(void 0, void 0, void 0, function () { + var GlobalPromise; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(Promise !== Dexie__default["default"].Promise, "At global scope. Promise should not be Dexie.Promise"); + QUnit.ok(window.Promise !== Dexie__default["default"].Promise, "At global scope. Promise should not be Dexie.Promise"); + GlobalPromise = window.Promise; + return [4 /*yield*/, db$6.transaction('rw', db$6.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + QUnit.ok(Promise === Dexie__default["default"].Promise, "Within transaction scope, Promise should be Dexie.Promise."); + QUnit.ok(window.Promise === Dexie__default["default"].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(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$6.transaction('rw', db$6.items, function () { return __awaiter(void 0, void 0, void 0, function () { + var trans; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + trans = Dexie__default["default"].currentTransaction; + QUnit.ok(!!trans, "Should have a current transaction"); + return [4 /*yield*/, db$6.items.add({ id: 'foo' })]; + case 1: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of Dexie.Promise"); + return [4 /*yield*/, Promise.resolve()]; + case 2: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of Promise.resolve()"); + return [4 /*yield*/, 3]; + case 3: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted after await 3"); + return [4 /*yield*/, db$6.transaction('r', db$6.items, function (innerTrans) { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + QUnit.ok(!!innerTrans, "Should have inner transaction"); + QUnit.equal(Dexie__default["default"].currentTransaction, innerTrans, "Inner transaction should be there"); + QUnit.equal(innerTrans.parent, trans, "Parent transaction should be correct"); + return [4 /*yield*/, db$6.items.get(1)]; + case 1: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === innerTrans, "Transaction persisted in inner transaction"); + return [2 /*return*/]; + } + }); + }); })]; + case 4: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of sub transaction"); + return [4 /*yield*/, (function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$6.items.get(1)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); })()]; + case 5: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of async function"); + return [4 /*yield*/, (function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Promise.all([db$6.transaction('r', db$6.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$6.items.get(1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$6.items.get(2)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }), db$6.transaction('r', db$6.items, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$6.items.get(1)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); })])]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })()]; + case 6: + _a.sent(); + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted between await calls of async function 2"); + return [4 /*yield*/, Promise.resolve().then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted after window.Promise.resolve().then()"); + return (function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); })(); // Resolve with native promise + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted after native promise completion"); + return Promise.resolve(); + }).then(function () { + QUnit.ok(Dexie__default["default"].currentTransaction === trans, "Transaction persisted after window.Promise.resolve().then()"); + return (function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); })(); + })]; + case 7: + _a.sent(); + QUnit.ok(Dexie__default["default"].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/dexie/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(void 0, void 0, void 0, function () { + var compatible; + return __generator(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__default["default"], db$6)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + var GlobalPromise = window.Promise; + promisedTest("Should behave outside transactions as well", function () { return __awaiter(void 0, void 0, void 0, function () { + var compatible; + return __generator(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__default["default"], db$6, GlobalPromise)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var db$5 = new Dexie__default["default"]("TestDBException"); + db$5.version(1).stores({ users: "id,first,last,&username,&*email,*pets" }); + db$5.on("populate", function (trans) { + db$5.users.add({ id: 1, first: "David", last: "Fahlander", username: "dfahlander", email: ["david@awarica.com", "daw@thridi.com"], pets: ["dog"] }); + db$5.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$5).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + spawnedTest("transaction should abort on collection error", function () { + var _a, _b; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, db$5.transaction("rw", db$5.users, function () { + var id; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$5.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" })]; + case 1: + id = _a.sent(); + QUnit.equal(id, 3); + return [4 /*yield*/, db$5.users.where('id').equals(null).toArray()]; + case 2: + _a.sent(); + QUnit.ok(false, "Should not come here"); + return [2 /*return*/]; + } + }); + }).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw DataError: " + e); + })]; + case 1: + _c.sent(); + _a = QUnit.equal; + return [4 /*yield*/, db$5.users.where('first').equals("Foo").count()]; + case 2: + _a.apply(void 0, [_c.sent(), 0, "Should not have succeeded to add when transaction was aborted"]); + return [4 /*yield*/, db$5.transaction("rw", db$5.users, function () { + db$5.users.add({ id: 3, first: "Foo", last: "Bar", username: "foobar" }); + db$5.users.where('id').equals(null).toArray(function (res) { + QUnit.ok(false, "Not possible to query null"); + }); + }).then(function () { + QUnit.ok(false, "Transaction shouldnt commit"); + }).catch(function (e) { + QUnit.ok(true, "Got error because WhereClause.equals(null) should throw TypeError"); + })]; + case 3: + _c.sent(); + _b = QUnit.equal; + return [4 /*yield*/, db$5.users.where('first').equals("Foo").count()]; + case 4: + _b.apply(void 0, [_c.sent(), 0, "Should not have succeeded to add when transaction was aborted"]); + return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("eventError-transaction-catch", function () { + db$5.transaction("rw", db$5.users, function () { + db$5.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$5.transaction("rw", db$5.users, function () { + db$5.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$5.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$5.transaction("r", db$5.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$5.transaction("r", db$5.users, function () { + db$5.users.where("username").equals("apa").toArray(function () { + db$5.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$5.users.hook('deleting', deletingHook); + db$5.transaction('rw', db$5.users, function () { + function deleteKarls() { + db$5.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }); + } + db$5.users.delete(1); + deleteKarls(); + }).then(function () { + QUnit.ok(false, "Transaction should not complete!"); + }).catch(function (err) { + QUnit.ok(true, "Transaction aborted"); + }).finally(function () { + db$5.users.hook('deleting').unsubscribe(deletingHook); + QUnit.start(); + }); + }); + QUnit.asyncTest("exceptionThrown-iteration-should-not-abort-when-using-hook", function () { + db$5.users.hook('deleting', function () { + // Testing with + }); + db$5.transaction('rw', db$5.users, function () { + function deleteKarls() { + db$5.users.toCollection().modify(function (user) { + delete this.value; + throw "Throwing something"; + }).catch(function (err) { + // Catching error should prevent transaction from aborting. + }); + } + db$5.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__default["default"]("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__default["default"]("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__default["default"]("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__default["default"]("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__default["default"]("TestUpgrader"); + return db.open(); + }).then(function () { + QUnit.ok(false, "The database should not have been created"); + }).catch(function (err) { + QUnit.ok(err instanceof Dexie__default["default"].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__default["default"]("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__default["default"].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__default["default"].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__default["default"].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__default["default"].Promise.all([ + // WhereClause.equals() + db$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.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$5.transaction('rw', db$5.users, function () { + db$5.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$5.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 #67 - Regression test 2 - other error in key", function () { + db$5.transaction('rw', db$5.users, function () { + db$5.users.where('first').above("").delete().then(function (num) { + QUnit.ok(true, num + " users deleted"); + db$5.users.where('first').above(false).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.module("upgrading"); + var Promise$2 = Dexie__default["default"].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; + var baseTables = []; + // Ensure Dexie verno and backing IDB version are as expected. + function checkVersion(version) { + QUnit.equal(db.verno, version, "DB should be version ".concat(version)); + QUnit.equal(db.backendDB().version, version * 10, "idb should be version ".concat(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__default["default"].delete(DBNAME); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Empty schema + db = new Dexie__default["default"](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. + db.tables.length; + baseTables = db.tables.map(function (t) { return t.name; }); + }); + }).then(function () { + // -------------------------------------------------------------------- + // Test: Adding version. + db = new Dexie__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"](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__default["default"].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__default["default"].delete("raw-db").then(function () { + // Create a bare-bone indexedDB database with custom indexes of various kinds. + return new Dexie__default["default"].Promise(function (resolve, reject) { + var indexedDB = Dexie__default["default"].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__default["default"]("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", + 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__default["default"]("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__default["default"].delete("raw-db").then(done); + }); + }); + promisedTest("Issue #713 - how to change table name", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, db2, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].delete("issue713")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]('issue713'); + _a.label = 2; + case 2: + _a.trys.push([2, , 5, 7]); + db.version(1).stores({ + friends: '++id, name, age' + }); + return [4 /*yield*/, db.friends.bulkAdd([ + { name: "Foo", age: 25 }, + { name: "Bar", age: 75 } + ])]; + case 3: + _a.sent(); + db.close(); + db2 = new Dexie__default["default"]('issue713'); + db2.version(1).stores({ + friends: '++id, name, age' + }); + db2.version(2).stores({ + friends2: 'id, name, age' + }).upgrade(function (tx) { + return tx.friends.toArray().then(function (objs) { + return tx.friends2.bulkAdd(objs); + }); + }); + db2.version(3).stores({ + friends: null + }); + return [4 /*yield*/, db2.friends2.toArray()]; + case 4: + result = _a.sent(); + QUnit.equal(result.length, 2, "Should get 2 friends"); + QUnit.equal(result[0].name, "Foo", "First friend is 'Foo'"); + QUnit.equal(result[1].name, "Bar", "First friend is 'Bar'"); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, db.delete()]; + case 6: + _a.sent(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #713 - how to change table name (short)", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, db2, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].delete("issue713Short")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]('issue713Short'); + _a.label = 2; + case 2: + _a.trys.push([2, , 5, 7]); + db.version(1).stores({ + friends: '++id, name, age' + }); + return [4 /*yield*/, db.friends.bulkAdd([ + { name: "Foo", age: 25 }, + { name: "Bar", age: 75 } + ])]; + case 3: + _a.sent(); + db.close(); + db2 = new Dexie__default["default"]('issue713Short'); + db2.version(1).stores({ + friends: '++id, name, age' + }); + db2.version(2).stores({ + friends2: 'id, name, age', + friends: null // delete after upgrader + }).upgrade(function (tx) { + return tx.friends.toArray().then(function (objs) { + return tx.friends2.bulkAdd(objs); + }); + }); + return [4 /*yield*/, db2.friends2.toArray()]; + case 4: + result = _a.sent(); + QUnit.equal(result.length, 2, "Should get 2 friends"); + QUnit.equal(result[0].name, "Foo", "First friend is 'Foo'"); + QUnit.equal(result[1].name, "Bar", "First friend is 'Bar'"); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, db.delete()]; + case 6: + _a.sent(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); }); + promisedTest("Changing primary key", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, foos, foo2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE || isEdge) { + QUnit.ok(true, "Skipping this test for IE and Edge - it has a bug that prevents it from renaming a table"); + return [2 /*return*/]; + } + return [4 /*yield*/, Dexie__default["default"].delete("changePrimKey")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]("changePrimKey"); + db.version(1).stores({ + foos: '++id' + }); + return [4 /*yield*/, db.foos.bulkAdd([{ name: "Hola" }, { name: "Hello" }])]; + case 2: + _a.sent(); + db.close(); + // To change primary key, let's start by copying the table + // and then deleting and recreating the original table + // to copy it back again + db = new Dexie__default["default"]("changePrimKey"); + db.version(1).stores({ + foos: '++id' + }); + // Add version 2 that copies the data to foos2 + db.version(2).stores({ + foos2: 'objId' + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos2.bulkAdd(foos.map(function (foo) { return ({ + objId: "obj:" + foo.id, + hello: foo.name + }); }))]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + // Add version 3 that deletes old "foos" + db.version(3).stores({ + foos: null + }); + // Add version 4 that recreates "foos" with wanted primary key + // and do the copying again + db.version(4).stores({ + foos: 'objId, hello' + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos2.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos.bulkAdd(foos)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + // Finally delete the temp table + db.version(5).stores({ + foos2: null + }); + return [4 /*yield*/, db.foos.toArray()]; + case 3: + foos = _a.sent(); + QUnit.equal(foos.length, 2, "Should have 2 rows"); + QUnit.equal(foos[0].objId, "obj:1", "A primary key with an object ID 1 is there"); + QUnit.equal(foos[1].objId, "obj:2", "A primary key with an object ID 2 is there"); + return [4 /*yield*/, db.foos.get({ hello: "Hello" })]; + case 4: + foo2 = _a.sent(); + QUnit.ok(foo2 != null, "Should get a match"); + QUnit.equal(foo2.objId, "obj:2", "The expected ID was returned"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Changing primary key (short)", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, foos, foo2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE || isEdge) { + QUnit.ok(true, "Skipping this test for IE and Edge - it has a bug that prevents it from renaming a table"); + return [2 /*return*/]; + } + return [4 /*yield*/, Dexie__default["default"].delete("changePrimKeyShort")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]("changePrimKeyShort"); + db.version(1).stores({ + foos: '++id' + }); + return [4 /*yield*/, db.foos.bulkAdd([{ name: "Hola" }, { name: "Hello" }])]; + case 2: + _a.sent(); + db.close(); + // To change primary key, let's start by copying the table + // and then deleting and recreating the original table + // to copy it back again + db = new Dexie__default["default"]("changePrimKeyShort"); + db.version(1).stores({ + foos: '++id' + }); + // Add version 2 that copies the data to foos2 + db.version(2).stores({ + foos: null, + foos2: 'objId' + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos2.bulkAdd(foos.map(function (foo) { return ({ + objId: "obj:" + foo.id, + hello: foo.name + }); }))]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + // Add version 3 that recreates "foos" with wanted primary key + // and do the copying again + db.version(3).stores({ + foos: 'objId, hello', + foos2: null // delete after upgrader + }).upgrade(function (tx) { return __awaiter(void 0, void 0, void 0, function () { + var foos; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, tx.foos2.toArray()]; + case 1: + foos = _a.sent(); + return [4 /*yield*/, tx.foos.bulkAdd(foos)]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + return [4 /*yield*/, db.foos.toArray()]; + case 3: + foos = _a.sent(); + QUnit.equal(foos.length, 2, "Should have 2 rows"); + QUnit.equal(foos[0].objId, "obj:1", "A primary key with an object ID 1 is there"); + QUnit.equal(foos[1].objId, "obj:2", "A primary key with an object ID 2 is there"); + return [4 /*yield*/, db.foos.get({ hello: "Hello" })]; + case 4: + foo2 = _a.sent(); + QUnit.ok(foo2 != null, "Should get a match"); + QUnit.equal(foo2.objId, "obj:2", "The expected ID was returned"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue 919: Store not found when versions declared in decending order", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, _a, _b, _c, _d, _e, _f; + return __generator(this, function (_g) { + switch (_g.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].delete("issue919")]; + case 1: + _g.sent(); + db = new Dexie__default["default"]("issue919"); + db.version(1).stores({ + friends: "++id,name,age" + }); + return [4 /*yield*/, db.open()]; + case 2: + _g.sent(); + // succeeds + _a = QUnit.ok; + _b = [true]; + _c = "Could open v1: ".concat; + return [4 /*yield*/, db.friends.toArray()]; + case 3: + // succeeds + _a.apply(void 0, _b.concat([_c.apply("Could open v1: ", [_g.sent()])])); + db.close(); + db = new Dexie__default["default"]("issue919"); + // add a new store, `friends` store remains as before + db.version(2).stores({ + enemies: "++id,name" + }); + db.version(1).stores({ + friends: "++id,name,age" + }); + return [4 /*yield*/, db.open()]; + case 4: + _g.sent(); + // fails with: NotFoundError: `The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.` + _d = QUnit.ok; + _e = [true]; + _f = "Could open version 2: ".concat; + return [4 /*yield*/, db.friends.toArray()]; + case 5: + // fails with: NotFoundError: `The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.` + _d.apply(void 0, _e.concat([_f.apply("Could open version 2: ", [_g.sent()])])); + return [4 /*yield*/, db.delete()]; + case 6: + _g.sent(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("PR #959: Dexie should no more require users to keep old versions if they don't attach an upgrader to it", function () { return __awaiter(void 0, void 0, void 0, function () { + var DBNAME, db, foo; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + DBNAME = "pr959"; + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie__default["default"](DBNAME); + db.version(1).stores({ + friends: "id" + }); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + QUnit.ok(true, "Could open v1"); + return [4 /*yield*/, db.friends.add({ id: 1, name: "Foo 959" })]; + case 3: + _a.sent(); + db.close(); + db = new Dexie__default["default"](DBNAME); + db.version(2).stores({ + friends: "id, name" + }); + return [4 /*yield*/, db.open()]; + case 4: + _a.sent(); + QUnit.ok(true, "Could open v2 without having v1 specified. Name should now be indexed."); + return [4 /*yield*/, db.friends.where("name").startsWith("Foo").first()]; + case 5: + foo = _a.sent(); + QUnit.ok(!!foo, "Could find friend using newly added index"); + QUnit.equal(foo.id, 1, "Got the right foo here"); + db.close(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #959 - Should migrate successfully with an explicit unique modifier of the primary key", function () { return __awaiter(void 0, void 0, void 0, function () { + var db, result, result2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, Dexie__default["default"].delete("issue959")]; + case 1: + _a.sent(); + db = new Dexie__default["default"]("issue959"); + db.version(1).stores({ + friends: "&name, age" + }); + return [4 /*yield*/, db.friends.bulkAdd([ + { name: "Foo", age: 25, weight: 70 }, + { name: "Bar", age: 75, weight: 100 } + ])]; + case 2: + _a.sent(); + db.close(); + db = new Dexie__default["default"]("issue959"); + db.version(1).stores({ + friends: "&name, age" + }); + db.version(2).stores({ + friends: "&name, age, weight" + }); + return [4 /*yield*/, db.friends.orderBy("age").toArray()]; + case 3: + result = _a.sent(); + QUnit.equal(result.length, 2, "Should get 2 friends"); + QUnit.equal(result[0].name, "Foo", "First friend is 'Foo'"); + QUnit.equal(result[1].name, "Bar", "First friend is 'Bar'"); + return [4 /*yield*/, db.friends.get({ weight: 100 })]; + case 4: + result2 = _a.sent(); + QUnit.ok(result2 != null, "Should get a match"); + QUnit.equal(result2.name, "Bar", "The expected friends was returned"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue 1145 - Regression: SchemaError during version upgrade", function () { return __awaiter(void 0, void 0, void 0, function () { + var DBNAME, db, e_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + DBNAME = "issue1145"; + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie__default["default"](DBNAME); + db.version(1).stores({ Y: "id" }); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + return [4 /*yield*/, db.close()]; + case 3: + _a.sent(); + db.version(2).upgrade(function (trans) { + QUnit.ok(true, "Starting version 2 upgrade."); + return trans.Y.count(); + }); + db.version(3).stores({ + Y: "id,X", + }); + db.version(4).upgrade(function (trans) { + QUnit.ok(true, "Starting version 4 upgrade."); + return trans.Y.where("X").equals("value").toArray(); + }); + _a.label = 4; + case 4: + _a.trys.push([4, 6, 7, 9]); + return [4 /*yield*/, db.open()]; + case 5: + _a.sent(); + QUnit.ok(true, "Open successful"); + return [3 /*break*/, 9]; + case 6: + e_1 = _a.sent(); + QUnit.ok(false, "Open Failed:: " + e_1); + return [3 /*break*/, 9]; + case 7: return [4 /*yield*/, db.delete()]; + case 8: + _a.sent(); + return [7 /*endfinally*/]; + case 9: return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue 1418 - Not deleting all object stores", function () { return __awaiter(void 0, void 0, void 0, function () { + var DBNAME, db; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports("deleteObjectStoreAfterRead")) { + QUnit.ok(true, "Skipping this test - buggy browser."); + return [2 /*return*/]; + } + if (Dexie__default["default"].addons.length > 0) { + QUnit.ok(true, "Skipping this test - default addons are acitve and can add more object stores"); + return [2 /*return*/]; + } + DBNAME = "issue1418"; + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 1: + _a.sent(); + db = new Dexie__default["default"](DBNAME); + db.version(1).stores({ + a: '++', + b: '++', + c: '++', + d: '++', + e: '++' + }); + return [4 /*yield*/, db.open()]; + case 2: + _a.sent(); + QUnit.equal(db.idbdb.objectStoreNames.length, 5, "There are 5 object stores"); + db.close(); + db = new Dexie__default["default"](DBNAME); + db.version(2).stores({ + a: null, + b: null, + c: null, + d: null, + e: '++' + }); + return [4 /*yield*/, db.open()]; + case 3: + _a.sent(); + QUnit.equal(db.idbdb.objectStoreNames.length, 1, "There is only one object store now"); + db.close(); + return [4 /*yield*/, Dexie__default["default"].delete(DBNAME)]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var async$1 = Dexie__default["default"].async; + var db$4 = new Dexie__default["default"]("TestIssuesDB"); + db$4.version(1).stores({ + users: "id,first,last,&username,*&email,*pets", + keyless: ",name", + foo: "id", + bars: "++id,text", + metrics: "id,[name+time]", + // If required for your test, add more tables here + }); + QUnit.module("misc", { + setup: function () { + QUnit.stop(); + resetDatabase(db$4).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + // + // Misc Tests + // + promisedTest("issue#729", function () { return __awaiter(void 0, void 0, void 0, function () { + var onConsoleWarn, warnDescriptor, err_1, err_2, err_3, err_4; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + onConsoleWarn = function (txt) { + QUnit.ok(false, 'console warn happened: ' + txt); + }; + warnDescriptor = Object.getOwnPropertyDescriptor(console, 'warn'); + console.warn = onConsoleWarn; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, db$4.foo.bulkPut([{ + id: 1, + foo: 'foo', + }, { + id: 2, + foo: 'bar', + } + ])]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + QUnit.ok(false, "Couldn't populate data: " + err_1); + return [3 /*break*/, 4]; + case 4: + _a.trys.push([4, 6, , 7]); + return [4 /*yield*/, db$4.foo.add({ id: 1, foo: "bar" })]; + case 5: + _a.sent(); + return [3 /*break*/, 7]; + case 6: + err_2 = _a.sent(); + QUnit.ok(true, "Got the err:" + err_2); + return [3 /*break*/, 7]; + case 7: + _a.trys.push([7, 9, , 10]); + return [4 /*yield*/, db$4.foo.get(false)]; + case 8: + _a.sent(); + return [3 /*break*/, 10]; + case 9: + err_3 = _a.sent(); + QUnit.ok(true, "Got the err:" + err_3); + return [3 /*break*/, 10]; + case 10: + _a.trys.push([10, 12, , 13]); + return [4 /*yield*/, db$4.foo.where({ id: 1 }) + .modify({ id: 2, foo: "bar" })]; + case 11: + _a.sent(); + return [3 /*break*/, 13]; + case 12: + err_4 = _a.sent(); + QUnit.ok(true, "Got the err:" + err_4); + return [3 /*break*/, 13]; + case 13: + if (warnDescriptor) { + Object.defineProperty(console, 'warn', warnDescriptor); + } + else { + delete console.warn; + } + return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("Adding object with falsy keys", function () { + db$4.keyless.add({ name: "foo" }, 1).then(function (id) { + QUnit.equal(id, 1, "Normal case ok - Object with key 1 was successfully added."); + return db$4.keyless.add({ name: "bar" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could add a numeric falsy value (0)"); + return db$4.keyless.add({ name: "foobar" }, ""); + }).then(function (id) { + QUnit.equal(id, "", "Could add a string falsy value ('')"); + return db$4.keyless.put({ name: "bar2" }, 0); + }).then(function (id) { + QUnit.equal(id, 0, "Could put a numeric falsy value (0)"); + return db$4.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); + }); + promisedTest("#770", function () { return __awaiter(void 0, void 0, void 0, function () { + var dbName, db, runnedVersions, otherDB, otherDbRows, origDbRows, err_5; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + dbName = 'TestDB-' + Math.random(); + db = new Dexie__default["default"](dbName, { addons: [] }); + runnedVersions = []; + _a.label = 1; + case 1: + _a.trys.push([1, 7, 8, 11]); + db.version(1).stores({ test: 'id' }); + return [4 /*yield*/, db.test.put({ id: 1 })]; + case 2: + _a.sent(); + return [4 /*yield*/, db.open()]; + case 3: + _a.sent(); + db.close(); + db = new Dexie__default["default"](dbName, { addons: [] }); + db.version(1).stores({ test: 'id' }); + db.version(2).stores({ test: 'id' }).upgrade(function (t) { return __awaiter(void 0, void 0, void 0, function () { + var rowsToCopy; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + runnedVersions.push(2); + return [4 /*yield*/, t.test.toArray()]; + case 1: + rowsToCopy = _a.sent(); + return [4 /*yield*/, Dexie__default["default"].waitFor((function () { return __awaiter(void 0, void 0, void 0, function () { + var otherDB; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + otherDB = new Dexie__default["default"](dbName + '-another-unrelated-db', { addons: [] }); + otherDB.version(1).stores({ foo: 'id' }); + return [4 /*yield*/, otherDB.open()]; + case 1: + _a.sent(); + return [4 /*yield*/, otherDB.foo.bulkAdd(rowsToCopy)]; + case 2: + _a.sent(); + otherDB.close(); + return [2 /*return*/]; + } + }); + }); })())]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + db.version(3).stores({ test: 'id' }).upgrade(function (t) { + runnedVersions.push(3); + }); + return [4 /*yield*/, db.open()]; + case 4: + _a.sent(); + QUnit.deepEqual(runnedVersions, [2, 3], "Versions 3 did indeed proceed (as well as version 2)"); + otherDB = new Dexie__default["default"](dbName + '-another-unrelated-db', { addons: [] }); + otherDB.version(1).stores({ foo: 'id' }); + return [4 /*yield*/, otherDB.foo.toArray()]; + case 5: + otherDbRows = _a.sent(); + return [4 /*yield*/, db.test.toArray()]; + case 6: + origDbRows = _a.sent(); + QUnit.deepEqual(otherDbRows, origDbRows, "All rows was copied atomically"); + db.close(); + otherDB.close(); + return [3 /*break*/, 11]; + case 7: + err_5 = _a.sent(); + QUnit.ok(false, "Error " + err_5); + return [3 /*break*/, 11]; + case 8: return [4 /*yield*/, db.delete()]; + case 9: + _a.sent(); + return [4 /*yield*/, new Dexie__default["default"](dbName + '-another-unrelated-db', { addons: [] }).delete()]; + case 10: + _a.sent(); + return [7 /*endfinally*/]; + case 11: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("#102 Passing an empty array to anyOf throws exception", async$1(function () { + var count, err_6; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, db$4.users.where("username").anyOf([]).count()]; + case 1: + count = _a.sent(); + QUnit.equal(count, 0, "Zarro items matched the query anyOf([])"); + return [3 /*break*/, 4]; + case 2: + err_6 = _a.sent(); + QUnit.ok(false, "Error when calling anyOf([]): " + err_6); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + })); + spawnedTest("#248 'modifications' object in 'updating' hook can be bizarre", function () { + function CustomDate(realDate) { + this._year = new Date(realDate).getFullYear(); + this._month = new Date(realDate).getMonth(); + this._day = new Date(realDate).getDate(); + this._millisec = new Date(realDate).getTime(); + //... + } + function creatingHook(primKey, obj) { + ++numCreating; + var date = obj.date; + if (date && date instanceof CustomDate) { + obj.date = new Date(date._year, date._month, date._day); + } + } + function updatingHook(modifications, primKey, obj) { + ++numUpdating; + var date = modifications.date; + if (date && date instanceof CustomDate) { + return { date: new Date(date._year, date._month, date._day) }; + } + } + function isDate(obj) { + // obj instanceof Date does NOT work with Safari when Date are retrieved from IDB. + return obj.getTime && obj.getDate && obj.getFullYear; + } + function readingHook(obj) { + if (obj.date && isDate(obj.date)) { + obj.date = new CustomDate(obj.date); + } + return obj; + } + var numCreating, numUpdating, testDate, testDate2, retrieved; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + numCreating = 0, numUpdating = 0; + db$4.foo.hook('creating', creatingHook); + db$4.foo.hook('reading', readingHook); + db$4.foo.hook('updating', updatingHook); + testDate = new CustomDate(new Date(2016, 5, 11)); + QUnit.equal(testDate._year, 2016, "CustomDate has year 2016"); + QUnit.equal(testDate._month, 5, "CustomDate has month 5"); + QUnit.equal(testDate._day, 11, "CustomDate has day 11"); + testDate2 = new CustomDate(new Date(2016, 5, 12)); + _a.label = 1; + case 1: + _a.trys.push([1, , 4, 5]); + db$4.foo.add({ id: 1, date: testDate }); + return [4 /*yield*/, db$4.foo.get(1)]; + case 2: + retrieved = _a.sent(); + QUnit.ok(retrieved.date instanceof CustomDate, "Got a CustomDate object when retrieving object"); + QUnit.equal(retrieved.date._day, 11, "The CustomDate is on day 11"); + db$4.foo.put({ id: 1, date: testDate2 }); + return [4 /*yield*/, db$4.foo.get(1)]; + case 3: + retrieved = _a.sent(); + QUnit.ok(retrieved.date.constructor === CustomDate, "Got a CustomDate object when retrieving object"); + QUnit.equal(retrieved.date._day, 12, "The CustomDate is now on day 12"); + // Check that hooks has been called expected number of times + QUnit.equal(numCreating, 1, "creating hook called once"); + QUnit.equal(numUpdating, 1, "updating hook called once"); + return [3 /*break*/, 5]; + case 4: + db$4.foo.hook('creating').unsubscribe(creatingHook); + db$4.foo.hook('reading').unsubscribe(readingHook); + db$4.foo.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + QUnit.asyncTest("Issue: Broken Promise rejection #264", 1, function () { + db$4.open().then(function () { + return db$4.users.where('id') + .equals('does-not-exist') + .first(); + }).then(function (result) { + return Promise.reject(undefined); + }).catch(function (err) { + QUnit.equal(err, undefined, "Should catch the rejection"); + }).then(function (res) { + QUnit.start(); + }).catch(function (err) { + QUnit.start(); + }); + }); + QUnit.asyncTest("#323 @gitawego's post. Should not fail unexpectedly on readonly properties", function () { + var Foo = /** @class */ (function () { + function Foo() { + } + Object.defineProperty(Foo.prototype, "synced", { + get: function () { return false; }, + enumerable: false, + configurable: true + }); + return Foo; + }()); + db$4.foo.mapToClass(Foo); + db$4.transaction('rw', db$4.foo, function () { + db$4.foo.put({ id: 1 }); + db$4.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$4.foo.get(1); + }).then(function (foo) { + return db$4.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: ".concat(e.stack || e)); + }).then(function () { + return db$4.foo.toArray(); + }).then(function (array) { + console.log("Got array of length: ".concat(array.length)); + }).catch(function (e) { + QUnit.ok(true, "Got error from toArray: ".concat(e.stack || e)); + return db$4.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(): ".concat(e.stack || e)); + return db$4.foo.toCollection().sortBy('synced'); + }).then(function (array) { + console.log("Could do sortBy"); + }).catch(function (e) { + QUnit.ok(true, "Got error from sortBy(): ".concat(e.stack || e)); + }).finally(QUnit.start); + }); + spawnedTest("#360 DB unresponsive after multiple Table.update() or Collection.modify()", function () { + var NUM_UPDATES, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + NUM_UPDATES = 2000; + return [4 /*yield*/, db$4.transaction('rw', db$4.foo, function () { + var i; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$4.foo.put({ id: 1, value: 0 })]; + case 1: + _a.sent(); + for (i = 0; i < NUM_UPDATES; ++i) { + db$4.foo.where('id').equals(1).modify(function (item) { return ++item.value; }); + } + return [4 /*yield*/, db$4.foo.get(1)]; + case 2: return [2 /*return*/, _a.sent()]; + } + }); + })]; + case 1: + result = _a.sent(); + QUnit.equal(result.value, NUM_UPDATES, "Should have updated id 1 a ".concat(NUM_UPDATES, " times")); + return [2 /*return*/]; + } + }); + }); + spawnedTest("delByKeyPath not working correctly for arrays", function () { + var obj, obj2, jsonResult, jsonResult2; + return __generator(this, function (_a) { + obj = { deepObject: { someArray: ["a", "b"] } }; + obj2 = { deepObject: { someArray: ["a", "b", "c"] } }; + jsonResult = JSON.stringify(obj); + console.log("jsonResult = ", jsonResult); + Dexie__default["default"].delByKeyPath(obj2, "deepObject.someArray.2"); + jsonResult2 = JSON.stringify(obj2); + console.log("jsonResult2 = ", jsonResult2); + QUnit.equal(jsonResult, jsonResult2, "Should be equal ".concat(jsonResult, " ").concat(jsonResult2)); + return [2 /*return*/]; + }); + }); + QUnit.asyncTest("#1079 mapToClass", function () { + var Foo = /** @class */ (function () { + function Foo() { + } + return Foo; + }()); + db$4.foo.mapToClass(Foo); + db$4.transaction('rw', db$4.foo, function () { + db$4.foo.put({ id: 1 }); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from put: ".concat(e.stack || e)); + }).then(function () { + return db$4.foo.get(1); + }).then(function (getResult) { + QUnit.ok(getResult instanceof Foo, "Result of get not mapped to class"); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from get: ".concat(e.stack || e)); + }).then(function () { + return db$4.foo.bulkGet([1]); + }).then(function (bulkGetResult) { + QUnit.ok(bulkGetResult.length === 1, "Unexpected array length ".concat(bulkGetResult.length, " from bulkGet")); + QUnit.ok(bulkGetResult[0] instanceof Foo, "Result of bulkGet not mapped to class"); + }).catch(function (e) { + QUnit.ok(true, "Unexpected error from bulkGet: ".concat(e.stack || e)); + }).finally(QUnit.start); + }); + QUnit.asyncTest("PR #1108", function () { return __awaiter(void 0, void 0, void 0, function () { + var origConsoleWarn, warnings, DBNAME, db_1, error_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE || isEdge) { + QUnit.ok(true, "Disabling this test for IE and legacy Edge"); + QUnit.start(); + return [2 /*return*/]; + } + origConsoleWarn = console.warn; + warnings = []; + console.warn = function (msg) { warnings.push(msg); return origConsoleWarn.apply(this, arguments); }; + _a.label = 1; + case 1: + _a.trys.push([1, 5, 6, 7]); + DBNAME = "PR1108"; + db_1 = new Dexie__default["default"](DBNAME); + db_1.version(1).stores({ + foo: "id" + }); + return [4 /*yield*/, db_1.open()]; + case 2: + _a.sent(); + QUnit.ok(!warnings.some(function (x) { return /SchemaDiff/.test(x); }), "".concat(DBNAME, " could be opened without SchemaDiff warnings")); + db_1.close(); + // Adding an index without updating version number: + db_1 = new Dexie__default["default"](DBNAME); + db_1.version(1).stores({ + foo: "id,name" + }); + warnings = []; + return [4 /*yield*/, db_1.open()]; + case 3: + _a.sent(); + QUnit.ok(warnings.some(function (x) { return /SchemaDiff/.test(x); }), "Should warn when a new index was declared without incrementing version number"); + db_1.close(); + warnings = []; + // Adding a table without updating version number: + db_1 = new Dexie__default["default"](DBNAME); + db_1.version(1).stores({ + foo: "id", + bar: "" + }); + return [4 /*yield*/, db_1.open()]; + case 4: + _a.sent(); + QUnit.ok(warnings.some(function (x) { return /SchemaDiff/.test(x); }), "Should warn when a new table was declared without incrementing version number"); + db_1.close(); + warnings = []; + return [3 /*break*/, 7]; + case 5: + error_1 = _a.sent(); + QUnit.ok(false, error_1); + return [3 /*break*/, 7]; + case 6: + console.warn = origConsoleWarn; + QUnit.start(); + return [7 /*endfinally*/]; + case 7: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("Issue #1112", function () { return __awaiter(void 0, void 0, void 0, function () { + function Bar(text) { + this.id = undefined; + this.text = text; + } + var id1, id2, id3, id4, bar3, bar3_2, error_2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 8, 9, 10]); + return [4 /*yield*/, db$4.bars.add(new Bar("hello1"))]; + case 1: + id1 = _a.sent(); + QUnit.ok(!isNaN(id1), "got a real autoincremented id for my bar using add()"); + return [4 /*yield*/, db$4.bars.put(new Bar("hello2"))]; + case 2: + id2 = _a.sent(); + QUnit.ok(!isNaN(id2), "got a real autoincremented id for my bar using put()"); + return [4 /*yield*/, db$4.bars.bulkAdd([new Bar("hello3")])]; + case 3: + id3 = _a.sent(); + QUnit.ok(!isNaN(id3), "got a real autoincremented id for my bar using bulkAdd()"); + return [4 /*yield*/, db$4.bars.bulkPut([new Bar("hello4")])]; + case 4: + id4 = _a.sent(); + QUnit.ok(!isNaN(id4), "got a real autoincremented id for my bar using bulkPut()"); + return [4 /*yield*/, db$4.bars.get(id3)]; + case 5: + bar3 = _a.sent(); + QUnit.equal(bar3.text, "hello3", "Should get the object with text hello3"); + bar3.text = "hello3 modified"; + return [4 /*yield*/, db$4.bars.put(bar3)]; + case 6: + _a.sent(); + return [4 /*yield*/, db$4.bars.get(id3)]; + case 7: + bar3_2 = _a.sent(); + QUnit.equal(bar3_2.text, "hello3 modified", "Could successfully change a prop and put back."); + return [3 /*break*/, 10]; + case 8: + error_2 = _a.sent(); + QUnit.ok(false, error_2); + return [3 /*break*/, 10]; + case 9: + QUnit.start(); + return [7 /*endfinally*/]; + case 10: return [2 /*return*/]; + } + }); + }); }); + QUnit.asyncTest("Issue #1280 - Don't perform deep-clone workaround when adding non-POJO to auto-incrementing table", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, 3, 4]); + return [4 /*yield*/, db$4.bars.add({ text: "hello1", fooProp: function () { } })]; + case 1: + _a.sent(); + QUnit.ok(false, "Expected add() to fail since IDB would fail with DOMError if trying to store a function."); + return [3 /*break*/, 4]; + case 2: + _a.sent(); + QUnit.ok(true); + return [3 /*break*/, 4]; + case 3: + QUnit.start(); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }); + promisedTest("Issue #1333 - uniqueKeys on virtual index should produce unique results", function () { return __awaiter(void 0, void 0, void 0, function () { + var result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!supports('compound')) + return [2 /*return*/, QUnit.ok(true, "SKIPPED - COMPOUND UNSUPPORTED")]; + return [4 /*yield*/, db$4.metrics.add({ id: "id1", name: "a", time: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$4.metrics.add({ id: "id2", name: "b", time: 2 })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$4.metrics.add({ id: "id3", name: "a", time: 3 })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$4.metrics.orderBy("name").uniqueKeys()]; + case 4: + result = _a.sent(); + QUnit.ok(result.length === 2, "Unexpected array length ".concat(result.length, " from uniqueKeys on virtual index, expected 2. Got ").concat(result.join(','))); + return [2 /*return*/]; + } + }); + }); }); + /** Try to reproduce customer issue where ReadonlyError was thrown when using liveQuery. + * This repro is not good enough though as it doesn't fail in dexie@4.0.1-alpha.23. + * Probably need to reproduce it in a more complex scenario with + * multiple liveQueries and transactions running in parallel. + * However, the issue is fixed with this same commit which will be + * dexie@4.0.1-alpha.24. It is verified with customer application. + * + * Keeping the test in case there will be time to try to improve it later. + */ + promisedTest("Issue - ReadonlyError thrown in liveQuery despite user did not do write transactions", function () { return __awaiter(void 0, void 0, void 0, function () { + var F; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // Encapsulating the code in a string to avoid transpilation. We need native await here to trigger bug. + QUnit.ok(!Promise.PSD, "Must not be within async context when starting"); + QUnit.ok(db$4.isOpen(), "DB must be open when starting"); + return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 10); })]; + case 1: + _a.sent(); + F = new Function('ok', 'equal', 'Dexie', 'db', 'liveQuery', "\n ok(true, \"Got here\");\n return (async ()=>{\n let physicalTickScheduled = false;\n const observable = liveQuery(async () => {\n console.debug(\"liveQuery executing\");\n //debugger;\n const result = db.transaction('r', 'metrics', async () => db.metrics.toArray());\n physicalTickScheduled = true;\n console.debug(\"physicalTick executed by toArray\");\n return await result;\n });\n const subscription = observable.subscribe({\n next: function (result) {\n ok(true, \"Got next result from observable\");\n }\n });\n ok(!!physicalTickScheduled, \"physicalTick is scheduled at this point\");\n console.debug(\"liveQuery subscribed. Now doing transaction immediately - it will push to microtickQueue\");\n try {\n //debugger;\n //db.transaction('rw', db.metrics, () => {\n // const x = Promise.PSD;\n await db.metrics.add({ id: \"id1\", name: \"a\", time: 1 }).then(() => {\n //debugger;\n return db.metrics.update(\"id1\", {name: \"b\"});\n });\n //});\n console.debug(\"Transaction succeeded\");\n ok(true, \"Successfully executed transaction\");\n } catch (error) {\n console.debug(\"Transaction failed\");\n ok(false, 'Failed to execute transaction due to ' + error);\n }\n subscription.unsubscribe();\n })();\n "); + return [2 /*return*/, F(QUnit.ok, QUnit.equal, Dexie__default["default"], db$4, Dexie.liveQuery).catch(function (err) { return QUnit.ok(false, 'final catch: ' + err); })]; + } + }); + }); }); + + QUnit.module("promise"); + //Dexie.debug = "dexie"; + function createDirectlyResolvedPromise() { + return new Dexie__default["default"].Promise(function (resolve) { + resolve(); + }); + } + QUnit.asyncTest("Promise basics", function () { + new Dexie__default["default"].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__default["default"].Promise(function (resolve) { return resolve("value"); }) + .then(function (value) { + return Dexie__default["default"].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__default["default"].Promise(function (resolve) { return resolve("value"); }) + .then(function (value) { + return new Dexie__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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__default["default"].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("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__default["default"]("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__default["default"].Promise.newPSD(function () { + Dexie__default["default"].Promise.PSD.hello = "promise land"; + Dexie__default["default"].Promise.resolve().then(function () { + QUnit.ok(!!Dexie__default["default"].Promise.PSD, "We should have a Dexie.Promise.PSD"); + QUnit.equal(Dexie__default["default"].Promise.PSD.hello, "promise land"); + }).catch(function (e) { + QUnit.ok(false, "Error: " + e); + }).finally(QUnit.start); + }); + }); + + QUnit.module("extendability"); + QUnit.asyncTest("recursive-pause", function () { + var db = new Dexie__default["default"]("TestDB"); + db.version(1).stores({ + activities: "Oid,Task,Tick,Tock,Type,Flags", + tasks: "Oid,Name,Parent" + }); + 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__default["default"].Promise.newPSD(function () { + Dexie__default["default"].currentTransaction._lock(); + db.activities.where("Type").equals(2).modify({ Flags: 2 }).finally(function () { + Dexie__default["default"].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__default["default"].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__default["default"].derive; + function Root() { } + function Branch1() { } + function Branch2() { } + derive(Branch1).from(Root); + derive(Branch2).from(Root); + var root = new Root(); + var branch1 = new Branch1(); + var branch2 = new Branch2(); + QUnit.ok(branch1 instanceof root.constructor, "branch1 instanceof root.constructor"); + QUnit.ok(branch2 instanceof root.constructor, "branch2 instanceof root.constructor"); + QUnit.ok(!(root instanceof branch1.constructor), "!(root instanceof branch1.constructor)"); + QUnit.ok(!(root instanceof branch2.constructor), "!(root instanceof branch2.constructor)"); + QUnit.ok(!(branch1 instanceof branch2.constructor), "!(branch1 instanceof branch2.constructor)"); + QUnit.ok(!(branch2 instanceof branch1.constructor), "!(branch2 instanceof branch1.constructor)"); + }); + + var Promise$1 = Dexie__default["default"].Promise, all = Promise$1.all, async = Dexie__default["default"].async; Dexie__default["default"].spawn; + var db$3 = new Dexie__default["default"]("TestDBCrudHooks"); + db$3.version(1).stores({ + table1: "id,idx", + table2: ",&idx", + table3: "++id,&idx", + table4: "++,&idx", + table5: "" + }); + var ourTables = [db$3.table1, db$3.table2, db$3.table3, db$3.table4, db$3.table5]; + var opLog = [], successLog = [], errorLog = [], watchSuccess = false, watchError = false, deliverKeys = [], deliverModifications = null, deliverKeys2 = [], deliverModifications2 = null, opLog2 = [], successLog2 = [], errorLog2 = [], 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(function reset() { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + unsubscribeHooks(); + return [4 /*yield*/, all(ourTables.map(function (table) { return table.clear(); }))]; + case 1: + _a.sent(); + subscrubeHooks(); + opLog = []; + successLog = []; + errorLog = []; + watchSuccess = false; + watchError = false; + deliverKeys = []; + deliverModifications = null; + deliverKeys2 = []; + deliverModifications2 = null; + opLog2 = []; + successLog2 = []; + errorLog2 = []; + transLog = []; + return [2 /*return*/]; + } + }); + }); + /*function stack() { + if (Error.captureStackTrace) { + let obj = {}; + Error.captureStackTrace(obj, stack); + return obj.stack; + } + var e = new Error(""); + if (e.stack) return e.stack; + try{throw e}catch(ex){return ex.stack || "";} + }*/ + function nop() { } + 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__default["default"].currentTransaction }); + var op = { + op: "create", + key: primKey, + value: Dexie__default["default"].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__default["default"].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__default["default"].deepClone(obj) + }); + return { theObject: obj }; + } + function reading2(obj) { + opLog2.push({ + op: "read", + obj: Dexie__default["default"].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 = function (updatedObj){} 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__default["default"].currentTransaction }); + var op = { + op: "update", + key: primKey, + obj: Dexie__default["default"].deepClone(obj), + mods: Dexie__default["default"].shallowClone(modifications), + }; + opLog.push(op); + if (watchSuccess) { + this.onsuccess = function (updatedObj) { return successLog.push(updatedObj); }; + } + 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 = function (updatedObj){} 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__default["default"].deepClone(obj), + mods: Dexie__default["default"].shallowClone(modifications) + }; + opLog2.push(op); + if (watchSuccess) { + this.onsuccess = function (updatedObj) { return successLog2.push(updatedObj); }; + } + 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__default["default"].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$3).then(function () { return reset(); }).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + unsubscribeHooks(); + } + }); + var expect = async(function (expected, modifyer) { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, reset()]; + case 1: + _a.sent(); + return [4 /*yield*/, modifyer()]; + case 2: + _a.sent(); + QUnit.equal(JSON.stringify(opLog, null, 2), JSON.stringify(expected.map(function (x) { return (__assign(__assign({}, x), { updatedObj: undefined })); }), null, 2), "Expected oplog: " + JSON.stringify(expected)); + QUnit.ok(transLog.every(function (x) { return x.trans && x.current === x.trans; }), "transaction argument is valid and same as Dexie.currentTransaction"); + return [4 /*yield*/, reset()]; + case 3: + _a.sent(); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 4: + _a.sent(); + QUnit.equal(errorLog.length + errorLog2.length, 0, "No errors should have been registered"); + QUnit.equal(successLog.length, expected.filter(function (op) { return op.op !== 'read'; }).length, "First hook got success events"); + QUnit.equal(successLog2.length, expected.filter(function (op) { return op.op !== 'read'; }).length, "Second hook got success events"); + expected.forEach(function (x, i) { + if (x.op === "create" && x.key !== undefined) { + QUnit.equal(successLog[i], x.key, "Success events got the correct key"); + QUnit.equal(successLog2[i], x.key, "Success events got the correct key (2)"); + } + if (x.op === "update") { + QUnit.equal(JSON.stringify(successLog[i]), JSON.stringify(x.updatedObj), "Success events got the updated object"); + QUnit.equal(JSON.stringify(successLog2[i]), JSON.stringify(x.updatedObj), "Success events got the updated object (2)"); + } + }); + if (!expected.some(function (x) { return x.op === "create" && x.key === undefined; })) return [3 /*break*/, 7]; + // Test to deliver prim key from both hooks and expect the second hook's key to win. + return [4 /*yield*/, reset()]; + case 5: + // Test to deliver prim key from both hooks and expect the second hook's key to win. + _a.sent(); + deliverKeys = expected.map(function (x, i) { return "Hook1Key" + i; }); + deliverKeys2 = expected.map(function (x, i) { return "Hook2Key" + i; }); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 6: + _a.sent(); + QUnit.equal(errorLog.length + errorLog2.length, 0, "No errors should have been registered"); + expected.forEach(function (x, i) { + if (x.op === "create" && x.key === undefined) { + QUnit.equal(opLog[i].key, expected[i].key, "First hook got expected key delivered"); + QUnit.equal(opLog2[i].key, deliverKeys[i], "Second hook got key delivered from first hook"); + QUnit.equal(successLog[i], deliverKeys2[i], "Success event got delivered key from hook2"); + QUnit.equal(successLog2[i], deliverKeys2[i], "Success event got delivered key from hook2 (2)"); + } + }); + _a.label = 7; + case 7: + if (!expected.some(function (x) { return x.op === "update"; })) return [3 /*break*/, 10]; + return [4 /*yield*/, reset()]; + case 8: + _a.sent(); + deliverModifications = { "someProp.someSubProp": "someValue" }; + return [4 /*yield*/, modifyer()]; + case 9: + _a.sent(); + expected.forEach(function (x, i) { + if (x.op === "update") { + QUnit.equal(JSON.stringify(opLog[i].obj), JSON.stringify(opLog2[i].obj), "Object has not yet been changed in hook2"); + QUnit.ok(Object.keys(opLog[i].mods).every(function (prop) { + return JSON.stringify(opLog[i].mods[prop]) === + JSON.stringify(opLog2[i].mods[prop]); + }), "All mods that were originally sent to hook1, are also sent to hook2"); + QUnit.ok("someProp.someSubProp" in opLog2[i].mods, "oplog2 got first hook's additional modifications"); + } + }); + _a.label = 10; + case 10: return [2 /*return*/]; + } + }); + }); + var verifyErrorFlows = async(function (modifyer) { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, reset()]; + case 1: + _a.sent(); + QUnit.ok(true, "Verifying ERROR flows"); + watchSuccess = true; + watchError = true; + return [4 /*yield*/, modifyer()]; + case 2: + _a.sent(); + QUnit.equal(opLog.length, opLog2.length, "Number of ops same for hook1 and hook2: " + opLog.length); + QUnit.equal(successLog.length + errorLog.length, opLog.length, "Either onerror or onsuccess must have been called for every op. onerror: " + + errorLog.length + ". onsuccess: " + successLog.length + ". opLog: " + JSON.stringify(opLog)); + QUnit.equal(successLog2.length + errorLog2.length, opLog2.length, "Either onerror or onsuccess must have been called for every op (hook2). onerror: " + + errorLog2.length + ". onsuccess: " + successLog2.length + ". opLog: " + JSON.stringify(opLog2)); + return [2 /*return*/]; + } + }); + }); + // + // + // Tests goes here... + // + // + // + // CREATING hook tests... + // + // Ways to produce CREATEs: + // Table.add() + // Table.put() + // Table.bulkAdd() + // Table.bulkPut() + spawnedTest("creating using Table.add()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 14 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + db$3.table1.add({ id: 1, idx: 11 }); + db$3.table2.add({ idx: 12 }, 2); + db$3.table3.add({ idx: 13 }); + db$3.table4.add({ idx: 14 }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$3.table1.add({ id: 1 }).catch(nop)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table2.add({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$3.table2.add({}, 1).catch(nop)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table1.add({ id: {} }).catch(nop)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("creating using Table.put()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 14 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + //console.log("Putting {id:1, idx: 11} into table1"); + return [4 /*yield*/, db$3.table1.put({ id: 1, idx: 11 })]; + case 1: + //console.log("Putting {id:1, idx: 11} into table1"); + _a.sent(); + //console.log("Putting {idx: 12} for key 2 into table2"); + return [4 /*yield*/, db$3.table2.put({ idx: 12 }, 2)]; + case 2: + //console.log("Putting {idx: 12} for key 2 into table2"); + _a.sent(); + //console.log("Putting {idx: 13} into table3"); + return [4 /*yield*/, db$3.table3.put({ idx: 13 })]; + case 3: + //console.log("Putting {idx: 13} into table3"); + _a.sent(); + //console.log("Putting {idx: 14} into table4"); + return [4 /*yield*/, db$3.table4.put({ idx: 14 })]; + case 4: + //console.log("Putting {idx: 14} into table4"); + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.put({ idx: 1 })]; + case 1: + _a.sent(); // success + return [4 /*yield*/, db$3.table3.put({ idx: 1 }).catch(nop)]; + case 2: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table2.put({}, 1)]; + case 3: + _a.sent(); // sucesss + return [4 /*yield*/, db$3.table2.put({}, 1).catch(nop)]; + case 4: + _a.sent(); // Trigger error event (constraint) + return [4 /*yield*/, db$3.table3.put({ id: {} }).catch(nop)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("creating using Table.bulkAdd()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 1.2, + value: { id: 1.2, idx: 11.2 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + key: 2.2, + value: { idx: 12.2 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 13.2 } + }, { + op: "create", + value: { idx: 14 } + }, { + op: "create", + value: { idx: 14.2 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + db$3.table1.bulkAdd([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }]); + db$3.table2.bulkAdd([{ idx: 12 }, { idx: 12.2 }], [2, 2.2]); + db$3.table3.bulkAdd([{ idx: 13 }, { idx: 13.2 }]); + db$3.table4.bulkAdd([{ idx: 14 }, { idx: 14.2 }]); + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.bulkAdd([{ id: 1 }, { id: 1 }]).catch(nop)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$3.table1.bulkAdd([{ id: 2 }, { id: 2 }, { id: 3 }]).catch(nop)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$3.table2.bulkAdd([{}, {}], [1, 1]).catch(nop)]; + case 3: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$3.table2.bulkAdd([{}, {}, {}], [2, 2, 3]).catch(nop)]; + case 4: + _a.sent(); // 1. success, 2. error event. 3. success. + return [4 /*yield*/, db$3.table1.bulkAdd([{ id: {} }]).catch(nop)]; + case 5: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("creating using Table.bulkPut()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, idx: 11 } + }, { + op: "create", + key: 1.2, + value: { id: 1.2, idx: 11.2 } + }, { + op: "create", + key: 2, + value: { idx: 12 } + }, { + op: "create", + key: 2.2, + value: { idx: 12.2 } + }, { + op: "create", + value: { idx: 13 } + }, { + op: "create", + value: { idx: 13.2 } + }, { + op: "create", + value: { idx: 14 } + }, { + op: "create", + value: { idx: 14.2 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.bulkPut([{ id: 1, idx: 11 }, { id: 1.2, idx: 11.2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table2.bulkPut([{ idx: 12 }, { idx: 12.2 }], [2, 2.2])]; + case 2: + _a.sent(); + return [4 /*yield*/, db$3.table3.bulkPut([{ idx: 13 }, { idx: 13.2 }])]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.table4.bulkPut([{ idx: 14 }, { idx: 14.2 }])]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.bulkPut([{ idx: 1 }, { idx: 1 }]).catch(nop)]; + case 1: + _a.sent(); // 1. success, 2. error event. + return [4 /*yield*/, db$3.table3.bulkPut([{ idx: 2 }, { idx: 2 }, { idx: 3 }]).catch(nop)]; + case 2: + _a.sent(); // 1. success, 2. error event., 3. success + return [4 /*yield*/, db$3.table1.bulkPut([{ id: {} }]).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + // + // READING hooks test + // Ways to produce READs: + // Table.get() + // Table.bulkGet() + // Collection.toArray() + // Collection.each() + // Collection.first() + // Collection.last() + // But not: + // Table.filter() / Collection.and() + spawnedTest("reading tests", function () { + var readOps, readOps2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { foo: "bar" } + }, { + op: "create", + key: 2, + value: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }, { + op: "read", + obj: { foo: "bar" } + }, { + op: "read", + obj: { fee: "bore" } + }], function () { return db$3.transaction('rw', 'table5', function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table5.bulkAdd([{ foo: "bar" }, { fee: "bore" }], [1, 2])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table5.toArray()]; + case 2: + _a.sent(); + return [4 /*yield*/, db$3.table5.reverse().each(function (x) { })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.table5.orderBy(':id').first()]; + case 4: + _a.sent(); + return [4 /*yield*/, db$3.table5.orderBy(':id').last()]; + case 5: + _a.sent(); + return [4 /*yield*/, db$3.table5.bulkGet([1, 2])]; + case 6: + _a.sent(); + return [4 /*yield*/, db$3.table5.filter(function (x) { return false; }).toArray()]; + case 7: + _a.sent(); + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + readOps = opLog.filter(function (o) { return o.op === 'read'; }), readOps2 = opLog2.filter(function (o) { return o.op === 'read'; }); + QUnit.ok(readOps.every(function (o, i) { + return JSON.stringify(readOps2[i].obj.theObject) === JSON.stringify(o.obj); + }), "hook2 should have got hook1's return value"); + return [2 /*return*/]; + } + }); + }); + // + // UPDATING hooks test + // Ways to produce UPDATEs: + // Table.put() + // Table.bulkPut() + // Table.update() + // Collection.modify() + spawnedTest("updating using Table.put()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + db$3.table1.put({ id: 1, address: { city: 'A' } }); // create + db$3.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.add({ id: 1, idx: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table3.put({ id: 2, idx: 1 }).catch(nop)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$3.table3.put({ id: {} }).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("updating using Table.bulkPut()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + db$3.table1.put({ id: 1, address: { city: 'A' } }); // create + db$3.table1.put({ id: 1, address: { city: 'B' } }); // update + return [2 /*return*/]; + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table4.add({ idx: 1 }, 1)]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table4.bulkPut([{ idx: 1 }], [2]).catch(nop)]; + case 2: + _a.sent(); // error event (DataError) + return [4 /*yield*/, db$3.table3.bulkPut([{}], [{}]).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception (invalid key type) + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("updating using Table.update()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.update(1, { "address.city": "B" })]; + case 2: + _a.sent(); // update + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table3.update(1, { idx: 2 }).catch(nop)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$3.table3.update(1, 3).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception? + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("updating using Collection.modify()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, address: { city: 'A' } } + }, { + op: "update", + key: 1, + obj: { id: 1, address: { city: 'A' } }, + mods: { "address.city": "B" }, + updatedObj: { id: 1, address: { city: 'B' } }, + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, address: { city: 'A' } })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.where('id').equals(1).modify({ "address.city": "B" })]; + case 2: + _a.sent(); // update + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [4 /*yield*/, verifyErrorFlows(function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table3.bulkAdd([{ id: 1, idx: 1 }, { id: 2, idx: 2 }])]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table3.where('id').equals(1).modify({ idx: 2 }).catch(nop)]; + case 2: + _a.sent(); // error event (constraint) + return [4 /*yield*/, db$3.table3.where('id').equals(1).modify(function () { throw "apa"; }).catch(nop)]; + case 3: + _a.sent(); // Trigger direct exception + return [2 /*return*/]; + } + }); + }).catch(nop); })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + // + // DELETING hook tests + // + // Ways to produce DELETEs: + // Table.delete(key) + // Table.bulkDetele(keys) + // Table.clear() + // Collection.modify() + // Collection.delete() + spawnedTest("deleting using Table.delete(key)", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.delete(1)]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Table.bulkDelete(key)", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.bulkDelete([1])]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Table.clear()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.clear()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Table.modify()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.where('id').between(0, 2).modify(function () { + delete this.value; + })]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + spawnedTest("deleting using Collection.delete()", function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "delete", + key: 1, + obj: { id: 1 } + }], function () { return db$3.transaction('rw', db$3.tables, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); // create + return [4 /*yield*/, db$3.table1.where('id').between(0, 2).delete()]; + case 2: + _a.sent(); // delete + return [2 /*return*/]; + } + }); + }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); + promisedTest("issue #1195 Update with array as value adds number objects", function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1 } + }, { + op: "update", + key: 1, + obj: { id: 1 }, + mods: { authors: [{ foo: "bar" }] }, + updatedObj: { id: 1, authors: [{ foo: "bar" }] }, + }, { + op: "update", + key: 1, + obj: { id: 1, authors: [{ foo: "bar" }] }, + mods: { authors: [] }, + updatedObj: { id: 1, authors: [] }, + }, { + op: "update", + key: 1, + obj: { id: 1, authors: [] }, + mods: { authors: [{ name: "foo" }, { name: "bar" }] }, + updatedObj: { id: 1, authors: [{ name: "foo" }, { name: "bar" }] }, + }], function () { return db$3.transaction('rw', db$3.table1, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [{ foo: "bar" }] })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [] })]; + case 3: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [{ name: "foo" }, { name: "bar" }] })]; + case 4: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("issue #1270 Modification object in updating hook not correct when changing array", function () { return __awaiter(void 0, void 0, void 0, function () { + var buffer1, buffer2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + // Test sub-array + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, authors: [{ name: "foo" }] } + }, { + op: "update", + key: 1, + obj: { id: 1, authors: [{ name: "foo" }] }, + mods: { authors: [{ name: "bar" }] }, + updatedObj: { id: 1, authors: [{ name: "bar" }] }, + }], function () { return db$3.transaction('rw', db$3.table1, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, authors: [{ name: "foo" }] })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, authors: [{ name: "bar" }] })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 1: + // Test sub-array + _a.sent(); + // Test sub-object + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, author: { name: "foo" } } + }, { + op: "update", + key: 1, + obj: { id: 1, author: { name: "foo" } }, + mods: { "author.name": "bar" }, + updatedObj: { id: 1, author: { name: "bar" } }, + }], function () { return db$3.transaction('rw', db$3.table1, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, author: { name: "foo" } })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, author: { name: "bar" } })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 2: + // Test sub-object + _a.sent(); + buffer1 = new Uint8Array(8).fill(1); + buffer2 = new Uint8Array(8).fill(2); + return [4 /*yield*/, expect([{ + op: "create", + key: 1, + value: { id: 1, author: { buf: buffer1 } } + }, { + op: "update", + key: 1, + obj: { id: 1, author: { buf: buffer1 } }, + mods: { "author.buf": buffer2 }, + updatedObj: { id: 1, author: { buf: buffer2 } }, + }], function () { return db$3.transaction('rw', db$3.table1, function () { return __awaiter(void 0, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, db$3.table1.add({ id: 1, author: { buf: buffer1 } })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$3.table1.put({ id: 1, author: { buf: buffer2 } })]; + case 2: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); })]; + case 3: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }); + + var db$2 = new Dexie__default["default"]("TestDBBinary"); + db$2.version(1).stores({ + items: "id" + }); + QUnit.module("blobs", { + setup: function () { + QUnit.stop(); + resetDatabase(db$2).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(void 0, void 0, void 0, function () { + var binaryData, blob, back, arrayBuffer, resultBinaryData; + return __generator(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$2.items.add({ id: 1, blob: blob })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.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(void 0, 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(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, , 5, 6]); + db$2.items.hook('updating', updatingHook); + binaryData = new Uint8Array([1, 2, 3, 4]); + blob = new Blob([binaryData], { type: 'application/octet-binary' }); + return [4 /*yield*/, db$2.items.add({ id: 1 })]; + case 1: + _a.sent(); + return [4 /*yield*/, db$2.items.put({ id: 1, blob: blob })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$2.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$2.items.hook('updating').unsubscribe(updatingHook); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }); + + var db$1 = new Dexie__default["default"]("TestDBBinaryKeys"); + db$1.version(1).stores({ + items: "id,data" + }); + db$1.on('populate', function () { + db$1.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$1).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + promisedTest('Binary Primary Key (Int32Array)', function () { return __awaiter(void 0, void 0, void 0, function () { + var id, back; + return __generator(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$1.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$1.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$1.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(void 0, void 0, void 0, function () { + var id, back; + return __generator(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$1.items.add({ id: id, data: "string" })]; + case 2: + _a.sent(); + return [4 /*yield*/, db$1.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$1.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(void 0, void 0, void 0, function () { + var _a, x; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!supports("binarykeys")) { + QUnit.ok(true, "This browser does not support IndexedDB 2.0"); + return [2 /*return*/]; + } + _a = QUnit.equal; + return [4 /*yield*/, db$1.items.where('data').equals(new Uint8Array([1, 2, 3])).count()]; + case 1: + _a.apply(void 0, [_b.sent(), 1, "Should be able to query on binary key"]); + return [4 /*yield*/, db$1.items.where('data') + .anyOf([new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])]) + .toArray()]; + case 2: + x = _b.sent(); + QUnit.equal(x.length, 2, "Should find both keys even though the second has another binary type (IndexedDB should not distinguish them)"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest('OR-query', function () { return __awaiter(void 0, void 0, void 0, function () { + var a; + return __generator(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$1.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$1.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$1.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*/]; + } + }); + }); }); + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var sortedJson = createCommonjsModule(function (module, exports) { + var NON_SORTABLE_TYPES = ['undefined', 'string', 'number', 'boolean', 'function']; + var DEFAULT_SORT_OPTIONS = { + sortBy : undefined, + sortKey : true, + sortArray: false, + + stringify: false, + replacer : null, + space : null, + }; + + var _sortify = function(obj, options) { + for (var i = 0; i < NON_SORTABLE_TYPES.length; i++) { + if (NON_SORTABLE_TYPES[i] === typeof obj || obj === null) { + return obj; + } + } + + if (Array.isArray(obj)) { + if (options.sortArray === true) { + obj.sort(options.sortBy); + } + + for (var i = 0; i < obj.length; i++) { + obj[i] = _sortify(obj[i], options); + } + + return obj; + + } else { + if (options.sortKey === true) { + var sortedObj = {}; + var keyList = []; + + for (var k in obj) { + keyList.push(k); + } + keyList.sort(options.sortBy); + + for (var i = 0; i < keyList.length; i++) { + var k = keyList[i]; + var v = obj[k]; + + sortedObj[k] = _sortify(v, options); + } + + return sortedObj; + + } else { + for (var k in obj) { + obj[k] = _sortify(obj[k], options); + } + + return obj; + } + } + }; + + exports.sortify = function(obj, options) { + if (!options) { + options = {}; + } + + for (var k in DEFAULT_SORT_OPTIONS) if (DEFAULT_SORT_OPTIONS.hasOwnProperty(k)) { + var v = DEFAULT_SORT_OPTIONS[k]; + + if (!(k in options)) { + options[k] = v; + } + } + + var result = _sortify(obj, options); + if (options.stringify === true) { + result = JSON.stringify(result, options.replacer, options.space); + } + + return result; + }; + + /* Deprecated Code below */ + var _stringify = function(obj, compareFunction) { + if (typeof obj == 'string') { + return '"' + obj + '"'; + } + else if (typeof obj == 'number') { + return obj; + } + else if (typeof obj == 'boolean') { + return obj; + } + else if (typeof obj == 'function') { + return '""'; + } + else if (typeof obj == 'object') { + if (Array.isArray(obj)) { + var parts = []; + for (var i = 0; i < obj.length; i++) { + var v = exports.stringify(obj[i], compareFunction); + parts.push(v); + } + + return '[' + parts.join(',') + ']'; + } + else { + var keyList = []; + for (var k in obj) { + keyList.push(k); + } + keyList.sort(compareFunction); + + var parts = []; + for (var i = 0; i < keyList.length; i++) { + var k = keyList[i]; + var v = exports.stringify(obj[k], compareFunction); + + parts.push('"' + k + '":' + v); + } + return '{' + parts.join(',') + '}'; + } + } + else { + return '""'; + } + }; + + exports.stringify = function(obj, compareFunction) { + console.log("The stringify() function is DEPRECATED. Please use sortify() instead."); + + return _stringify(obj, compareFunction); + }; + }); + sortedJson.sortify; + sortedJson.stringify; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isFunction(x) { + return typeof x === 'function'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var _enable_super_gross_mode_that_will_cause_bad_things = false; + var config = { + Promise: undefined, + set useDeprecatedSynchronousErrorHandling(value) { + if (value) { + var error = /*@__PURE__*/ new Error(); + /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); + } + _enable_super_gross_mode_that_will_cause_bad_things = value; + }, + get useDeprecatedSynchronousErrorHandling() { + return _enable_super_gross_mode_that_will_cause_bad_things; + }, + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function hostReportError(err) { + setTimeout(function () { throw err; }, 0); + } + + /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ + var empty = { + closed: true, + next: function (value) { }, + error: function (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + }, + complete: function () { } + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isObject(x) { + return x !== null && typeof x === 'object'; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { + function UnsubscriptionErrorImpl(errors) { + Error.call(this); + this.message = errors ? + errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; + this.name = 'UnsubscriptionError'; + this.errors = errors; + return this; + } + UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return UnsubscriptionErrorImpl; + })(); + var UnsubscriptionError = UnsubscriptionErrorImpl; + + /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ + var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parentOrParents = null; + this._subscriptions = null; + if (unsubscribe) { + this._ctorUnsubscribe = true; + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var errors; + if (this.closed) { + return; + } + var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parentOrParents = null; + this._subscriptions = null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } + } + if (isFunction(_unsubscribe)) { + if (_ctorUnsubscribe) { + this._unsubscribe = undefined; + } + try { + _unsubscribe.call(this); + } + catch (e) { + errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; + } + } + if (isArray(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (isObject(sub)) { + try { + sub.unsubscribe(); + } + catch (e) { + errors = errors || []; + if (e instanceof UnsubscriptionError) { + errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); + } + else { + errors.push(e); + } + } + } + } + } + if (errors) { + throw new UnsubscriptionError(errors); + } + }; + Subscription.prototype.add = function (teardown) { + var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (!(subscription instanceof Subscription)) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: { + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + } + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; + } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); + } + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; + }()); + function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var rxSubscriber = /*@__PURE__*/ (function () { + return typeof Symbol === 'function' + ? /*@__PURE__*/ Symbol('rxSubscriber') + : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); + })(); + + /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ + var Subscriber = /*@__PURE__*/ (function (_super) { + __extends(Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + switch (arguments.length) { + case 0: + _this.destination = empty; + break; + case 1: + if (!destinationOrNext) { + _this.destination = empty; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; + } + Subscriber.prototype[rxSubscriber] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parentOrParents = _parentOrParents; + return this; + }; + return Subscriber; + }(Subscription)); + var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (isFunction(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== empty) { + context = Object.create(observerOrNext); + if (isFunction(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + hostReportError(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + hostReportError(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!config.useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + hostReportError(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; + }(Subscriber)); + + /** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ + function canReportError(observer) { + while (observer) { + var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; + if (closed_1 || isStopped) { + return false; + } + else if (destination && destination instanceof Subscriber) { + observer = destination; + } + else { + observer = null; + } + } + return true; + } + + /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ + function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof Subscriber) { + return nextOrObserver; + } + if (nextOrObserver[rxSubscriber]) { + return nextOrObserver[rxSubscriber](); + } + } + if (!nextOrObserver && !error && !complete) { + return new Subscriber(empty); + } + return new Subscriber(nextOrObserver, error, complete); + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function identity(x) { + return x; + } + + /** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ + function pipeFromArray(fns) { + if (fns.length === 0) { + return identity; + } + if (fns.length === 1) { + return fns[0]; + } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; + } + + /** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ + var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = toSubscriber(observerOrNext, error, complete); + if (operator) { + sink.add(operator.call(sink, this.source)); + } + else { + sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (config.useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (canReportError(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[observable] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return pipeFromArray(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; + }()); + function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = config.Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; + } + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var subscribeToArray = function (array) { + return function (subscriber) { + for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { + subscriber.next(array[i]); + } + subscriber.complete(); + }; + }; + + /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ + function scheduleArray(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); + } + + /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ + function map(project, thisArg) { + return function mapOperation(source) { + if (typeof project !== 'function') { + throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); + } + return source.lift(new MapOperator(project, thisArg)); + }; + } + var MapOperator = /*@__PURE__*/ (function () { + function MapOperator(project, thisArg) { + this.project = project; + this.thisArg = thisArg; + } + MapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); + }; + return MapOperator; + }()); + var MapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MapSubscriber, _super); + function MapSubscriber(destination, project, thisArg) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.count = 0; + _this.thisArg = thisArg || _this; + return _this; + } + MapSubscriber.prototype._next = function (value) { + var result; + try { + result = this.project.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return MapSubscriber; + }(Subscriber)); + + /** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ + var subscribeToPromise = function (promise) { + return function (subscriber) { + promise.then(function (value) { + if (!subscriber.closed) { + subscriber.next(value); + subscriber.complete(); + } + }, function (err) { return subscriber.error(err); }) + .then(null, hostReportError); + return subscriber; + }; + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function getSymbolIterator() { + if (typeof Symbol !== 'function' || !Symbol.iterator) { + return '@@iterator'; + } + return Symbol.iterator; + } + var iterator = /*@__PURE__*/ getSymbolIterator(); + + /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ + var subscribeToIterable = function (iterable) { + return function (subscriber) { + var iterator$1 = iterable[iterator](); + do { + var item = void 0; + try { + item = iterator$1.next(); + } + catch (err) { + subscriber.error(err); + return subscriber; + } + if (item.done) { + subscriber.complete(); + break; + } + subscriber.next(item.value); + if (subscriber.closed) { + break; + } + } while (true); + if (typeof iterator$1.return === 'function') { + subscriber.add(function () { + if (iterator$1.return) { + iterator$1.return(); + } + }); + } + return subscriber; + }; + }; + + /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ + var subscribeToObservable = function (obj) { + return function (subscriber) { + var obs = obj[observable](); + if (typeof obs.subscribe !== 'function') { + throw new TypeError('Provided object does not correctly implement Symbol.observable'); + } + else { + return obs.subscribe(subscriber); + } + }; + }; + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); + + /** PURE_IMPORTS_START PURE_IMPORTS_END */ + function isPromise(value) { + return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; + } + + /** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ + var subscribeTo = function (result) { + if (!!result && typeof result[observable] === 'function') { + return subscribeToObservable(result); + } + else if (isArrayLike(result)) { + return subscribeToArray(result); + } + else if (isPromise(result)) { + return subscribeToPromise(result); + } + else if (!!result && typeof result[iterator] === 'function') { + return subscribeToIterable(result); + } + else { + var value = isObject(result) ? 'an invalid object' : "'" + result + "'"; + var msg = "You provided " + value + " where a stream was expected." + + ' You can provide an Observable, Promise, Array, or Iterable.'; + throw new TypeError(msg); + } + }; + + /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ + function scheduleObservable(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + var observable$1 = input[observable](); + sub.add(observable$1.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); + } + + /** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ + function schedulePromise(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); + })); + return sub; + }); + } + + /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ + function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); + } + return new Observable(function (subscriber) { + var sub = new Subscription(); + var iterator$1; + sub.add(function () { + if (iterator$1 && typeof iterator$1.return === 'function') { + iterator$1.return(); + } + }); + sub.add(scheduler.schedule(function () { + iterator$1 = input[iterator](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; + } + var value; + var done; + try { + var result = iterator$1.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } + })); + })); + return sub; + }); + } + + /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ + function isInteropObservable(input) { + return input && typeof input[observable] === 'function'; + } + + /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ + function isIterable(input) { + return input && typeof input[iterator] === 'function'; + } + + /** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ + function scheduled(input, scheduler) { + if (input != null) { + if (isInteropObservable(input)) { + return scheduleObservable(input, scheduler); + } + else if (isPromise(input)) { + return schedulePromise(input, scheduler); + } + else if (isArrayLike(input)) { + return scheduleArray(input, scheduler); + } + else if (isIterable(input) || typeof input === 'string') { + return scheduleIterable(input, scheduler); + } + } + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); + } + + /** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ + function from(input, scheduler) { + if (!scheduler) { + if (input instanceof Observable) { + return input; + } + return new Observable(subscribeTo(input)); + } + else { + return scheduled(input, scheduler); + } + } + + var db = new Dexie__default["default"]("TestLiveQuery", { + cache: 'immutable' // Using immutable cache in tests because it is most likely to fail if not using properly. + }); + db.version(2).stores({ + items: "id, name", + foo: "++id", + outbound: "++,name", + friends: "++id, name, age", + multiEntry: "id, *tags" + }); + db.on('populate', function () { + db.items.bulkAdd([ + { id: 1 }, + { id: 2 }, + { id: 3 } + ]); + db.outbound.bulkAdd([ + { num: 1, name: "A" }, + { num: 2, name: "B" }, + { num: 3, name: "C" } + ], [1, 2, 3]); + }); + function objectify(map) { + var rv = {}; + map.forEach(function (value, name) { + rv[name] = value; + }); + return rv; + } + function deepEqual(actual, expected, description) { + actual = JSON.parse(JSON.stringify(actual)); + expected = JSON.parse(JSON.stringify(expected)); + actual = sortedJson.sortify(actual, { sortArray: false }); + expected = sortedJson.sortify(expected, { sortArray: false }); + QUnit.equal(JSON.stringify(actual, null, 2), JSON.stringify(expected, null, 2), description); + } + function isDeepEqual(actual, expected, allowedExtra, prevActual) { + actual = deepClone(actual); + expected = deepClone(expected); + if (allowedExtra) + Array.isArray(allowedExtra) ? allowedExtra.forEach(function (key) { + if (actual[key]) + expected[key] = deepClone(prevActual[key]); + }) : Object.keys(allowedExtra).forEach(function (key) { + if (actual[key]) + expected[key] = deepClone(allowedExtra[key]); + }); + actual = sortedJson.sortify(actual, { sortArray: false }); + expected = sortedJson.sortify(expected, { sortArray: false }); + return JSON.stringify(actual, null, 2) === JSON.stringify(expected, null, 2); + } + var Signal = /** @class */ (function () { + function Signal() { + var _this = this; + this.promise = new Promise(function (resolve) { return _this.resolve = resolve; }); + } + return Signal; + }()); + QUnit.module("live-query", { + setup: function () { + QUnit.stop(); + resetDatabase(db).catch(function (e) { + QUnit.ok(false, "Error resetting database: " + e.stack); + }).finally(QUnit.start); + }, + teardown: function () { + } + }); + /*promisedTest("txcommitted event", async ()=>{ + let signal = new Signal(); + let os = {}; + function txCommitted(observabilitySet) { + Dexie.extendObservabilitySet(os, observabilitySet); + signal.resolve(observabilitySet); + } + await db.open(); + Dexie.on('txcommitted', txCommitted); + await db.transaction('rw', db.items, db.foo, async ()=>{ + await db.items.add({id: 4, name: "aiwo1"}); + await db.items.add({id: 7, name: "kjlj"}); + await db.foo.add({name: "jkll"}); + await db.items.update(1, {name: "A"}); + }); + while (!os.TestLiveQuery || !os.TestLiveQuery.items || !hasKey(os.TestLiveQuery.items.keys, 4)) { + // When Dexie.Observable is active, we might see intermediate transactions taking place + // before our transaction. + signal = new Signal(); + await signal.promise; + console.log("got new os:", os); + } + ok(!!os.TestLiveQuery, "Got changes in our table name TestLiveQuery"); + let itemsChanges = os.TestLiveQuery.items; + ok(itemsChanges, "Got changes for items table"); + deepEqual(itemsChanges.keys, rangeSet([[4], [7], [1]]), "Item changes on concattenated keys"); + deepEqual(itemsChanges.indexes, {"": rangeSet([[4],[7]]),name: rangeSet([["aiwo1"],["kjlj"],["A"]])}, "Index changes present"); + + // Foo changes (auto-incremented id) + let fooChanges = os.TestLiveQuery.foo; + ok(fooChanges, "Got changes for foo table"); + + os = {}; + let fooIds = await db.foo.toCollection().primaryKeys(); + await db.transaction('rw', db.items, db.foo, async ()=>{ + await db.items.update(4, {name: "aiwo2"}); + await db.foo.where('id').between(0, 1000).delete(); + }); + while (!os.TestLiveQuery || !os.TestLiveQuery.items || !hasKey(os.TestLiveQuery.items.keys, 4)) { + // When Dexie.Observable is active, we might see intermediate transactions taking place + // before our transaction. + signal = new Signal(); + await signal.promise; + } + itemsChanges = os.TestLiveQuery.items; + ok(hasKey(itemsChanges.keys, 4), "Item 4 was updated"); + ok(hasKey(itemsChanges.indexes.name, "aiwo1"), "Old value of name index were triggered"); + ok(hasKey(itemsChanges.indexes.name, "aiwo2"), "New value of name index were triggered"); + + fooChanges = os.TestLiveQuery.foo; + ok(!!fooChanges, "Foo table changed"); + if (hasKey(fooChanges.keys, 0) && hasKey(fooChanges.keys, 1000)) { + // Without addons: + deepEqual(fooChanges.keys, rangeSet([[0, 1000]]), "Got a range update of foo keys 0..1000"); + } else { + // With hooks / addons or browser workarounds: + deepEqual(fooChanges.keys, rangeSet(fooIds.map(id => [id])), "Got individual delete updates of foo keys ", fooIds.join(',')); + } + + Dexie.on('txcommitted').unsubscribe(txCommitted); + });*/ + promisedTest("subscribe to range", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal, subscription, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + signal = new Signal(); + subscription = Dexie.liveQuery(function () { return db.items.toArray(); }).subscribe(function (result) { + signal.resolve(result); + }); + return [4 /*yield*/, signal.promise]; + case 1: + result = _a.sent(); + deepEqual(result, [{ id: 1 }, { id: 2 }, { id: 3 }], "First callback should give initally populated content"); + signal = new Signal(); + db.items.add({ id: -1 }); + return [4 /*yield*/, signal.promise]; + case 2: + result = _a.sent(); + deepEqual(result, [{ id: -1 }, { id: 1 }, { id: 2 }, { id: 3 }], "2nd callback should give updated content"); + signal = new Signal(); + db.items.delete(2); + return [4 /*yield*/, signal.promise]; + case 3: + result = _a.sent(); + deepEqual(result, [{ id: -1 }, { id: 1 }, { id: 3 }], "3rd callback should wake up when deletion was made"); + subscription.unsubscribe(); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("subscribe to keys", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal1, signal2, count1, count2, sub1, res1, sub2, res2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (isIE) { + // The IE implementation becomes shaky here. + // Maybe becuase we launch several parallel queries to IDB. + QUnit.ok(true, "Skipping this test for IE - too shaky for the CI"); + return [2 /*return*/]; + } + signal1 = new Signal(), signal2 = new Signal(); + count1 = 0, count2 = 0; + sub1 = Dexie.liveQuery(function () { return db.items.get(1); }).subscribe(function (result) { + ++count1; + signal1.resolve(result); + }); + return [4 /*yield*/, signal1.promise]; + case 1: + res1 = _a.sent(); + QUnit.equal(res1.id, 1, "First result for ID 1 ok"); + QUnit.equal(count1, 1, "Callback called once"); + sub2 = Dexie.liveQuery(function () { return db.items.get(2); }).subscribe(function (result) { + ++count2; + signal2.resolve(result); + }); + return [4 /*yield*/, signal2.promise]; + case 2: + res2 = _a.sent(); + QUnit.equal(res2.id, 2, "2nd result for ID 2 ok"); + QUnit.equal(count2, 1, "2nd callback called once"); + QUnit.equal(count1, 1, "First callback wasn't called again"); + // Now mutate using update - verify listeners don't wake up on other than the keys the subscribe + signal1 = new Signal(); + signal2 = new Signal(); + return [4 /*yield*/, db.items.update(1, { name: "one" })]; + case 3: + _a.sent(); + QUnit.ok(true, "Could update item 1"); + return [4 /*yield*/, signal1.promise]; + case 4: + res1 = _a.sent(); + QUnit.equal(count1, 2, "First should have been called 2 times now"); + QUnit.equal(count2, 1, "2nd callback should still only have been called once"); + QUnit.equal(res1.name, "one", "We got the updated value from the expression"); + return [4 /*yield*/, db.items.update(2, { name: "two" })]; + case 5: + _a.sent(); + return [4 /*yield*/, signal2.promise]; + case 6: + res2 = _a.sent(); + QUnit.equal(count1, 2, "First should have been called 2 times now"); + QUnit.equal(count2, 2, "2nd callback should have been called twice also"); + QUnit.equal(res2.name, "two", "We got the updated value from the 2nd expression"); + // Now mutate using delete + signal1 = new Signal(); + signal2 = new Signal(); + return [4 /*yield*/, db.items.delete(1)]; + case 7: + _a.sent(); + return [4 /*yield*/, signal1.promise]; + case 8: + res1 = _a.sent(); + QUnit.equal(count1, 3, "First should have been called 3 times now"); + QUnit.equal(count2, 2, "2nd callback should still only have been called twice"); + QUnit.ok(res1 === undefined, "The updated result of db.items.get(1) should return undefined after the deletion"); + return [4 /*yield*/, db.items.delete(2)]; + case 9: + _a.sent(); + return [4 /*yield*/, signal2.promise]; + case 10: + res2 = _a.sent(); + QUnit.equal(count1, 3, "First should still have been called 3 times"); + QUnit.equal(count2, 3, "2nd callback should have been called 3 times also now"); + QUnit.ok(res2 === undefined, "The updated result of db.items.get(2) should return undefined after the deletion"); + // Verify that no more callbacks are called after unsubscribing + sub1.unsubscribe(); + sub2.unsubscribe(); + return [4 /*yield*/, db.items.update(1, { name: "fljkds" })]; + case 11: + _a.sent(); + QUnit.equal(count1, 3, "No more calls after having unsubscribed"); + return [4 /*yield*/, db.items.update(1, { name: "sfdfs" })]; + case 12: + _a.sent(); + QUnit.equal(count1, 3, "Just double-checking - no more calls after having unsubscribed"); + return [2 /*return*/]; + } + }); + }); }); + promisedTest("subscribe and error occur", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal, subscription, result; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + signal = new Signal(); + subscription = Dexie.liveQuery(function () { return db.items.get(NaN); } // NaN is not a valid key + ).subscribe({ + next: function (result) { return signal.resolve("success"); }, + error: function (result) { return signal.resolve("error"); }, + complete: function () { return signal.resolve("complete"); } + }); + QUnit.ok(!subscription.closed, "Subscription should not yet be closed"); + return [4 /*yield*/, signal.promise]; + case 1: + result = _a.sent(); + QUnit.equal(result, "error", "The observable's error callback should have been called"); + //No. Should not close errored subscriptions. What if they did a fetch call in it that failed? SHould keep subscribing. + //ok(subscription.closed, "Subscription should have been closed after error has occurred"); + subscription.unsubscribe(); + return [2 /*return*/]; + } + }); + }); }); + /* Use cases to cover: + + Queries + get + getMany + query + queryKeys + itemsStartsWithAOffset3 + openKeyCursor + count + queryOutbound + queryOutboundByPKey + openCursorOutbound + + Mutations + add + addAuto + update + delete + deleteRange + */ + var abbaKey = 0; + var lastFriendId = 0; + var barbarFriendId = 0; + var fruitCount = 0; // A bug in Safari <= 13.1 makes it unable to count on the name index (adds 1 extra) + var bulkFriends = []; + for (var i = 0; i < 51; ++i) { + bulkFriends.push({ name: "name".concat(i), age: i }); + } + var bulkOutbounds = []; + for (var i = 0; i < 51; ++i) { + bulkOutbounds.push({ name: "z" + i.toLocaleString('en-US', { + minimumIntegerDigits: 2, + useGrouping: false + }) }); + } + var mutsAndExpects = function () { return [ + // add + [ + function () { return db.items.add({ id: -1, name: "A" }); }, + { + itemsToArray: [{ id: -1, name: "A" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "A" }], + itemsStartsWithA: [{ id: -1, name: "A" }], + itemsStartsWithAPrimKeys: [-1], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: ["A"], + itemsStartsWithACount: fruitCount + 1 + } + ], + // addAuto + [ + function () { return db.outbound.add({ name: "Abba" }).then(function (id) { return abbaKey = id; }); }, + { + outboundToArray: [{ num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }, { name: "Abba" }], + outboundStartsWithA: [{ name: "A", num: 1 }, { name: "Abba" }] + } + ], [ + function () { return db.outbound.bulkAdd([{ name: "Benny" }, { name: "C" }], [-1, 0]); }, + { + outboundToArray: [{ name: "Benny" }, { name: "C" }, { num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }, { name: "Abba" }], + outboundIdBtwnMinus1And2: [{ name: "Benny" }, { name: "C" }, { name: "A", num: 1 }, { name: "B", num: 2 }], + outboundAnyOf_BCD_keys: ["B", "C", "C"] + } + ], + // update + [ + function () { return db.outbound.update(abbaKey, { name: "Zlatan" }); }, + { + outboundToArray: [{ name: "Benny" }, { name: "C" }, { num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }, { name: "Zlatan" }], + outboundStartsWithA: [{ name: "A", num: 1 }] + } + ], + [ + // Testing that keys-only queries don't get bothered + function () { return db.items.update(-1, { foo: "bar" }); }, + { + itemsToArray: [{ id: -1, name: "A", foo: "bar" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "A", foo: "bar" }], + itemsStartsWithA: [{ id: -1, name: "A", foo: "bar" }], + //itemsStartsWithAPrimKeys: [-1], should not have to be updated! + //itemsStartsWithAKeys: ["A"] should not have to be updated! + } + ], + [ + // Update an index property (name) should trigger + // listeners to that index: + function () { return db.items.update(-1, { foo: undefined, name: "B" }); }, + { + itemsToArray: [{ id: -1, name: "B" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "B" }], + itemsStartsWithA: [], + itemsStartsWithAPrimKeys: [], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: [], + itemsStartsWithACount: fruitCount + } + ], + [ + // Restoring and re-checking. + function () { return db.items.update(-1, { name: "A" }); }, + { + itemsToArray: [{ id: -1, name: "A" }, { id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, { id: -1, name: "A" }], + itemsStartsWithA: [{ id: -1, name: "A" }], + itemsStartsWithAPrimKeys: [-1], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: ["A"], + itemsStartsWithACount: fruitCount + 1 + } + ], + // add again + [ + function () { return db.items.bulkAdd([{ id: 4, name: "Abbot" }, { id: 5, name: "Assot" }, { id: 6, name: "Ambros" }]).then(function (lastId) { }); }, + { + itemsToArray: [{ id: -1, name: "A" }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5, name: "Assot" }, { id: 6, name: "Ambros" }], + itemsStartsWithA: [{ id: -1, name: "A" }, { id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }, { id: 5, name: "Assot" }], + itemsStartsWithAPrimKeys: [-1, 4, 6, 5], + itemsStartsWithAOffset3: [{ id: 5, name: "Assot" }], + itemsStartsWithAKeys: ["A", "Abbot", "Ambros", "Assot"], + itemsStartsWithACount: fruitCount + 4 + } + ], + // delete: + [ + function () { return db.transaction('rw', db.items, db.outbound, function () { + db.items.delete(-1); + }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5, name: "Assot" }, { id: 6, name: "Ambros" }], + itemsGet1And2: [{ id: 1 }, null], + itemsStartsWithA: [{ id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }, { id: 5, name: "Assot" }], + itemsStartsWithAPrimKeys: [4, 6, 5], + itemsStartsWithAKeys: ["Abbot", "Ambros", "Assot"], + itemsStartsWithACount: fruitCount + 3 + }, + // Allowed extras: + // If hooks is listened to we'll get an even more correct update of the itemsStartsWithAOffset3 query + // since oldVal will be available and offset-queries will be correcly triggered for deleted index keys before the offset. + { + itemsStartsWithAOffset3: [] + } + ], + // Special case for more fine grained keys observation of put (not knowing oldObjs + [ + function () { return db.items.put({ id: 5, name: "Azlan" }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5, name: "Azlan" }, { id: 6, name: "Ambros" }], + itemsStartsWithA: [{ id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }, { id: 5, name: "Azlan" }], + itemsStartsWithAKeys: ["Abbot", "Ambros", "Azlan"], + }, { + // Things that optionally can be matched in result (if no hooks specified): + itemsStartsWithAPrimKeys: [4, 6, 5], + itemsStartsWithACount: fruitCount + 3, + itemsStartsWithAOffset3: [] + } + ], + [ + function () { return db.transaction('rw', db.items, db.outbound, function () { + db.items.bulkPut([{ id: 5 }]); + }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 5 }, { id: 6, name: "Ambros" }], + itemsStartsWithA: [{ id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }], + itemsStartsWithAPrimKeys: [4, 6], + itemsStartsWithAKeys: ["Abbot", "Ambros"], + itemsStartsWithACount: fruitCount + 2 + }, { + itemsStartsWithAOffset3: [] // This is + } + ], + [ + function () { return db.transaction('rw', db.items, db.outbound, function () { + db.items.delete(5); + db.outbound.bulkDelete([abbaKey, -1, 0]); + }); }, + { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4, name: "Abbot" }, { id: 6, name: "Ambros" }], + // (allOutbound was: + // [{name:"Benny"},{name: "C"},{num:1,name:"A"},{num:2,name:"B"},{num:3,name:"C"},{name:"Zlatan"}]) + // ) + outboundToArray: [{ num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }], + //outboundStartsWithA: [{num:1,name:"A"}], + outboundIdBtwnMinus1And2: [{ num: 1, name: "A" }, { num: 2, name: "B" }], + outboundAnyOf_BCD_keys: ["B", "C"] + }, [ + "itemsStartsWithACount" + ] + ], + [ + function () { return db.friends.add({ name: "Foo", age: 20 }).then(function (id) { return lastFriendId = id; }); }, + { + friendsOver18: [{ get id() { return lastFriendId; }, name: "Foo", age: 20 }] + } + ], + [ + function () { return db.friends.put({ name: "Barbar", age: 21 }).then(function (id) { return barbarFriendId = id; }); }, + { + friendsOver18: [ + { get id() { return lastFriendId; }, name: "Foo", age: 20 }, + { get id() { return barbarFriendId; }, name: "Barbar", age: 21 } + ] + } + ], + [ + // bulkPut + function () { return db.friends.bulkPut(bulkFriends, { allKeys: true }).then(function (ids) { + // Record the actual ids here + for (var i = 0; i < ids.length; ++i) { + bulkFriends[i].id = ids[i]; + } + }); }, + { + friendsOver18: __spreadArray([ + { get id() { return lastFriendId; }, name: "Foo", age: 20 }, + { get id() { return barbarFriendId; }, name: "Barbar", age: 21 } + ], __read(bulkFriends.map(function (f) { return ({ name: f.name, age: f.age, get id() { return f.id; } }); }).filter(function (f) { return f.age > 18; })), false).sort(function (a, b) { return a.age - b.age; }) + } + ], + // bulkPut over 50 items on an outbound table: + [ + function () { return db.outbound.bulkPut(bulkOutbounds); }, + { + outboundToArray: __spreadArray([{ num: 1, name: "A" }, { num: 2, name: "B" }, { num: 3, name: "C" }], __read(bulkOutbounds), false), + outbound_above_z49: __spreadArray([], __read(bulkOutbounds.filter(function (o) { return o.name > "z49"; })), false) + }, ["outboundStartsWithA", "outboundIdBtwnMinus1And2", "outboundAnyOf_BCD_keys"] + ], + // deleteRange + [ + function () { return db.friends.where('id').between(0, barbarFriendId, true, true).delete(); }, + { + friendsOver18: __spreadArray([], __read(bulkFriends.filter(function (f) { return f.age > 18; })), false) + } + ], + // bulkDelete + [ + // Delete all but one: + function () { return db.friends.bulkDelete(bulkFriends.filter(function (f) { return f.age !== 20; }).map(function (f) { return f.id; })); }, + { + friendsOver18: __spreadArray([], __read(bulkFriends.filter(function (f) { return f.age === 20; })), false) + } + ], + // multiEntry + [ + function () { return db.multiEntry.add({ id: 1, tags: ["fooTag", "Apa"] }); }, + { + multiEntry1: [1], + multiEntry2: [1] + } + ], + [ + function () { return db.multiEntry.bulkPut([ + { id: 1, tags: [] }, + { id: 2, tags: ["Apa", "x", "y"] }, + { id: 3, tags: ["barTag", "fooTag"] } + ]); }, + { + multiEntry1: [2], + multiEntry2: [3] + } + ] + ]; }; + promisedTest("Full use case matrix", function () { return __awaiter(void 0, void 0, void 0, function () { + function zeroFlyers(abortSignal) { + return new Promise(function (resolve, reject) { + eventTarget.addEventListener('zeroflyers', resolve, { once: true }); + abortSignal.addEventListener('abort', function () { return reject(new Error('flyers timeout')); }, { once: true }); + }); + } + function timeout(ms) { + var ac = new AbortController(); + setTimeout(function () { return ac.abort(); }, ms); + return ac.signal; + } + function allValuesOk(actual, expected, allowedExtra, prevActual, abortSignal) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(flyingNow > 0)) return [3 /*break*/, 2]; + return [4 /*yield*/, zeroFlyers(abortSignal)]; + case 1: + _a.sent(); + return [3 /*break*/, 0]; + case 2: + if (!!isDeepEqual(actual, expected, allowedExtra, prevActual)) return [3 /*break*/, 4]; + return [4 /*yield*/, zeroFlyers(abortSignal)]; + case 3: + _a.sent(); + return [3 /*break*/, 2]; + case 4: return [2 /*return*/]; + } + }); + }); + } + var queries, expectedInitialResults, flyingNow, eventTarget, actualResults, observables, subscriptions, prevActual_1, _loop_1, _a, _b, _c, mut, expects, allowedExtra, e_1_1; + var e_1, _d; + return __generator(this, function (_e) { + switch (_e.label) { + case 0: return [4 /*yield*/, db.items.where('name').startsWith('A').count()]; + case 1: + // A bug in Safari <= 13.1 makes it unable to count on the name index (adds 1 extra) + fruitCount = _e.sent(); + if (fruitCount > 0) + console.log("fruitCount: " + fruitCount); + if (isIE) { + // The IE implementation becomes shaky here. + // Maybe becuase we launch several parallel queries to IDB. + QUnit.ok(true, "Skipping this test for IE - too shaky for the CI"); + return [2 /*return*/]; + } + queries = { + itemsToArray: function () { return db.items.toArray(); }, + itemsGet1And2: function () { return Promise.all(db.items.get(1), db.items.get(-1)); }, + itemsBulkGet123: function () { return db.items.bulkGet([1, 2, 3]); }, + itemsStartsWithA: function () { return db.items.where('name').startsWith("A").toArray(); }, + itemsStartsWithAPrimKeys: function () { return db.items.where('name').startsWith("A").primaryKeys(); }, + itemsStartsWithAOffset3: function () { return db.items.where('name').startsWith("A").offset(3).toArray(); }, + itemsStartsWithAKeys: function () { return db.items.where('name').startsWith("A").keys(); }, + itemsStartsWithACount: function () { return db.items.where('name').startsWith("A").count(); }, + outboundToArray: function () { return db.outbound.toArray(); }, + outboundStartsWithA: function () { return db.outbound.where('name').startsWith("A").toArray(); }, + outboundIdBtwnMinus1And2: function () { return db.outbound.where(':id').between(-1, 2, true, true).toArray(); }, + outboundAnyOf_BCD_keys: function () { return db.outbound.where('name').anyOf("B", "C", "D").keys(); }, + outbound_above_z49: function () { return db.outbound.where('name').above("z49").toArray(); }, + friendsOver18: function () { return db.friends.where('age').above(18).toArray(); }, + multiEntry1: function () { return db.multiEntry.where('tags').startsWith('A').primaryKeys(); }, + multiEntry2: function () { return db.multiEntry.where({ tags: "fooTag" }).primaryKeys(); } + }; + expectedInitialResults = { + itemsToArray: [{ id: 1 }, { id: 2 }, { id: 3 }], + itemsGet1And2: [{ id: 1 }, undefined], + itemsBulkGet123: [{ id: 1 }, { id: 2 }, { id: 3 }], + itemsStartsWithA: [], + itemsStartsWithAPrimKeys: [], + itemsStartsWithAOffset3: [], + itemsStartsWithAKeys: [], + itemsStartsWithACount: fruitCount, + outboundToArray: [ + { num: 1, name: "A" }, + { num: 2, name: "B" }, + { num: 3, name: "C" } + ], + outboundStartsWithA: [{ num: 1, name: "A" }], + outboundIdBtwnMinus1And2: [{ num: 1, name: "A" }, { num: 2, name: "B" }], + outboundAnyOf_BCD_keys: ["B", "C"], + outbound_above_z49: [], + friendsOver18: [], + multiEntry1: [], + multiEntry2: [] + }; + flyingNow = 0; + eventTarget = new EventTarget(); + actualResults = objectify(new Map(Object.keys(queries).map(function (name) { return [name, undefined]; }))); + observables = new Map(Object.keys(queries).map(function (name) { return [ + name, + Dexie.liveQuery(function () { return __awaiter(void 0, void 0, void 0, function () { + var res; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + ++flyingNow; + _a.label = 1; + case 1: + _a.trys.push([1, , 3, 4]); + return [4 /*yield*/, queries[name]()]; + case 2: + res = _a.sent(); + console.log("Setting actual result of ".concat(name, " to ").concat(JSON.stringify(res))); + actualResults[name] = res; + return [2 /*return*/, res]; + case 3: + if (--flyingNow === 0) + eventTarget.dispatchEvent(new CustomEvent('zeroflyers')); + return [7 /*endfinally*/]; + case 4: return [2 /*return*/]; + } + }); + }); }) + ]; })); + subscriptions = Object.keys(queries).map(function (name) { return observables.get(name).subscribe({ + next: function (res) { }, + error: function (error) { return QUnit.ok(false, '' + error); } + }); }); + _e.label = 2; + case 2: + _e.trys.push([2, , 12, 13]); + return [4 /*yield*/, zeroFlyers(timeout(200))]; + case 3: + _e.sent(); + deepEqual(actualResults, expectedInitialResults, "Initial results as expected"); + prevActual_1 = Dexie__default["default"].deepClone(actualResults); + _loop_1 = function (mut, expects, allowedExtra) { + var expected; + return __generator(this, function (_g) { + switch (_g.label) { + case 0: + console.log("RUNNING: ".concat(mut.toString())); + console.log("---------------------------------"); + actualResults = {}; + return [4 /*yield*/, mut()]; + case 1: + _g.sent(); + _g.label = 2; + case 2: + _g.trys.push([2, 4, , 5]); + return [4 /*yield*/, allValuesOk(actualResults, expects, allowedExtra, prevActual_1, timeout(200))]; + case 3: + _g.sent(); + return [3 /*break*/, 5]; + case 4: + _g.sent(); + return [3 /*break*/, 5]; + case 5: + expected = Dexie__default["default"].deepClone(expects); + if (allowedExtra) + Array.isArray(allowedExtra) ? allowedExtra.forEach(function (key) { + if (actualResults[key]) + expected[key] = prevActual_1[key]; + }) : Object.keys(allowedExtra).forEach(function (key) { + if (actualResults[key]) + expected[key] = allowedExtra[key]; + }); + deepEqual(actualResults, expected, "".concat(mut.toString())); + Object.assign(prevActual_1, actualResults); + return [2 /*return*/]; + } + }); + }; + _e.label = 4; + case 4: + _e.trys.push([4, 9, 10, 11]); + _a = __values(mutsAndExpects()), _b = _a.next(); + _e.label = 5; + case 5: + if (!!_b.done) return [3 /*break*/, 8]; + _c = __read(_b.value, 3), mut = _c[0], expects = _c[1], allowedExtra = _c[2]; + return [5 /*yield**/, _loop_1(mut, expects, allowedExtra)]; + case 6: + _e.sent(); + _e.label = 7; + case 7: + _b = _a.next(); + return [3 /*break*/, 5]; + case 8: return [3 /*break*/, 11]; + case 9: + e_1_1 = _e.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 11]; + case 10: + try { + if (_b && !_b.done && (_d = _a.return)) _d.call(_a); + } + finally { if (e_1) throw e_1.error; } + return [7 /*endfinally*/]; + case 11: return [3 /*break*/, 13]; + case 12: + subscriptions.forEach(function (s) { return s.unsubscribe(); }); + return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); }); + promisedTest("RxJS compability", function () { return __awaiter(void 0, void 0, void 0, function () { + var signal, o, s, result, res2; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + signal = new Signal(); + o = from(Dexie.liveQuery(function () { return db.items.toArray(); })).pipe(map(function (items) { return items.map(function (item) { return item.id; }); })); + s = o.subscribe(function (results) { return signal.resolve(results); }); + return [4 /*yield*/, signal.promise]; + case 1: + result = _a.sent(); + deepEqual(result, [1, 2, 3], "We should have get a mapped result"); + signal = new Signal(); + db.items.add({ id: 4 }); + return [4 /*yield*/, signal.promise]; + case 2: + res2 = _a.sent(); + deepEqual(res2, [1, 2, 3, 4], "We should have get an updated mapped result"); + s.unsubscribe(); + return [2 /*return*/]; + } + }); + }); }); + + // Implementation of https://www.w3.org/TR/IndexedDB-3/#compare-two-keys + // ... with the adjustment to return NaN instead of throwing. + function cmp(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === 'Array') + return 1; + if (tb === 'Array') + return -1; + if (ta === 'binary') + return 1; + if (tb === 'binary') + return -1; + if (ta === 'string') + return 1; + if (tb === 'string') + return -1; + if (ta === 'Date') + return 1; + if (tb !== 'Date') + return NaN; + return -1; + } + switch (ta) { + case 'number': + case 'Date': + case 'string': + return a > b ? 1 : a < b ? -1 : 0; + case 'binary': { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case 'Array': + return compareArrays(a, b); + } + } + catch (_a) { } + return NaN; // Return value if any given args are valid keys. + } + function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + // Implementation of https://www.w3.org/TR/IndexedDB-3/#key-type + function type(x) { + var t = typeof x; + if (t !== 'object') + return t; + if (ArrayBuffer.isView(x)) + return 'binary'; + var tsTag = toStringTag(x); // Cannot use instanceof in Safari + return tsTag === 'ArrayBuffer' ? 'binary' : tsTag; + } + function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + // TypedArray or DataView + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); // ArrayBuffer + } + + var _a; + /* An interval tree implementation to efficiently detect overlapping ranges of queried indexes. + * + * https://en.wikipedia.org/wiki/Interval_tree + * + */ + function isEmptyRange(node) { + return !("from" in node); + } + var RangeSet = function (fromOrTree, to) { + if (this) { + // Called with new() + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } + else { + // Called without new() + var rv = new RangeSet(); + if (fromOrTree && ("d" in fromOrTree)) { + extend(rv, fromOrTree); + } + return rv; + } + }; + props(RangeSet.prototype, (_a = { + add: function (rangeSet) { + mergeRanges(this, rangeSet); + return this; + }, + addKey: function (key) { + addRange(this, key, key); + return this; + }, + addKeys: function (keys) { + var _this = this; + keys.forEach(function (key) { return addRange(_this, key, key); }); + return this; + } + }, + _a[iteratorSymbol] = function () { + return getRangeSetIterator(this); + }, + _a)); + function addRange(target, from, to) { + var diff = cmp(from, to); + // cmp() returns NaN if one of the args are IDB-invalid keys. + // Avoid storing invalid keys in rangeset: + if (isNaN(diff)) + return; + // Caller is trying to add a range where from is greater than to: + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from: from, to: to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp(to, target.from) < 0) { + left + ? addRange(left, from, to) + : (target.l = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + if (cmp(from, target.to) > 0) { + right + ? addRange(right, from, to) + : (target.r = { from: from, to: to, d: 1, l: null, r: null }); + return rebalance(target); + } + // Now we have some kind of overlap. We will be able to merge the new range into the node or let it be swallowed. + // Grow left? + if (cmp(from, target.from) < 0) { + target.from = from; + target.l = null; // Cut off for now. Re-add later. + target.d = right ? right.d + 1 : 1; + } + // Grow right? + if (cmp(to, target.to) > 0) { + target.to = to; + target.r = null; // Cut off for now. Re-add later. + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + // Re-add left? + if (left && !target.l) { + //Ranges to the left may be swallowed. Cut it of and re-add all. + //Could probably be done more efficiently! + mergeRanges(target, left); + } + // Re-add right? + if (right && rightWasCutOff) { + //Ranges to the right may be swallowed. Cut it of and re-add all. + //Could probably be done more efficiently! + mergeRanges(target, right); + } + } + function mergeRanges(target, newSet) { + function _addRangeSet(target, _a) { + var from = _a.from, to = _a.to, l = _a.l, r = _a.r; + addRange(target, from, to); + if (l) + _addRangeSet(target, l); + if (r) + _addRangeSet(target, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); + } + function rangesOverlap(rangeSet1, rangeSet2) { + // Start iterating other from scratch. + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + // Start iterating this from start of other + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); // Start from beginning of other range + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp(b.from, a.to) <= 0 && cmp(b.to, a.from) >= 0) + return true; + cmp(a.from, b.from) < 0 + ? (a = (nextResult1 = i1.next(b.from)).value) // a is behind. forward it to beginning of next b-range + : (b = (nextResult2 = i2.next(a.from)).value); // b is behind. forward it to beginning of next a-range + } + return false; + } + function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function (key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + // Initial state for node. + // Fast forward to leftmost node. + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } + else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + // intentionally fall into case 1: + case 1: + // We're on a node where it's left part is already handled or does not exist. + state.s = 2; + if (!keyProvided || cmp(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + // We've emitted our node and should continue with the right part or let parent take over from it's state 1 + if (state.n.r) { + state.s = 3; // So when child is done, we know we're done. + state = { up: state, n: state.n.r, s: 0 }; + continue; // Will fall in to case 0 with fast forward to left leaf of this subtree. + } + // intentionally fall into case 3: + case 3: + state = state.up; + } + } + return { done: true }; + }, + }; + } + function rebalance(target) { + var _a, _b; + var diff = (((_a = target.r) === null || _a === void 0 ? void 0 : _a.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + // Rotate (https://en.wikipedia.org/wiki/Tree_rotation) + // + // + // [OLDROOT] + // [OLDROOT.L] [NEWROOT] + // [NEWROOT.L] [NEWROOT.R] + // + // Is going to become: + // + // + // [NEWROOT] + // [OLDROOT] [NEWROOT.R] + // [OLDROOT.L] [NEWROOT.L] + // * clone now has the props of OLDROOT + // Plan: + // * target must be given the props of NEWROOT + // * target[l] must point to a new OLDROOT + // * target[r] must point to NEWROOT.R + // * OLDROOT[r] must point to NEWROOT.L + var l = r === "r" ? "l" : "r"; // Support both left/right rotation + var rootClone = __assign({}, target); + // We're gonna copy props from target's right node into target so that target will + // have same range as old target[r] (instead of changing pointers, we copy values. + // that way we do not need to adjust pointers in parents). + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); + } + function computeDepth(_a) { + var r = _a.r, l = _a.l; + return (r ? (l ? Math.max(r.d, l.d) : r.d) : l ? l.d : 0) + 1; + } + + QUnit.module("rangeset"); + QUnit.test("it should do match correctly", function () { + var set = new RangeSet() + .add({ from: 1, to: 1 }) + .add({ from: 2, to: 10 }) + .add({ from: 20, to: 30 }) + .add({ from: 40, to: 40 }); + QUnit.ok(!rangesOverlap(set, new RangeSet(1.1, 1.9)), "set does not overlap with 1.1-1.9"); + QUnit.ok(rangesOverlap(set, new RangeSet(1, 1)), "set overlaps with 1-1"); + QUnit.ok(rangesOverlap(set, new RangeSet(0, 1)), "set overlaps with 0-1"); + QUnit.ok(!rangesOverlap(set, new RangeSet(0, 0.9)), "set doesnt overlap with 0-0.9"); + QUnit.ok(rangesOverlap(set, new RangeSet(39, 41)), "set overlaps with 39-40"); + }); + QUnit.test("it should balance itself", function () { + var set = new RangeSet(); + for (var i = 0; i < 10000; ++i) { + set.add({ from: i, to: i + 0.5 }); + } + QUnit.ok(!isNaN(set.d) && set.d <= 14 && set.d >= 1, "Depth should be below or equal to 14"); + set.add({ from: 0, to: 10000 }); + QUnit.equal(set.d, 1, "After adding a super range, the depth should be 1"); + QUnit.equal(__spreadArray([], __read(set), false).length, 1, "After adding the super range, the entire set should just contain the super set"); + }); + QUnit.test("it should be iterable", function () { + var set = new RangeSet(); + for (var i = 0; i < 10; ++i) { + set.addKey(i); + } + QUnit.equal(__spreadArray([], __read(set), false).length, 10, "Should iterate 10 items"); + QUnit.ok(__spreadArray([], __read(set), false).every(function (node, i) { return node.from === i && node.to === i; }), "Each node should have correct ranges"); + }); + QUnit.test("it should be mergable", function () { + var set = RangeSet().addKeys([0, 2, 4, 7, 8]); + var set2 = RangeSet().addKeys([1, 3, 5, 7, 9, 11]); + set.add(set2); + QUnit.equal(__spreadArray([], __read(set), false).map(function (_a) { + var from = _a.from; + return from; + }).join(','), [ + 0, + 1, + 2, + 3, + 4, + 5, + 7, + 8, + 9, + 11, + ].join(','), "successful merge of two sets"); + set.add(new RangeSet(1, 6)); + QUnit.equal(JSON.stringify(__spreadArray([], __read(set), false).map(function (_a) { + var from = _a.from, to = _a.to; + return [from, to]; + })), JSON.stringify([ + [0, 0], + [1, 6], + [7, 7], + [8, 8], + [9, 9], + [11, 11], + ]), "after adding a super range to some of the containing ranges, the rangeset should have replaced the subranges with their subset"); + set.add({ from: 0, to: 20 }); + QUnit.equal(JSON.stringify(__spreadArray([], __read(set), false).map(function (_a) { + var from = _a.from, to = _a.to; + return [from, to]; + })), JSON.stringify([[0, 20]]), "after adding a superset, the entire set should just equal the super set"); + }); + function isSequencial(set) { + var e_1, _a; + var lastFrom = -Infinity; + try { + for (var _b = __values(__spreadArray([], __read(set), false)), _c = _b.next(); !_c.done; _c = _b.next()) { + var node = _c.value; + if (node.from <= lastFrom) { + return false; + } + lastFrom = node.from; + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return true; + } + QUnit.test("stress", function () { + var set = new RangeSet(); + //console.log("depth", set.d); + for (var i = 1; i <= 600; ++i) { + set.addKey(i); + } + QUnit.ok(isSequencial(set), "set is sequencial"); + //console.log("the set 1", [...set]); + //console.log("depth", set.d); + QUnit.equal(__spreadArray([], __read(set), false).length, 600, "Set should contain individual ranges"); + QUnit.ok(isSequencial(set), "set is sequencial"); + //debugger; + set.add({ from: 280, to: 321 }); + //console.log("the set 2", JSON.parse(JSON.stringify([...set]))); + QUnit.ok(isSequencial(set), "set is sequencial"); + //console.log("depth", set.d); + QUnit.equal(__spreadArray([], __read(set), false).length, 559, "Set should have less ranges"); + //console.log("depth", set.d); + }); + var issue1268_triggering_input = [ + { from: 63, to: 71 }, + { from: 99, to: 102 }, + // (null) [99-102] + { from: 90, to: 92 }, + // [63-71] (null) + // [90-92] [90-92] + // WOW: Here both left and right leafs are the same node! + { from: 92, to: 95 }, + { from: 4, to: 10 }, + { from: 51, to: 51 }, + { from: 45, to: 46 }, + { from: 14, to: 20 }, + { from: 13, to: 20 }, + { from: 9, to: 12 }, + { from: 23, to: 25 }, + { from: 31, to: 35 }, + { from: 80, to: 88 }, + { from: 87, to: 91 }, + { from: 36, to: 37 }, + { from: 77, to: 79 } + ]; + QUnit.test("issue1268", function () { + var set = new RangeSet(); + issue1268_triggering_input.forEach(function (range, idx) { + try { + //if (idx === 11) debugger; + //console.log(`Adding [${range.from}-${range.to}]`); + set.add(range); + if (!verifySet(set)) { + QUnit.ok(false, "set not ok at idx " + idx + " depth: " + set.d); + } + else { + //console.log("Printing tree on idx " + idx); + //if (idx === 2) debugger; + //printTree([set]); + } + } + catch (e) { + console.log("crashed on idx", idx); + QUnit.ok(false, "died on idx " + idx + " with " + e); + } + }); + QUnit.ok(true, "Done"); + }); + function verifySet(set) { + var e_2, _a; + var i = issue1268_triggering_input.length + 2; + try { + for (var set_1 = __values(set), set_1_1 = set_1.next(); !set_1_1.done; set_1_1 = set_1.next()) { + var node = set_1_1.value; + if (--i === 0) + return false; + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (set_1_1 && !set_1_1.done && (_a = set_1.return)) _a.call(set_1); + } + finally { if (e_2) throw e_2.error; } + } + return true; + } + + Dexie__default["default"].test = true; // Improve code coverage + //import "./tests-performance.js"; Not required. Should make other performance tests separately instead. + +})); +//# sourceMappingURL=bundle.js.map