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